Industry Index Momentum Strategy + akshare

On a weekly basis, obtain the 5 strongest industry indices this week and make average purchases.

The data source adopts akshare.

import package

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

 Daily line to weekly line

#日线换为周线数据
def transferToWeekLine(df):
    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 = 'W'


    stock_data.set_index('date',inplace=True)

    #进行转换,周线的每个变量都等于那一周中最后一个交易日的变量值

    period_stock_data = stock_data.resample(period_type).last()

    # 周线的open等于那一周中第一个交易日的open

    period_stock_data['open'] = stock_data['close'].resample(period_type).first()

    #周线的high等于那一周中的high的最大值

    period_stock_data['high'] = stock_data['close'].resample(period_type).max()

    #周线的low等于那一周中的low的最大值

    period_stock_data['low'] = stock_data['close'].resample(period_type).min()

    #周线的volume和money等于那一周中volume和money各自的和
    
    period_stock_data['chg_pct'] = stock_data['chg_pct'].resample(period_type).sum()
    period_stock_data['volume'] = stock_data['volume'].resample(period_type).sum()

    # period_stock_data['money'] = stock_data['money'].resample(period_type,how='sum')

    #计算周线turnover

    # period_stock_data['turnover'] = period_stock_data['volume'](period_stock_data['traded_market_value']/period_stock_data['close'])

    #股票在有些周一天都没有交易,将这些周去除

    period_stock_data = period_stock_data[period_stock_data['volume'].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 Shenwan secondary industry code

#获取申万二级行业代码
sw_index_third_info_df = ak.sw_index_third_info()
sw_index_third_info_df['行业代码']=sw_index_third_info_df['行业代码'].apply(lambda x:str(x)[:6])

#Get Industry Index Quotes
#Strategy 1, intuitive representation of industry rotation phenomenon: relative strength

ind = pd.DataFrame()
for i in range(len(sw_index_third_info_df)):
    #print(sw_index_third_info_df.iloc[i,0])
    sw_index_daily_df = ak.sw_index_daily_indicator(symbol=sw_index_third_info_df.iloc[i,0], start_date="20191201", end_date="20220310",data_type='Day')
    stock_data=pd.DataFrame(transferToWeekLine(sw_index_daily_df))
    stock_data.rename(columns={0:'date',1:'code',2:'name',3:'close',4:'volume',5:'chg_pct'},inplace=True)
    stock_data=stock_data.iloc[:,:6]
    stock_data['ret'] = stock_data['chg_pct'].shift(-1)
    ind = ind.append(stock_data)

#Get the industry index of each trading week, and buy the top five, (average buy), and calculate the return of the position for one week.

ind = ind.sort_values(by='date')
last = pd.DataFrame()
l = []
for i in ind['date'].unique():
    d = ind.loc[ind['date']==i].sort_values('close',ascending=True).head(5)
    l = l+[d.ret.mean()/100] 

Draw a capital curve

pd.DataFrame(l).cumsum().plot()

 

Guess you like

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