Can fixed investment index make money ?Python Here's the answer
writing | doug

source :Python technology 「ID: pythonall」

 Can fixed investment index make money ?Python Here's the answer

Seriously affected by the epidemic , Global stock markets are falling , Even if you are always mature 、 The stable growth of the U.S. stock market is also in a series of continuous downward fusing , It's broken five times in March alone . You know, the first time in the history of U.S. stocks was 1997 year , A lot of people are falling back to understanding the night before .

Compared to the big drop in the stock market , The funds that track the market index are much smoother , Even though it's falling , But not as big as the stock market . Even Mr. Buffett once persuaded us , For individual investors , The best way to invest is to invest in index funds .

The so-called fixed investment index fund , Is to buy a fixed amount of funds on a fixed date . Compared with buying and selling stocks , Fixed investment index fund saves time and effort , You don't have to keep an eye on it all the time , Just buy once a week or a month , Young people should spend more time on their work , The best investment is to constantly improve your ability .

that , Today we're going to use the data to verify , Can fixed investment index fund make money , How much money can we make .

Grab fund website data

Many domestic websites can find the historical net value of the fund , This paper takes Tiantian fund as an example , The fund takes 「 Shanghai and Shenzhen 300 ETF」, The code is 510300.

First let's open up 510300 The net value query page of (http://fundf10.eastmoney.com/jjjz_510300.html), It can be seen that the establishment date of the fund is 2012-05-04, So far, it's almost there 8 It's about 20 years old , The fund tracks Shanghai and Shenzhen 300 Index , It can be said that it is a representative index fund .

 Can fixed investment index make money ?Python Here's the answer

Then we set the query date to 2012-05-04 To 2020-03-01, open chrome Developer panel for , Switch to Network Next , Click on 「 Inquire about 」 View network requests . We will find the following request , Confirm that the data of its response is really the fund net value data we need .

 Can fixed investment index make money ?Python Here's the answer

Requested URL as follows :

http://api.fund.eastmoney.com/f10/lsjz?callback=jQuery183024641278834999003_1585311648931&fundCode=510300&pageIndex=1&pageSize=20&startDate=2012-05-04&endDate=2020-03-01&_=1585383229681

Look closely at this request URL We found that ,fundCode This is the fund code we want to query ,pageIndex Is the current page number ,pageSize It's the number of pages ,startDate It's the start time ,endDate It's the end time .callback It doesn't work for us .

The normal logic is to get the data of the specified time period by page number , Simplicity , Here we get all the data at one time , Only need to pageSize Change to 3000 that will do , Because it hasn't been since its establishment 8 Year time , Remove the non trading days ,3000 enough .

therefore , Our crawler program can write like this . Old rules , First, introduce all the modules needed in this article .

import json
import datetime
import calendar
import requests
from pyecharts.charts import Bar
from pyecharts.charts import Line
from pyecharts import options as opts

The function to obtain the historical net value of the fund is as follows :

startDate = '2012-05-04'
endDate = '2020-03-01'
foundCode = '510300'
pageSize = 3000
header = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36',
'Referer': f'http://fundf10.eastmoney.com/jjjz_{foundCode}.html'
}
url = f'http://api.fund.eastmoney.com/f10/lsjz?&fundCode={foundCode}&pageIndex=1&pageSize={pageSize}&startDate={startDate}&endDate={endDate}&_=1585302987423'
response = requests.get(url, headers=header)
def write_file(content):
filename = f'found_{foundCode}.txt'
with open(filename, 'a') as f:
f.write(content + '\n')
write_file(response.text)

thus , We have got the basic data we need , By the way, the obtained data is written to found_510300.txt In file , Convenient follow-up operation .

Calculate the fixed investment income

With historical net worth data , We're about to start calculating the benefits .

Let's take a look at the data format we got .

{"Data":{"LSJZList":[{"FSRQ":"2020-02-28","DWJZ":"3.9313","LJJZ":"1.6026","SDATE":null,"ACTUALSYI":"","NAVTYPE":"1","JZZZL":"-3.55","SGZT":" Buy on the floor ","SHZT":" Sell on the market ","FHFCZ":"","FHFCBZ":"","DTYPE":null,"FHSP":""},
{"FSRQ":"2020-02-27","DWJZ":"4.0758","LJJZ":"1.6562","SDATE":null,"ACTUALSYI":"","NAVTYPE":"1","JZZZL":"0.30","SGZT":" Buy on the floor ","SHZT":" Sell on the market ","FHFCZ":"","FHFCBZ":"","DTYPE":null,"FHSP":""}...

One of the things that works for us is LSJZList The net value date in (FSRQ) And unit net worth (DWJZ) 了 . therefore , We need to sort out the data into the format we need , Date based key, The net value is value Put in dict Then you can .

foundCode = '510300'
fixed_investment_amount_per_week = 500 # Weekly fixed amount of investment
fixed_investment_amount_per_month = 2000 # Fixed amount of investment per month
def get_data():
with open(f'./found_{foundCode}.txt') as f:
line = f.readline()
result = json.loads(line)
found_date_price = {}
for found in result['Data']['LSJZList'][::-1]:
found_date_price[found['FSRQ']] = found['DWJZ']
return found_date_price
found_date_price = get_data()

Here we use two methods of calculation , One is Zhou dingtou , One is fixed monthly investment . The corresponding functions are calculate_found_profit_by_week(start_date, end_date, weekday) and calculate_found_profit_by_month(start_date, end_date), The parameters shared by two of these functions start_date and end_date They represent the starting date respectively , The parameters of the function of weekly returns weekday It means the fixed investment date ,weekday by 0 I'm sure I'll vote for you every week ,1 On Tuesday, it's fixed ...

The return values of the two functions are the same , They are the fixed number of shots , The ultimate holding share , Total purchase amount , Real income .

Our casting rules are as follows , When weekday Or every month 1 The number is fixed , If the day is not a trading day, it will be postponed to the next trading day , At the same time, weekly fixed investment every time buy 500 element , Every time you buy 2000 element .

calculate_found_profit_by_week function :
# Buying rules : from start_date The date starts , When weekday purchase , If weekday It's not a trading day , It will be postponed to the latest trading day
# Every time you buy 500 element , And then it's converted into a corresponding share
def calculate_found_profit_by_week(start_date, end_date, weekday):
total_stock = 0
total_amount = 0
nums = 0
day = start_date + datetime.timedelta(days=-1)
while day < end_date:
day = day + datetime.timedelta(days=1)
if day.weekday() != weekday:
continue
while found_date_price.get(day.strftime('%Y-%m-%d'), None) is None and day < end_date:
day += datetime.timedelta(days=1)
if day == end_date:
break
nums += 1
total_stock += round(fixed_investment_amount_per_week / float(found_date_price[day.strftime('%Y-%m-%d')]), 2)
total_amount += fixed_investment_amount_per_week
# Calculate the profit
while found_date_price.get(end_date.strftime('%Y-%m-%d'), None) is None:
end_date += datetime.timedelta(days=-1)
total_profit = round(total_stock, 2) * float(found_date_price[end_date.strftime('%Y-%m-%d')]) - total_amount
return nums, round(total_stock, 2), total_amount, round(total_profit)

calculate_found_profit_by_month function :

def get_first_day_of_next_month(date):
first_day = datetime.datetime(date.year, date.month, 1)
days_num = calendar.monthrange(first_day.year, first_day.month)[1] # How many days in a month
return first_day + datetime.timedelta(days=days_num)
# Buying rules : from start_date The date starts , monthly 1 Buy , If 1 No. is not a trading day , It will be postponed to the latest trading day
# Every time you buy 2000 element , And then it's converted into a corresponding share
def calculate_found_profit_by_month(start_date, end_date):
total_stock = 0
total_amount = 0
nums = 0
first_day = datetime.datetime(start_date.year, start_date.month, 1)
day = first_day + datetime.timedelta(days=-1) # Set the date to start_date Last day of last month
while day < end_date:
day = get_first_day_of_next_month(day)
while found_date_price.get(day.strftime('%Y-%m-%d'), None) is None and day < end_date:
day = day + datetime.timedelta(days=1)
if day == end_date:
break
nums += 1
total_stock += round(fixed_investment_amount_per_month / float(found_date_price[day.strftime('%Y-%m-%d')]), 2)
total_amount += fixed_investment_amount_per_month
# Calculate the profit
while found_date_price.get(end_date.strftime('%Y-%m-%d'), None) is None:
end_date += datetime.timedelta(days=-1)
total_profit = round(total_stock, 2) * float(found_date_price[end_date.strftime('%Y-%m-%d')]) - total_amount
return nums, round(total_stock, 2), total_amount, round(total_profit)

Data analysis

With net worth data , There are also fixed investment rules and concrete realization of income calculation , Let's see what our earnings are .

First of all, let's look at the trend of the fund since its establishment .

line = (
Line()
.add_xaxis(list(found_date_price.keys()))
.add_yaxis(
'',
y_axis=list(found_date_price.values()),
label_opts=opts.LabelOpts(is_show=False),
)
.set_global_opts(
title_opts=opts.TitleOpts(title=f'{foundCode} Fund trend chart '),
)
)
line.render_notebook()

 Can fixed investment index make money ?Python Here's the answer

As we can see from the picture , The fund is in 2015 Year has a very high peak , We all know why ,2015 Year is a big bull market , After the 2018 There was another small peak in the year , Later on 2019 It fell to a low in 2007 .

First of all, let's analyze , The impact of fixed investment frequency on investment results . Let's make statistics : Monday 、 Tuesday 、 Wednesday 、 Thursday 、 Friday and monthly returns .

The income function is calculated as follows , We put the total investment amount and total income of weekly fixed investment and monthly fixed investment into two lists respectively .

start_date = datetime.datetime.fromisoformat('2010-01-01')
end_date = datetime.datetime.fromisoformat('2020-03-01')
def calculate_found_profit_week_month():
total_amount = []
total_profit = []
# Zhou dingtou
for i in range(5):
result = calculate_found_profit_by_week(start_date, end_date, i)
total_amount.append(result[2])
total_profit.append(result[3])
# Monthly fixed investment
result_month = calculate_found_profit_by_month(start_date, end_date)
total_amount.append(result_month[2])
total_profit.append(result_month[3])
return total_amount, total_profit
total_amount, total_profit = calculate_found_profit_week_month()

After the investment income and the amount of investment , Let's generate a histogram to compare .

x = [' Monday ', ' Tuesday ', ' Wednesday ', ' Thursday ', ' Friday ', ' Monthly fixed investment ']
bar = (
Bar()
.add_xaxis(x)
.add_yaxis(' The amount of investment ', total_amount)
.add_yaxis(' Income from investment ', total_profit)
.set_global_opts(
title_opts=opts.TitleOpts(title=" Total investment & Income from investment "),
xaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts(is_show=True)),
yaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts(is_show=True)),
)
)
bar.render_notebook()

 Can fixed investment index make money ?Python Here's the answer

From the diagram we can see that , The amount of weekly fixed investment is basically the same , The monthly fixed investment amount is slightly less than the weekly fixed investment amount . Let's look at the yield , On Friday, the highest yield is 56263 element , And Monday is at least 56263; And the monthly fixed investment is 56784 element . In a comprehensive comparison , Just look at Zhou dingtou , The highest yield is on Friday . If the monthly fixed investment is also included in the comparison object , Then the monthly fixed investment amount is the lowest , The highest yield .

And then finally, let's see , The impact of market entry time on fixed investment income . This time we use the method of monthly fixed investment to calculate the income .

We all know 2015 Year is a big bull market , Then we choose to enter at the highest point of the stock market , Set the start time to 2015-06-10, The Shanghai composite index was at 5000+, today 2700+, The final calculated income is as follows :

start_date = datetime.datetime.fromisoformat('2015-06-10')
end_date = datetime.datetime.fromisoformat('2020-03-01')
result = calculate_found_profit_by_month(start_date, end_date)
print(result)
# Output results
(57, 31715.69, 114000, 10684)

Total fixed investment 57 Time , Amount invested 114000 element , The total income is 10684, comparison 2010-01-01 There's less access 4W element , But at least the yield is positive . And that's when the stock market goes from bull market to bear market , What we have achieved in the near future .

summary

Today we take Shanghai and Shenzhen as an example 300 ETF This paper analyzes the return of fixed investment of index fund based on the data of index fund . It can be concluded as follows :

The highest yield is on Friday , Monday is the lowest . And weekly and monthly fixed investment to compare , The yield of monthly fixed investment is higher .

At the same time, we also found that ,2010-01-01 The Shanghai index is 2900 Near the point of , Now in the 2700 Near the point of , The index doesn't go up, it goes down , But our revenue is growing . Even if you choose to enter the market at the highest point of the stock market , Lengthen the time , Index fixed investment will not lose money .

Of course , This article only does 510300 Data analysis of this fund , The data may not be comprehensive enough , Readers can get the source code from the background , Analyze more fund data , And the investment returns in different periods of time .

Warm reminder : The stock market is changing , It's not completely predictable , Be in awe of the market . This article is only for study and discussion , As no investment advice !