akshare写etf动量滚动策略

68 篇文章 14 订阅
28 篇文章 24 订阅

导入包:

import akshare as ak
import pandas as pd
import numpy as np
import matplotlib

日线换周线:

#日线换为周线数据
def transferToWeekLine(df,period='W'):
    data1=df
    stock_data = pd.DataFrame(data1)
    
    #设定转换周期period_type  转换为周是'W',月'M',季度线'Q',五分钟'5min',12天'12D'
    stock_data["date"] = pd.to_datetime(stock_data["date"])
    period_type = period

    stock_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()

  • 2
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

神出鬼没,指的就是我!

必须花钱,数据超好

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值