指數(shù)投資方式中有四種基本的方法熏版,分別是定期定額、定期不定額捍掺、不定期定額和不定期不定額撼短,這四種方式投資效果不同,對(duì)投資者的要求也不同挺勿,定期定額最簡(jiǎn)單曲横,但收益不算高,不定期不定額最復(fù)雜,對(duì)投資者的要求最高禾嫉,特別是對(duì)情緒的要求非常高灾杰,同時(shí)收益也是最好的。
在上一篇《基于Python的指數(shù)基金量化投資- 指數(shù)投資技巧(一)定期定額》中已經(jīng)介紹了定期定額的方式熙参,這里接著介紹第而種定期不定額的情況喝量化的過(guò)程艳吠。
定期不定額還是按日、按周或者按月進(jìn)行投資孽椰,但每次投資的資金不一樣昭娩,如果指數(shù)高就少買,如果指數(shù)低就多買弄屡,例如每周都會(huì)買入滬深300基金题禀,當(dāng)指數(shù)是3000的時(shí)候買入300塊,當(dāng)指數(shù)是2000的時(shí)候買入600塊膀捷,當(dāng)指數(shù)是1000的時(shí)候買入900塊迈嘹,這樣相當(dāng)于在低位買入了更多的份額,高位買入了更少的份額全庸,這樣有利于在低于積累份額秀仲,在未來(lái)會(huì)獲得更多的收益,比第一種定期定額方案會(huì)更優(yōu)壶笼。
下面通過(guò)用中證全指的數(shù)據(jù)進(jìn)行量化測(cè)試來(lái)看看具體的過(guò)程神僵。
具體的策略是下面的三個(gè)條件:
1)按周進(jìn)行投資;
2)當(dāng)估值為80%時(shí)投入400元覆劈,估值70%時(shí)投入600元保礼,估值為60%時(shí)投入800元,估值50%時(shí)投入1000元责语,估值為40%時(shí)投入1200元炮障,估值30%時(shí)投入1400元,估值為20%時(shí)投入1600元坤候,估值10%時(shí)投入1800元胁赢,估值等于0%時(shí)投入2000元。
3)當(dāng)估值高于80%時(shí)全倉(cāng)賣出白筹;
通過(guò)這種方式可以得到下面的量化結(jié)果智末。
圖中上半部分藍(lán)線是指數(shù)走勢(shì),紅點(diǎn)是按周定投的位置徒河,但是紅點(diǎn)不是一樣大的系馆,指數(shù)位置越高紅點(diǎn)越小,指數(shù)位置越低紅點(diǎn)越大顽照,表示低點(diǎn)買得多它呀,高點(diǎn)買得少。而幾個(gè)紫色的點(diǎn)表示估值高于80%賣出的位置。
下半部分的圖表示總資產(chǎn)纵穿、已投入資金和持有基金份額下隧,其中紅線時(shí)總資產(chǎn),藍(lán)線是已投入資金谓媒,橙線是持有基金份額淆院。開始階段不斷買入持有份額和總資產(chǎn)是重合的,隨著買入的增多同時(shí)指數(shù)上漲句惯,紅線橙線逐步高于藍(lán)線土辩,在2015年初左右估值高于80%則賣出,可以看見橙線變?yōu)?抢野,也就是全倉(cāng)賣出拷淘,然后紅線、藍(lán)線和橙線持續(xù)保持了一段時(shí)間的水平走勢(shì)指孤,也就是這區(qū)間沒有任何投入启涯,資產(chǎn)、資金和份額都沒有變化恃轩,接下來(lái)也有不同時(shí)期的買入和賣出结洼。
最后可以看出投入的資金是447800元,整體資產(chǎn)是666224.42叉跛,收益是48.78%松忍,比定期定額的收益高出了不少。
結(jié)果顯示定期不定額的投資效果要高于定期定額筷厘,接下來(lái)還會(huì)分享不定期定額和和不定期不定額來(lái)進(jìn)行比較鸣峭。
源碼
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import math as math
name_index = 'lxr_1000002'
name_index_g = 'g_lxr'
all_data_index =pd.read_csv('./exportfile/indexDataAll/' + name_index + '.csv')
all_data_index_g =pd.read_csv('./importfile/indexSeries/indexValuation/g/' + name_index_g +'.csv')
calc_range = 2500
calc_gap = 5
data_index_p =all_data_index['close'].values[len(all_data_index['close']) -calc_range:len(all_data_index['close']):calc_gap]
data_index_g =all_data_index_g['pe'].values[len(all_data_index_g['pe']) -calc_range:len(all_data_index_g['pe']):calc_gap]
val_percentage_list = list()
sell_flag_no_regular_no_quota = [0, 0]
sell_flag_regular_quota = 0
sell_flag_regular_no_quota = 0
sell_flag_no_regular_quota = 0
def RegularNoQuota(val_percentage,val_data_p, buy_cnt, buy_total_share):
???global sell_flag_regular_no_quota
???thd_valuation = [0.0, 0.10, 0.20, 0.30, 0.40, 0.50, 0.60, 0.70, 0.80]
???each_ratio =??? [2.0, 1.80, 1.60,1.40, 1.20, 1.00, 0.80, 0.60, 0.40]
???if val_percentage == thd_valuation[0]:
???????each_ratio_todo = each_ratio[0]
???elif thd_valuation[0] < val_percentage <= thd_valuation[1]:
???????each_ratio_todo = each_ratio[1]
???elif thd_valuation[1] < val_percentage <= thd_valuation[2]:
???????each_ratio_todo = each_ratio[2]
???elif thd_valuation[2] < val_percentage <= thd_valuation[3]:
???????each_ratio_todo = each_ratio[3]
???elif thd_valuation[3] < val_percentage <= thd_valuation[4]:
???????each_ratio_todo = each_ratio[4]
???elif thd_valuation[4] < val_percentage <= thd_valuation[5]:
???????each_ratio_todo = each_ratio[5]
???elif thd_valuation[5] < val_percentage <= thd_valuation[6]:
???????each_ratio_todo = each_ratio[6]
???elif thd_valuation[6] < val_percentage <= thd_valuation[7]:
???????each_ratio_todo = each_ratio[7]
???elif thd_valuation[7] < val_percentage <= thd_valuation[8]:
???????each_ratio_todo = each_ratio[8]
???else:
???????each_ratio_todo = 0
???if each_ratio_todo > 0:
???????sell_flag_regular_no_quota = 0
???????buy_each_regular_quota = 1000 * each_ratio_todo
???????buy_each_share = buy_each_regular_quota / val_data_p
???????buy_cnt = buy_cnt + buy_each_regular_quota
???????plot_y = val_data_p
???????plot_x = i
???????plot_flag = 1
???else:
???????if sell_flag_regular_no_quota == 0:
???????????sell_flag_regular_no_quota = 1
???????????buy_each_share = -buy_total_share
???????????buy_total_share = 0
???????????plot_y = val_data_p
???????????plot_x = i
???????????plot_flag = -1
???????else:
???????????buy_each_share = 0
???????????plot_y = val_data_p
???????????plot_x = i
???????????plot_flag = 0
???return buy_each_share, buy_cnt, [plot_flag, plot_x, plot_y],buy_total_share
gap = 5?# invest each week
cnt = 0
buy_each_share_regular_no_quota =np.zeros((len(data_index_p), 1))
buy_total_share_list_regular_no_quota =np.zeros((len(data_index_p), 1))
buy_total_money_list_regular_no_quota =np.zeros((len(data_index_p), 1))
buy_cnt_regular_no_quota = 0
plot_regular_no_quota =np.zeros((len(data_index_p), 3))
# idx_start = 974 #2011-1-4
idx_start = 1
for i in range(len(data_index_p)):
???valuation_len =all_data_index_g['pe'].values[len(all_data_index['close']) -calc_range-500:len(all_data_index['close']) - calc_range+i*calc_gap:calc_gap]
???val_loc = np.where(valuation_len < data_index_g[i])
???val_percentage = len(val_loc[0]) / (len(valuation_len))
???val_percentage_list.append(val_percentage)
???buy_each_share_regular_no_quota[i], buy_cnt_regular_no_quota,plot_regular_no_quota[i], buy_total_share_regular_no_quota\
???????= RegularNoQuota(val_percentage, data_index_p[i],buy_cnt_regular_no_quota,sum(buy_each_share_regular_no_quota))
???buy_total_share_list_regular_no_quota[i] =sum(buy_each_share_regular_no_quota) * data_index_p[i]
???buy_total_money_list_regular_no_quota[i] = buy_cnt_regular_no_quota
earn_total_money_regular_no_quota =np.zeros((len(data_index_p), 1))
money_sell_regular_no_quota = 0
for i in range(len(data_index_p)):
???if buy_each_share_regular_no_quota[i] < 0:
???????money_sell_regular_no_quota = money_sell_regular_no_quota -buy_each_share_regular_no_quota[i] * data_index_p[i]
???earn_total_money_regular_no_quota[i] =sum(buy_each_share_regular_no_quota[0:i+1]) * data_index_p[i] +money_sell_regular_no_quota
plt_gap = 10
size_title = 28
size_label = 15
size_line = 3
size_rotation = 15
size_buy_plot = 5
plt.figure()
plt.rcParams["axes.grid"] = True
plt.rcParams['font.sans-serif'] =['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams["grid.linestyle"] =(3, 5)
plt.subplot(211)
income = 100 * (earn_total_money_regular_no_quota[-1][0]- buy_total_money_list_regular_no_quota[-1][0]) /buy_total_money_list_regular_no_quota[-1][0]
plt.title('定期不定額 | 投資收益= ' + str("{:.2f}".format(income)) + '%',size=15)
# plt.plot(buy_each_share_no_regular_quota)
v_max = max(data_index_p)
v_min = min(data_index_p)
for i in range(len(plot_regular_no_quota)):
???if plot_regular_no_quota[i][0] == 1:
???????plt.plot(plot_regular_no_quota[i][1],plot_regular_no_quota[i][2],color='tomato',marker='o',ms=(size_buy_plot*v_max/plot_regular_no_quota[i][2]))
???elif plot_regular_no_quota[i][0] == -1:
???????plt.plot(plot_regular_no_quota[i][1], plot_regular_no_quota[i][2],color='purple', marker='o',ms=10)
plt.plot(data_index_p)
plt_xticks =all_data_index['date'].values[len(all_data_index['close']) -calc_range:len(all_data_index['close']):calc_gap].tolist()
plt.xticks(range(len(plt_xticks),0,-math.floor(len(plt_xticks)/plt_gap)),plt_xticks[len(plt_xticks):0:-math.floor(len(plt_xticks)/plt_gap)],rotation=size_rotation)
plt.tick_params(labelsize=size_label)
plt.subplot(212)
plt.plot(buy_total_share_list_regular_no_quota,color='tomato')
font = {'size': 15, 'color': 'tomato','weight': 'black'}
plt.text(len(buy_total_share_list_regular_no_quota),buy_total_share_list_regular_no_quota[-1][0],str("{:.2f}".format(buy_total_share_list_regular_no_quota[-1][0])),fontdict=font)
plt.plot(len(buy_total_share_list_regular_no_quota)-1,buy_total_share_list_regular_no_quota[-1][0],color='tomato', marker='o')
plt.plot(buy_total_money_list_regular_no_quota,color='cornflowerblue')
font = {'size': 15, 'color':'cornflowerblue', 'weight': 'black'}
plt.text(len(buy_total_money_list_regular_no_quota),buy_total_money_list_regular_no_quota[-1][0],str("{:.2f}".format(buy_total_money_list_regular_no_quota[-1][0])),fontdict=font)
plt.plot(len(buy_total_money_list_regular_no_quota)-1,buy_total_money_list_regular_no_quota[-1][0],color='cornflowerblue', marker='o')
plt.plot(earn_total_money_regular_no_quota,color='red')
font = {'size': 15, 'color': 'red','weight': 'black'}
plt.text(len(earn_total_money_regular_no_quota),earn_total_money_regular_no_quota[-1][0],str("{:.2f}".format(earn_total_money_regular_no_quota[-1][0])),fontdict=font)
plt.plot(len(earn_total_money_regular_no_quota)-1,earn_total_money_regular_no_quota[-1][0],color='red', marker='o')
plt_xticks =all_data_index['date'].values[len(all_data_index['close']) -calc_range:len(all_data_index['close']):calc_gap].tolist()
plt.xticks(range(len(plt_xticks),0,-math.floor(len(plt_xticks)/plt_gap)),plt_xticks[len(plt_xticks):0:-math.floor(len(plt_xticks)/plt_gap)],rotation=size_rotation)
plt.tick_params(labelsize=size_label)
plt.show()
文中用到的兩個(gè)文件鏈接: https://pan.baidu.com/s/14vRxb08jRIRPhM-_8i8W3A?pwd=iefi 提取碼: iefi
程序中用到的數(shù)據(jù)如果有問(wèn)題,大家可以留言獲取酥艳,歡迎大家一起交流溝通^_^
課程參考:網(wǎng)易云課堂? 基于Python的量化指數(shù)基金投資