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

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

作者: 小将前行 | 来源:发表于2022-06-20 14:43 被阅读0次

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

    在上一篇《基于Python的指数基金量化投资- 指数投资技巧(二)定期不定额》中已经介绍了定期不定额的方式,这里接着介绍第三种不定期定额的情况和具体的量化过程。

    不定期定额的方式和前面介绍的定期定额、定期不定额有着本质的区别,定期定额和定期不定额都是固定时间进行投资,而不定期定额投资的时间是不定的,要根据具体的指数估值进行,例如当指数的估值百分位低于某一个阈值,比如30%的时候,就会启动投资,如果一直低于该阈值,则采用类似定投的方式,按日、按周或者按月进行,一般采用按周的方式;如果估值高于该阈值则立即停止投资,直到指数估值再次落入该阈值范围内后会再次启动投资。

    这里以沪深300指数进行举例说明,当沪深300指数的估值百分位低于某个阈值,这里以30%作为例子,当低于该阈值后,则开始进行沪深300的投资,每次投入的资金是等量的,同时按周进行投入,只要沪深300当下的估值百分位不高于30%,则一直执行该操作,如果沪深300的估值百分位高于30%则停止投资。

    这种方式的好处是能在低位积累更多的筹码,让投资都集中在底部,但对投资的耐心有一定的要求,比如等待指数进行击球区,同时上涨超过该阈值后不进行追高,这两方面都是有点反人性的,所以不定期定额在实际投资过程中会比前面介绍的定期定额、定期不定额更难。

    下面通过用中证全指的数据进行量化测试来看看具体的过程。

    具体的策略是下面的三个条件:

    1)估值百分位低于30%则启动投资;

    2)投资按周进行;

    3)每次买入1000元;

    4)当估值高于80%时全仓卖出;

    通过这种方式可以得到下面的量化结果。

    图中上半部分蓝线是指数走势,红点是按估值百分位低于30%并按周投资的位置,每次投资的数额是是一样的;而几个紫色的点表示估值高于80%卖出的位置。

    下半部分的图表示总资产、已投入资金和持有基金份额,其中红线时总资产,蓝线是已投入资金,橙线是持有基金份额。开始阶段不断买入持有份额和总资产是重合的,随着买入的增多同时指数上涨,红线橙线逐步高于蓝线,当估值超过预设的门限,则投入的资金暂停,蓝线也不再增长,在2015年初左右估值高于80%则卖出,可以看见橙线变为0,也就是全仓卖出,然后红线、蓝线和橙线持续保持了一段时间的水平走势,也就是这区间没有任何投入,资产、资金和份额都没有变化,接下来在2018年左右又开始进行投资,在2020年底左右卖出。

    最后可以看出投入的资金是144000元,整体资产是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()

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

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

    相关文章

      网友评论

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

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