基于Python的指數(shù)基金量化投資 - 指數(shù)投資技巧(三)不定期定額

指數(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ù)基金投資

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末仿畸,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子朗和,更是在濱河造成了極大的恐慌错沽,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,252評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件眶拉,死亡現(xiàn)場離奇詭異千埃,居然都是意外死亡,警方通過查閱死者的電腦和手機忆植,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,886評論 3 399
  • 文/潘曉璐 我一進店門放可,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人唱逢,你說我怎么就攤上這事吴侦。” “怎么了坞古?”我有些...
    開封第一講書人閱讀 168,814評論 0 361
  • 文/不壞的土叔 我叫張陵备韧,是天一觀的道長。 經(jīng)常有香客問我痪枫,道長织堂,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,869評論 1 299
  • 正文 為了忘掉前任奶陈,我火速辦了婚禮易阳,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘吃粒。我一直安慰自己潦俺,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 68,888評論 6 398
  • 文/花漫 我一把揭開白布徐勃。 她就那樣靜靜地躺著事示,像睡著了一般。 火紅的嫁衣襯著肌膚如雪僻肖。 梳的紋絲不亂的頭發(fā)上肖爵,一...
    開封第一講書人閱讀 52,475評論 1 312
  • 那天,我揣著相機與錄音臀脏,去河邊找鬼劝堪。 笑死冀自,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的秒啦。 我是一名探鬼主播熬粗,決...
    沈念sama閱讀 41,010評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼帝蒿!你這毒婦竟也來了荐糜?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,924評論 0 277
  • 序言:老撾萬榮一對情侶失蹤葛超,失蹤者是張志新(化名)和其女友劉穎暴氏,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體绣张,經(jīng)...
    沈念sama閱讀 46,469評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡答渔,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,552評論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了侥涵。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片沼撕。...
    茶點故事閱讀 40,680評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖芜飘,靈堂內(nèi)的尸體忽然破棺而出务豺,到底是詐尸還是另有隱情,我是刑警寧澤嗦明,帶...
    沈念sama閱讀 36,362評論 5 351
  • 正文 年R本政府宣布笼沥,位于F島的核電站,受9級特大地震影響娶牌,放射性物質(zhì)發(fā)生泄漏奔浅。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,037評論 3 335
  • 文/蒙蒙 一诗良、第九天 我趴在偏房一處隱蔽的房頂上張望汹桦。 院中可真熱鬧,春花似錦鉴裹、人聲如沸舞骆。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,519評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽督禽。三九已至,卻和暖如春猖凛,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背绪穆。 一陣腳步聲響...
    開封第一講書人閱讀 33,621評論 1 274
  • 我被黑心中介騙來泰國打工辨泳, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留虱岂,地道東北人。 一個月前我還...
    沈念sama閱讀 49,099評論 3 378
  • 正文 我出身青樓菠红,卻偏偏與公主長得像第岖,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子试溯,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,691評論 2 361

推薦閱讀更多精彩內(nèi)容