以周为单位,获取本周最强的5只行业指数,进行均值购买。
数据源采用akshare。
导入包
import akshare as ak
import pandas as pd
import numpy as np
import matplotlib
日线换为周线
#日线换为周线数据
def transferToWeekLine(df):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 = 'W'stock_data.set_index('date',inplace=True)#进行转换,周线的每个变量都等于那一周中最后一个交易日的变量值period_stock_data = stock_data.resample(period_type).last()# 周线的open等于那一周中第一个交易日的openperiod_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
获取申万二级行业代码
#获取申万二级行业代码
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])
#获取行业指数行情
#策略1,行业轮动现象的直观表征:相对强弱
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)
#获取每个交易周的行业指数,并买入排名前五,(均值买入),并计算持仓一个礼拜的收益。
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]
绘制资金曲线图
pd.DataFrame(l).cumsum().plot()