失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > akshare写etf动量滚动策略

akshare写etf动量滚动策略

时间:2022-08-30 19:43:46

相关推荐

akshare写etf动量滚动策略

导入包:

import akshare as akimport pandas as pdimport numpy as npimport matplotlib

日线换周线:

#日线换为周线数据def transferToWeekLine(df,period='W'):data1=dfstock_data = pd.DataFrame(data1)#设定转换周期period_type 转换为周是'W',月'M',季度线'Q',五分钟'5min',12天'12D'stock_data["date"] = pd.to_datetime(stock_data["date"])period_type = periodstock_data.set_index('date',inplace=True)#进行转换,周线的每个变量都等于那一周中最后一个交易日的变量值period_stock_data = stock_data.resample(period_type).last()#周线的volume和money等于那一周中volume和money各自的和period_stock_data['chg_pct'] = stock_data['chg_pct'].resample(period_type).last()#股票在有些周一天都没有交易,将这些周去除period_stock_data = period_stock_data[period_stock_data['chg_pct'].notnull()]period_stock_data.reset_index(inplace=True)data = np.array(period_stock_data) #先将数据框转换为数组data_list = data.tolist() #其次转换为列表for i in data_list:i[0]=str(i[0]).split(" ")[0]return data_list

获得etf列表

#etf基本数据fund_etf_fund_daily_em_df = ak.fund_etf_fund_daily_em()print(fund_etf_fund_daily_em_df)

获取etf历史行情

#获取etf行情#策略1,etf轮动现象的直观表征:相对强弱ind = pd.DataFrame()fund_etf_fund_daily_em_df = ak.fund_etf_fund_daily_em()for i in range(len(fund_etf_fund_daily_em_df[:])):print(fund_etf_fund_daily_em_df.iloc[i,0])fund_etf_fund_info_em_df = ak.fund_etf_fund_info_em(fund=fund_etf_fund_daily_em_df.iloc[i,0], start_date="20000101", end_date="20500101")fund_etf_fund_info_em_df['code'] = fund_etf_fund_daily_em_df.iloc[i,0]fund_etf_fund_info_em_df.rename(columns={'净值日期':'date','日增长率':'chg_pct'},inplace=True)fund_etf_fund_info_em_df = pd.DataFrame(transferToWeekLine(fund_etf_fund_info_em_df,'W'))fund_etf_fund_info_em_df.rename(columns={0:'date',3:'chg_pct',6:'code'},inplace=True)fund_etf_fund_info_em_df = fund_etf_fund_info_em_df[['date','chg_pct','code']]fund_etf_fund_info_em_df['ret'] = fund_etf_fund_info_em_df['chg_pct'].shift(-1)ind = ind.append(fund_etf_fund_info_em_df)

绘图:

ind = ind.sort_values(by='date')last = pd.DataFrame()l = []#获取每个交易周的行业指数,并买入排名前五,(均值买入),并计算持仓一个礼拜的收益。for i in ind['date'].unique():d = ind.loc[ind['date']==i].sort_values('chg_pct',ascending=True).head(20)l = (l+[d.ret.mean()/100])pd.DataFrame(l).cumsum().plot()

如果觉得《akshare写etf动量滚动策略》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。