指數(shù)投資方式中有四種基本的方法切蟋,分別是定期定額统捶、定期不定額、不定期定額和不定期不定額,這四種方式投資效果不同喘鸟,對投資者的要求也不同匆绣,定期定額最簡單,但收益不算高什黑,不定期不定額最復(fù)雜崎淳,對投資者的要求最高,特別是對情緒的要求非常高愕把,同時收益也是最好的拣凹。
在上一篇《基于Python的指數(shù)基金量化投資- 指數(shù)投資技巧(二)定期不定額》中已經(jīng)介紹了定期不定額的方式,這里接著介紹第三種不定期定額的情況和具體的量化過程礼华。
不定期定額的方式和前面介紹的定期定額咐鹤、定期不定額有著本質(zhì)的區(qū)別,定期定額和定期不定額都是固定時間進行投資圣絮,而不定期定額投資的時間是不定的祈惶,要根據(jù)具體的指數(shù)估值進行,例如當(dāng)指數(shù)的估值百分位低于某一個閾值扮匠,比如30%的時候捧请,就會啟動投資,如果一直低于該閾值棒搜,則采用類似定投的方式疹蛉,按日、按周或者按月進行力麸,一般采用按周的方式可款;如果估值高于該閾值則立即停止投資,直到指數(shù)估值再次落入該閾值范圍內(nèi)后會再次啟動投資克蚂。
這里以滬深300指數(shù)進行舉例說明闺鲸,當(dāng)滬深300指數(shù)的估值百分位低于某個閾值,這里以30%作為例子埃叭,當(dāng)?shù)陀谠撻撝岛竺校瑒t開始進行滬深300的投資,每次投入的資金是等量的赤屋,同時按周進行投入立镶,只要滬深300當(dāng)下的估值百分位不高于30%,則一直執(zhí)行該操作类早,如果滬深300的估值百分位高于30%則停止投資媚媒。
這種方式的好處是能在低位積累更多的籌碼,讓投資都集中在底部涩僻,但對投資的耐心有一定的要求欣范,比如等待指數(shù)進行擊球區(qū)变泄,同時上漲超過該閾值后不進行追高,這兩方面都是有點反人性的恼琼,所以不定期定額在實際投資過程中會比前面介紹的定期定額妨蛹、定期不定額更難。
下面通過用中證全指的數(shù)據(jù)進行量化測試來看看具體的過程晴竞。
具體的策略是下面的三個條件:
1)估值百分位低于30%則啟動投資蛙卤;
2)投資按周進行;
3)每次買入1000元噩死;
4)當(dāng)估值高于80%時全倉賣出颤难;
通過這種方式可以得到下面的量化結(jié)果。
圖中上半部分藍線是指數(shù)走勢已维,紅點是按估值百分位低于30%并按周投資的位置行嗤,每次投資的數(shù)額是是一樣的;而幾個紫色的點表示估值高于80%賣出的位置垛耳。
下半部分的圖表示總資產(chǎn)栅屏、已投入資金和持有基金份額,其中紅線時總資產(chǎn)堂鲜,藍線是已投入資金栈雳,橙線是持有基金份額。開始階段不斷買入持有份額和總資產(chǎn)是重合的缔莲,隨著買入的增多同時指數(shù)上漲哥纫,紅線橙線逐步高于藍線,當(dāng)估值超過預(yù)設(shè)的門限痴奏,則投入的資金暫停蛀骇,藍線也不再增長,在2015年初左右估值高于80%則賣出读拆,可以看見橙線變?yōu)?松靡,也就是全倉賣出,然后紅線建椰、藍線和橙線持續(xù)保持了一段時間的水平走勢,也就是這區(qū)間沒有任何投入岛马,資產(chǎn)棉姐、資金和份額都沒有變化,接下來在2018年左右又開始進行投資啦逆,在2020年底左右賣出伞矩。
最后可以看出投入的資金是144000元,整體資產(chǎn)是25148.39夏志,收益是74.62%乃坤,比定期定額和定期不定額的收益高出了不少。
在接下來最后一篇的不定期不定額會和大家分享最后一種投資方式,這種方式的投資效果最好湿诊,但也最考驗投資者狱杰。
源碼
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_quota = 0
def NoRegularQuota(val_percentage,val_data_p, buy_cnt, buy_total_share):
???global sell_flag_no_regular_quota
???if val_percentage <= 0.3:
???????sell_flag_no_regular_quota = 0
???????buy_each_no_regular_quota = 1000
???????buy_each_share = buy_each_no_regular_quota / val_data_p
???????buy_total_share = buy_total_share + buy_each_share
???????buy_cnt = buy_cnt + 1
???????plot_y = val_data_p
???????plot_x = i
???????plot_flag = 1
???elif val_percentage >= 0.8 and sell_flag_no_regular_quota == 0:
???????sell_flag_no_regular_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_no_regular_quota =np.zeros((len(data_index_p), 1))
buy_total_share_list_no_regular_quota =np.zeros((len(data_index_p), 1))
buy_total_money_list_no_regular_quota =np.zeros((len(data_index_p), 1))
buy_cnt_no_regular_quota = 0
plot_no_regular_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_no_regular_quota = 1000
???buy_each_share_no_regular_quota[i], buy_cnt_no_regular_quota,plot_no_regular_quota[i], buy_total_share_no_regular_quota\
???????= NoRegularQuota(val_percentage,data_index_p[i],buy_cnt_no_regular_quota, sum(buy_each_share_no_regular_quota))
???buy_total_share_list_no_regular_quota[i] =sum(buy_each_share_no_regular_quota) * data_index_p[i]
???buy_total_money_list_no_regular_quota[i] = buy_cnt_no_regular_quota *buy_each_no_regular_quota
earn_total_money_no_regular_quota =np.zeros((len(data_index_p), 1))
money_sell_no_regular_quota = 0
for i in range(len(data_index_p)):
???if buy_each_share_no_regular_quota[i] < 0:
???????money_sell_no_regular_quota = money_sell_no_regular_quota -buy_each_share_no_regular_quota[i] * data_index_p[i]
???earn_total_money_no_regular_quota[i] =sum(buy_each_share_no_regular_quota[0:i+1]) * data_index_p[i] +money_sell_no_regular_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_no_regular_quota[-1][0] - buy_total_money_list_no_regular_quota[-1][0])/ buy_total_money_list_no_regular_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_no_regular_quota)):
???if plot_no_regular_quota[i][0] == 1:
???????plt.plot(plot_no_regular_quota[i][1],plot_no_regular_quota[i][2],color='tomato',marker='o',ms=(size_buy_plot*v_max/plot_no_regular_quota[i][2]))
???elif plot_no_regular_quota[i][0] == -1:
???????plt.plot(plot_no_regular_quota[i][1], plot_no_regular_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_no_regular_quota,color='tomato')
font = {'size': 15, 'color': 'tomato','weight': 'black'}
plt.text(len(buy_total_share_list_no_regular_quota),buy_total_share_list_no_regular_quota[-1][0],str("{:.2f}".format(buy_total_share_list_no_regular_quota[-1][0])),fontdict=font)
plt.plot(len(buy_total_share_list_no_regular_quota)-1,buy_total_share_list_no_regular_quota[-1][0],color='tomato', marker='o')
plt.plot(buy_total_money_list_no_regular_quota,color='cornflowerblue')
font = {'size': 15, 'color':'cornflowerblue', 'weight': 'black'}
plt.text(len(buy_total_money_list_no_regular_quota),buy_total_money_list_no_regular_quota[-1][0],str("{:.2f}".format(buy_total_money_list_no_regular_quota[-1][0])),fontdict=font)
plt.plot(len(buy_total_money_list_no_regular_quota)-1,buy_total_money_list_no_regular_quota[-1][0],color='cornflowerblue', marker='o')
plt.plot(earn_total_money_no_regular_quota,color='red')
font = {'size': 15, 'color': 'red','weight': 'black'}
plt.text(len(earn_total_money_no_regular_quota),earn_total_money_no_regular_quota[-1][0],str("{:.2f}".format(earn_total_money_no_regular_quota[-1][0])),fontdict=font)
plt.plot(len(earn_total_money_no_regular_quota)-1,earn_total_money_no_regular_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()
程序中用到的數(shù)據(jù)如果有問題,大家可以留言獲取厅须,歡迎大家一起交流溝通^_^
課程參考:網(wǎng)易云課堂? 基于Python的量化指數(shù)基金投資