赞
踩
用python实现双均线模型,总共分为三步。
第一步:数据的获取。
通达信终端、新浪财经数据接口、经纪商的交易软件都能导出数据。
本次以中证1000指数的日线收盘数据为例。
使用第三方库pandas读取数据
数据文件如下图:
'''
作者:Leo
微信:470770753
完整教程:https://item.taobao.com/item.htm?spm=a230r.1.14.96.79c91aa8quZLX1&id=693510318381&ns=1&abbucket=16#detail
'''
import pandas as pd
file_name=’xxx.xls’
dataframe = pd.read_excel(file_name, header=0)
print(dataframe )
在使用pandas打开excel如果遇到如下报错安装xrld三方库即可
第二步:数据可视化。
使用matplotlib三方库做数据可视化。
画线
import matplotlib.pyplot as plt
list= [6, 2, 13, 10]
plt.plot(list)
plt.show()
双坐标
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(list1)
ax2.plot(list2)
plt.show()
画点
import matplotlib.pyplot as plt
plt.scatter(x, y, s=10, c='red', marker='s')
第三步:实现双均线模型,并做简单的交易信号标记记录分析。
import pandas as pd import matplotlib.pyplot as plt import numpy as np file_name='data.xls' dataframe = pd.read_excel(file_name, header=0) close_data=dataframe['close'] close_list=list(close_data) #计算双均线 arg1=10 arg2=20 data_list=[] ma1_list=[] ma2_list=[] open_price=None profit_list=[0] #将数据模拟成逐个回放 for close in close_list: data_list.append(close) if len(data_list)>=arg2: #用numpy来计算均值,mean() av1=np.mean(data_list[-arg1:]) av2 = np.mean(data_list[-arg2:]) ma1_list.append(av1) ma2_list.append(av2) #计算收益 if open_price==None: profit_list.append(profit_list[-1]) else: profit=profit_list[-1]+close-data_list[-2] profit_list.append(profit) if len(ma1_list) > 1 and len(ma2_list) > 1: #当金叉,开仓 if ma1_list[-1]>ma2_list[-1] and ma1_list[-2]<ma2_list[-2]: open_price=close #当死叉,平仓 if ma1_list[-1] < ma2_list[-1] and ma1_list[-2] > ma2_list[-2]: open_price=None # plt.plot(close_list) # plt.plot(ma1_list) # plt.plot(ma2_list) # plt.plot(profit_list) fig, ax1 = plt.subplots() ax2 = ax1.twinx() ax1.plot(close_list) ax1.plot(ma1_list) ax1.plot(ma2_list) ax2.plot(profit_list,color='red') plt.show()
最终实现的结果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。