akshare writes ETF momentum rolling strategy

import package:

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

Daily line change:

#日线换为周线数据
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

get a list of ETFs

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

Get ETF historical quotes

#获取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)

Drawing: 

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324322917&siteId=291194637