美文网首页
基于Python的指数基金量化投资 - 指数投资技巧(二)定期不

基于Python的指数基金量化投资 - 指数投资技巧(二)定期不

作者: 小将前行 | 来源:发表于2022-06-13 17:37 被阅读0次

指数投资方式中有四种基本的方法,分别是定期定额、定期不定额、不定期定额和不定期不定额,这四种方式投资效果不同,对投资者的要求也不同,定期定额最简单,但收益不算高,不定期不定额最复杂,对投资者的要求最高,特别是对情绪的要求非常高,同时收益也是最好的。

在上一篇《基于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 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()

文中用到的两个文件链接: https://pan.baidu.com/s/14vRxb08jRIRPhM-_8i8W3A?pwd=iefi 提取码: iefi

程序中用到的数据如果有问题,大家可以留言获取,欢迎大家一起交流沟通^_^

课程参考:网易云课堂  基于Python的量化指数基金投资

相关文章

网友评论

      本文标题:基于Python的指数基金量化投资 - 指数投资技巧(二)定期不

      本文链接:https://www.haomeiwen.com/subject/vquomrtx.html