群友說,行業指數不行,沒辦法跟買。這次我換成了etf進行動量策略,選擇本周上漲最強的5個etf,平均持倉,一周后移倉。查看回測效果。
? ? ? ? 不廢話,上傳代碼,但還是有點毛糙。下次加上日期這些數據,做成df格式,然后用pyfolio進行查看。
導包:
import akshare as ak
import pandas as pd
import numpy as np
import 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()period_stock_data['chg_pct'] = stock_data['chg_pct'].resample(period_type).last()#計算周線turnoverperiod_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
獲取公募數據
#公募基本數據
fund_name_em_df = ak.fund_name_em()
print(fund_name_em_df)#獲取公募凈值歷史行情
#策略1,公募輪動現象的直觀表征:相對強弱
ind = pd.DataFrame()fund_name_em_df = fund_open_fund_daily_em_df
for i in range(len(fund_name_em_df[:])):print(fund_name_em_df.iloc[i,0])sw_index_daily_df = ak.fund_open_fund_info_em(fund=fund_name_em_df.iloc[i,0], indicator="累計收益率走勢")sw_index_daily_df['code'] = fund_name_em_df.iloc[i,0]sw_index_daily_df.rename(columns={'凈值日期':'date','累計收益率':'chg_pct'},inplace=True)sw_index_daily_df = pd.DataFrame(transferToWeekLine(fund_open_fund_info_em_df,'W'))sw_index_daily_df.rename(columns={0:'date',1:'chg_pct'},inplace=True)#print(sw_index_daily_df.head())# 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]sw_index_daily_df['ret'] = sw_index_daily_df['chg_pct'].shift(-1)ind = ind.append(sw_index_daily_df)
計算每周凈值:
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()