python移动均线SMA及双均线策略
程序员文章站
2022-07-08 20:35:07
import pandas as pdimport numpy as npimport tushare as tsimport seabornimport matplotlib.pyplot as plotimport matplotlib as mplmpl.rcParams['font.sans-serif'] = ['SimHei'] # 设置matplotlib可以显示汉语mpl.rcParams['axes.unicode_minus'] = False#pd.set_opti...
import pandas as pd
import numpy as np
import tushare as ts
import seaborn
import matplotlib.pyplot as plot
import matplotlib as mpl
mpl.rcParams['font.sans-serif'] = ['SimHei'] # 设置matplotlib可以显示汉语
mpl.rcParams['axes.unicode_minus'] = False
#pd.set_option()就是pycharm输出控制显示的设置
pd.set_option('expand_frame_repr', False)#True就是可以换行显示。设置成False的时候不允许换行
pd.set_option('display.max_columns', None)# 显示所有列
#pd.set_option('display.max_rows', None)# 显示所有行
pd.set_option('colheader_justify', 'centre')# 显示居中
pro = ts.pro_api('a468c82b71012ef13de5af7d92d1494c97c19a334fecd5cfb9388318')
data = pro.daily(ts_code='000001.SZ', start_date='20180101', end_date='20190101')
#print(data.head())
data.set_index('trade_date',inplace=True) #设置索引覆盖原来的数据
print(data.head())
data['SMA_20'] = data['close'].rolling(20).mean() #简单移动平均线计算
data['SMA_60'] = data['close'].rolling(60).mean()
data[['close', 'SMA_20', 'SMA_60']].plot(figsize=(10, 6)) #画图
plot.show()
#计算股票收益,有两种计算收益率方法:1.离散收益率 2.连续收益率
data['position'] = np.where(data['SMA_20'] > data['SMA_60'], 1, -1) #当20日均线大于60日均线时记录1,反之记录-1
data['returns'] = np.log(data['close']/data['close'].shift(1)) #连续收益率计算
#data['returns_dis'] = data['close']/data['close'].shift(1) - 1 #离散收益率计算
data['strategy'] = data['position'].shift(1)*data['returns']
data['returns'].cumsum().apply(np.exp).plot(figsize=(10, 6)) #计算累计收益并输出图,np.exp方法返回x的指数
plot.show()
data['returns'].hist(bins=50) #绘制直方图
plot.show()
本文地址:https://blog.csdn.net/Wilburzzz/article/details/107636928
上一篇: 男性冬天喝什么粥好 这7款粥养生