pandas_datareader 和 tushare 差不多,就是导入的包不同,提取数据的函数不同,Close要大写C。
import numpy as np
import pandas as pd
import pandas_datareader.data as web
import matplotlib.pyplot as plt
# symbol = ['BABA','BIDU','MSFT']
data = web.get_data_yahoo('BABA',start = '7/20/2019',end = '7/20/2020')
# code0 = web.get_data_yahoo(symbol,start = '1/1/2020',end = '6/6/2020')
data.info()
data['MA5'] = data['Close'].rolling(5).mean()
data['MA10'] = data['Close'].rolling(10).mean()
data['MA20'] = data['Close'].rolling(20).mean()
data[['Close','MA5','MA10','MA20']].plot(figsize = (15,7))
plt.grid(True)
datas = data[['Close','MA5','MA10','MA20']].dropna()
datas['MA5-MA20'] = datas['MA5']-datas['MA20']
datas.describe()
SD = -1.3
#生成交易信号
datas['signal'] = np.where(datas['MA5-MA20'] < SD,1,0)
datas['signal'] = np.where(datas['MA5-MA20'] > -SD,-1,datas['signal'])
#计算收益率 算数收益率 对数收益率
datas['return'] = (datas['Close']-datas['Close'].shift(1))/datas['Close'].shift(1)
#累积收益率
datas['stra_re'] = datas['signal'].shift(1) * datas['return']
datas[['return','stra_re']].cumsum().plot(figsize = (15,7))
plt.grid(True)
还不太清楚这个参数和交易信号是怎么回事。。。
datas['stra_sum'] = datas['stra_re'].cumsum()
print(datas['stra_sum'].describe())
看最后的数据,没有亏损。