栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

用金交所Au(T+D)及Ag(T+D)均价预测Au(T+D)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

用金交所Au(T+D)及Ag(T+D)均价预测Au(T+D)

import time
import datetime
import akshare as ak

print('本程序纯为python学习用途,不构成投资建议,部分参考的CSDN代码如下: ')
print('https://blog.csdn.net/Python4857/article/details/122562812')

time.sleep(1)
print('欢迎使用小u的致富之道!今天来看看黄金有没有什么机会呢~')
time.sleep(1)
print('先来介绍个小概念,由于金银都具有投资属性、白银还有更多的工业属性,长期以来金价对银价比例是维持在一定范围的')
print('个人感觉,比如当金银比较小,可以做多黄金,做空白银,金银比较大,可以做空黄金,做多白银')
print('盈利方式是认为最终金银比会回归一个正常水平,因此白银价格对金价有一定关联')
time.sleep(3)
print('数据库为akshare,数据/投资标的为上海黄金交易所Au(T+D)')
time.sleep(1)


# LinearRegression 是一个用于线性回归的机器学习库
from sklearn.linear_model import LinearRegression

# pandas 和 numpy 用于数据操作
import pandas as pd
import numpy as np

# matplotlib 和 seaborn 用于绘制图形
import matplotlib.pyplot as plt
plt.show()
plt.style.use('seaborn-darkgrid')

file_name = input('相关数据所保存之excel文件命名为: ')
file_name = file_name + '.xlsx'
print('您的相关数据所保存之excel将命名为:')
print(file_name)
now_time = datetime.datetime.now().strftime('%Y-%m-%d')
print('此文件产生时间:')
print(now_time)
selfinfo = {'属性': ['文件时间', '文件类型','策略方法','特别提示'], '具体描述': [now_time, '致富之道','基于金银比用白银预测黄金价格','有较大亏损可能']}
selfinfo = pd.DataFrame(data=selfinfo)
selfinfo.to_excel(file_name,sheet_name='文件信息')

from openpyxl import load_workbook
writer = pd.ExcelWriter(file_name, engine='openpyxl')
book = load_workbook(writer.path)
writer.book = book

price_hist_df_Au = ak.spot_hist_sge(symbol='Au(T+D)')
price_hist_df_Ag = ak.spot_hist_sge(symbol='Ag(T+D)')

while True:
    price_hist_df_print = input('是否需要现在就看原始历史价格?Y/N').upper()
    if price_hist_df_print == 'Y':
        print('黄金历史价格为:')
        print(price_hist_df_Au)
        print('白银历史价格为:')
        print(price_hist_df_Ag)
        break
    elif price_hist_df_print == 'N':
        break
    else:
        print('小u不知道你在说啥')
        continue


while True:
    price_hist_df_xlsx = input('是否需要将历史价格保存至excel中?Y/N').upper()
    if price_hist_df_xlsx == 'Y':
        price_hist_df_Au.to_excel(excel_writer=writer, sheet_name='金交所Au(T+D)历史价格')
        writer.save()
        price_hist_df_Ag.to_excel(excel_writer=writer, sheet_name='金交所Ag(T+D)历史价格')
        writer.save()
        print('小u确认原始数据已经导入至excel中啦~')
        break
    elif price_hist_df_xlsx == 'N':
        break
    else:
        print('小u不知道你在说啥')
        continue

# type()格式均为 
sdate_Au = price_hist_df_Au['date'].min()
edate_Au = price_hist_df_Au['date'].max()
sdate_Ag = price_hist_df_Ag['date'].min()
edate_Ag = price_hist_df_Ag['date'].max()

# type()格式为
delta_Au = edate_Au-sdate_Au
delta_Ag = edate_Ag-sdate_Ag

dateinfo = {'属性': ['金价数据-起始', '银价数据-起始','金价数据-终止','银价数据-终止','金价数据-天数','银价数据-天数'], '日期': [sdate_Au, sdate_Ag,edate_Au,edate_Ag,delta_Au,delta_Ag]}
dateinfo = pd.DataFrame(dateinfo)
print('数据的起始及终止日期如下:')
time.sleep(1)
print(dateinfo)


for i in range(1,delta_Au.days+1):
    date_Au = (edate_Au-datetime.timedelta(days=i))
    if(date_Au not in price_hist_df_Au['date'].values):
        new_date_Au = pd.DataFrame(data={'date':date_Au,'value':-1},index=[price_hist_df_Au.shape[0]])
        price_hist_df_Au = price_hist_df_Au.append(new_date_Au,ignore_index=True)

# 按照日期列排序
price_hist_df_Au = price_hist_df_Au.sort_values('date').reset_index(drop=True)
# 填充缺失数据
price_hist_df_Au.ffill(axis=0, inplace=True)
price_hist_df_Au.drop('value',axis=1,inplace=True)
price_hist_df_Au.set_index('date',inplace=True)
price_hist_df_Au.to_excel(excel_writer=writer, sheet_name='金交所Au(T+D)价格adj.')
writer.save()


while True:
    price_hist_df_print = input('是否需要现在就看整理后金价数据?Y/N').upper()
    if price_hist_df_print == 'Y':
        print('考虑到有节假日休市,模型默认其价格与前一交易日相一致,整理后金价数据如下:')
        print(price_hist_df_Au)
        break
    elif price_hist_df_print == 'N':
        break
    else:
        print('小u不知道你在说啥')
        continue





for i in range(1,delta_Ag.days+1):
    date_Ag = (edate_Ag-datetime.timedelta(days=i))
    if(date_Ag not in price_hist_df_Ag['date'].values):
        new_date_Ag = pd.DataFrame(data={'date':date_Ag,'value':-1},index=[price_hist_df_Ag.shape[0]])
        price_hist_df_Ag = price_hist_df_Ag.append(new_date_Ag,ignore_index=True)

# 按照日期列排序
price_hist_df_Ag = price_hist_df_Ag.sort_values('date').reset_index(drop=True)
# 填充缺失数据
price_hist_df_Ag.ffill(axis=0, inplace=True)
price_hist_df_Ag.drop('value',axis=1,inplace=True)
price_hist_df_Ag.set_index('date',inplace=True)
price_hist_df_Ag.to_excel(excel_writer=writer, sheet_name='金交所Ag(T+D)价格adj.')
writer.save()

while True:
    price_hist_df_print = input('是否需要现在就看整理后金价数据?Y/N').upper()
    if price_hist_df_print == 'Y':
        print('考虑到有节假日休市,模型默认其价格与前一交易日相一致,整理后银价数据如下:')
        print(price_hist_df_Ag)
        break
    elif price_hist_df_print == 'N':
        break
    else:
        print('小u不知道你在说啥')
        continue

price_hist_close_df_Au_Ag=pd.concat([price_hist_df_Au.close,price_hist_df_Ag.close],axis=1,keys=['Au(T+D)','Ag(T+D)'])
price_hist_close_df_Au_Ag_gs=price_hist_close_df_Au_Ag['Au(T+D)']/price_hist_close_df_Au_Ag['Ag(T+D)']*1000

while True:
    price_hist_df_print = input('是否需要现在就看金银比数据?Y/N').upper()
    if price_hist_df_print == 'Y':
        print('金银比数据如下,已转为1g黄金对1g白银的比例:')
        print(price_hist_close_df_Au_Ag_gs)
        break
    elif price_hist_df_print == 'N':
        break
    else:
        print('小u不知道你在说啥')
        continue

price_hist_close_df_Au_Ag_gs.to_excel(excel_writer=writer, sheet_name='金银比')
writer.save()

print('金银比绘图如下: ')
price_hist_close_df_Au_Ag_gs.plot(figsize=(10, 7), color='r')
plt.ylabel("SHANGHAI GOLD EXCHANGE Au(T+D)/Ag(T+D) Prices")
plt.title("SHANGHAI GOLD EXCHANGE Au(T+D)/Ag(T+D) Prices Series")
plt.show()

pending=input('输入任意键继续')

Au_x1=int(input('x1:输入想选择多少天的平均金价'))
Ag_x2=int(input('x2:输入想选择多少天的平均银价'))

price_hist_close_df_Au_Ag['Au_x1'] = price_hist_close_df_Au_Ag['Au(T+D)'].rolling(window=Au_x1).mean()
price_hist_close_df_Au_Ag['Ag_x2'] = price_hist_close_df_Au_Ag['Ag(T+D)'].rolling(window=Ag_x2).mean()/1000
price_hist_close_df_Au_Ag['next_day_price'] = price_hist_close_df_Au_Ag['Au(T+D)'].shift(-1)
price_hist_close_df_Au_Ag = price_hist_close_df_Au_Ag.dropna()
#print(price_hist_close_df_Au_Ag)

X = price_hist_close_df_Au_Ag[['Au_x1', 'Ag_x2']]
y = price_hist_close_df_Au_Ag['next_day_price']

t = .8
t = int(t*len(price_hist_close_df_Au_Ag))
XX_train = X[:t]
yy_train = y[:t]
XX_test = X[t:]
yy_test = y[t:]

linear = LinearRegression().fit(XX_train, yy_train)
print("Linear Regression model")
print("Au(T+D) Prices (y) = %.2f *  Moving Average Ag(T+D) Price (X1) 
+ %.2f *  Moving Average Ag(T+D) Price (X2) 
+ %.2f (constant)" % (linear.coef_[0], linear.coef_[1], linear.intercept_))

predicted_price = linear.predict(XX_test)
predicted_price = pd.DataFrame(
    predicted_price, index=yy_test.index, columns=['price'])
predicted_price.plot(figsize=(10, 7))
yy_test.plot()
plt.legend(['predicted_price', 'actual_price'])
plt.ylabel("SHANGHAI GOLD EXCHANGE Au(T+D) Prices")
plt.show()

r2_score = linear.score(X[t:], y[t:])*100
float("{0:.2f}".format(r2_score))
print('该模型的拟合优度为: ')
print(r2_score)

gold = pd.DataFrame()
gold['price'] = price_hist_close_df_Au_Ag[t:]['Au(T+D)']
gold['predicted_price_next_day'] = predicted_price
gold['actual_price_next_day'] = yy_test
gold['gold_returns'] = gold['price'].pct_change().shift(-1)
gold['signal'] = np.where(gold.predicted_price_next_day.shift(1) < gold.predicted_price_next_day,1,0)
gold['strategy_returns'] = gold.signal * gold['gold_returns']
((gold['strategy_returns']+1).cumprod()).plot(figsize=(10,7),color='g')
plt.ylabel('Cumulative Returns')
plt.show()


data = price_hist_close_df_Au_Ag
data['Au_x1'] = data['Au(T+D)'].rolling(window=Au_x1).mean()
data['Ag_x2'] = data['Ag(T+D)'].rolling(window=Ag_x2).mean()/1000
data = data.dropna()
data['predicted_gold_price'] = linear.predict(data[['Au_x1', 'Ag_x2']])
data['signal'] = np.where(data.predicted_gold_price.shift(1) < data.predicted_gold_price,"Buy","No Position")
suggestion = data.tail(1)[['signal','predicted_gold_price']].T
print(suggestion)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/969257.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号