基于Python的指数基金量化投资 - 指数投资技巧(二)定期不定额
指數投資方式中有四種基本的方法,分別是定期定額、定期不定額、不定期定額和不定期不定額,這四種方式投資效果不同,對投資者的要求也不同,定期定額最簡單,但收益不算高,不定期不定額最復雜,對投資者的要求最高,特別是對情緒的要求非常高,同時收益也是最好的。
在上一篇《基于Python的指數基金量化投資- 指數投資技巧(一)定期定額》中已經介紹了定期定額的方式,這里接著介紹第而種定期不定額的情況喝量化的過程。
定期不定額還是按日、按周或者按月進行投資,但每次投資的資金不一樣,如果指數高就少買,如果指數低就多買,例如每周都會買入滬深300基金,當指數是3000的時候買入300塊,當指數是2000的時候買入600塊,當指數是1000的時候買入900塊,這樣相當于在低位買入了更多的份額,高位買入了更少的份額,這樣有利于在低于積累份額,在未來會獲得更多的收益,比第一種定期定額方案會更優。
下面通過用中證全指的數據進行量化測試來看看具體的過程。
具體的策略是下面的三個條件:
1)按周進行投資;
2)當估值為80%時投入400元,估值70%時投入600元,估值為60%時投入800元,估值50%時投入1000元,估值為40%時投入1200元,估值30%時投入1400元,估值為20%時投入1600元,估值10%時投入1800元,估值等于0%時投入2000元。
3)當估值高于80%時全倉賣出;
通過這種方式可以得到下面的量化結果。
圖中上半部分藍線是指數走勢,紅點是按周定投的位置,但是紅點不是一樣大的,指數位置越高紅點越小,指數位置越低紅點越大,表示低點買得多,高點買得少。而幾個紫色的點表示估值高于80%賣出的位置。
下半部分的圖表示總資產、已投入資金和持有基金份額,其中紅線時總資產,藍線是已投入資金,橙線是持有基金份額。開始階段不斷買入持有份額和總資產是重合的,隨著買入的增多同時指數上漲,紅線橙線逐步高于藍線,在2015年初左右估值高于80%則賣出,可以看見橙線變為0,也就是全倉賣出,然后紅線、藍線和橙線持續保持了一段時間的水平走勢,也就是這區間沒有任何投入,資產、資金和份額都沒有變化,接下來也有不同時期的買入和賣出。
最后可以看出投入的資金是447800元,整體資產是666224.42,收益是48.78%,比定期定額的收益高出了不少。
結果顯示定期不定額的投資效果要高于定期定額,接下來還會分享不定期定額和和不定期不定額來進行比較。
源碼
import pandas as pd import numpy as np import matplotlib.pyplot as plt import math as mathname_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 = 0def RegularNoQuota(val_percentage, val_data_p, buy_cnt, buy_total_share):global sell_flag_regular_no_quotathd_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 = 0if each_ratio_todo > 0:sell_flag_regular_no_quota = 0buy_each_regular_quota = 1000 * each_ratio_todobuy_each_share = buy_each_regular_quota / val_data_pbuy_cnt = buy_cnt + buy_each_regular_quotaplot_y = val_data_pplot_x = iplot_flag = 1else:if sell_flag_regular_no_quota == 0:sell_flag_regular_no_quota = 1buy_each_share = -buy_total_sharebuy_total_share = 0plot_y = val_data_pplot_x = iplot_flag = -1else:buy_each_share = 0plot_y = val_data_pplot_x = iplot_flag = 0return buy_each_share, buy_cnt, [plot_flag, plot_x, plot_y], buy_total_sharegap = 5 # invest each week cnt = 0buy_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_quotaearn_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_quotaplt_gap = 10 size_title = 28 size_label = 15 size_line = 3 size_rotation = 15 size_buy_plot = 5plt.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()文中用到的兩個文件下載鏈接: https://pan.baidu.com/s/14vRxb08jRIRPhM-_8i8W3A?pwd=iefi
提取碼: iefi
程序中用到的數據如果有問題,大家可以留言獲取也可以添加小將前行的微信xjqx_666進行獲取,歡迎大家一起交流溝通
課程參考:基于Python的量化指數基金投資
總結
以上是生活随笔為你收集整理的基于Python的指数基金量化投资 - 指数投资技巧(二)定期不定额的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CAPL脚本如何实现TCP Socket
- 下一篇: 超强OCR文字识别软件 图像文字识别软件