11import json
22import datetime
33import calendar
4- import matplotlib . pyplot as plt
5- from matplotlib import font_manager
6- import numpy as np
4+ from pyecharts . charts import Bar
5+ from pyecharts . charts import Line
6+ from pyecharts import options as opts
77
88foundCode = '510300'
9- file = f'./found_{ foundCode } .txt'
10- found_date_price = {}
11- found_price_x = []
12- found_price_y = []
9+ fixed_investment_amount_per_week = 500 # 每周定投金额
10+ fixed_investment_amount_per_month = 2000 # 每月定投金额
1311
14- fixed_investment_amount_per_week = 500
15- fixed_investment_amount_per_month = 2000
16- my_font = font_manager .FontProperties (fname = '/System/Library/Fonts/PingFang.ttc' )
17-
18- with open (file ) as f :
19- line = f .readline ()
20- result = json .loads (line )
21- for found in result ['Data' ]['LSJZList' ][::- 1 ]:
22- found_date_price [found ['FSRQ' ]] = found ['DWJZ' ]
23- found_price_x .append (found ['FSRQ' ])
24- found_price_y .append (found ['DWJZ' ])
12+ def get_data ():
13+ with open (f'./found_{ foundCode } .txt' ) as f :
14+ line = f .readline ()
15+ result = json .loads (line )
16+ found_date_price = {}
17+ for found in result ['Data' ]['LSJZList' ][::- 1 ]:
18+ found_date_price [found ['FSRQ' ]] = found ['DWJZ' ]
19+ return found_date_price
2520
21+ found_date_price = get_data ()
2622
2723# 买入规则:从 start_date 日期开始,每逢 weekday 买入,如果 weekday 不是交易日,则顺延至最近的交易日
2824# 每次买入 500 元,之后转化为相应的份额
@@ -42,17 +38,15 @@ def calculate_found_profit_by_week(start_date, end_date, weekday):
4238 nums += 1
4339 total_stock += round (fixed_investment_amount_per_week / float (found_date_price [day .strftime ('%Y-%m-%d' )]), 2 )
4440 total_amount += fixed_investment_amount_per_week
45- # print(day.strftime('%Y-%m-%d'), found_date_price[day.strftime('%Y-%m-%d')],
46- # round(fixed_investment_amount / float(found_date_price[day.strftime('%Y-%m-%d')]), 2), nums)
4741
4842 # 计算盈利
4943 while found_date_price .get (end_date .strftime ('%Y-%m-%d' ), None ) is None :
5044 end_date += datetime .timedelta (days = - 1 )
45+
5146 total_profit = round (total_stock , 2 ) * float (found_date_price [end_date .strftime ('%Y-%m-%d' )]) - total_amount
5247
5348 return nums , round (total_stock , 2 ), total_amount , round (total_profit )
5449
55-
5650def get_first_day_of_next_month (date ):
5751 first_day = datetime .datetime (date .year , date .month , 1 )
5852 days_num = calendar .monthrange (first_day .year , first_day .month )[1 ] # 获取一个月有多少天
@@ -76,8 +70,6 @@ def calculate_found_profit_by_month(start_date, end_date):
7670 nums += 1
7771 total_stock += round (fixed_investment_amount_per_month / float (found_date_price [day .strftime ('%Y-%m-%d' )]), 2 )
7872 total_amount += fixed_investment_amount_per_month
79- # print(day.strftime('%Y-%m-%d'), found_date_price[day.strftime('%Y-%m-%d')],
80- # round(fixed_investment_amount / float(found_date_price[day.strftime('%Y-%m-%d')]), 2), nums)
8173
8274 # 计算盈利
8375 while found_date_price .get (end_date .strftime ('%Y-%m-%d' ), None ) is None :
@@ -86,87 +78,54 @@ def calculate_found_profit_by_month(start_date, end_date):
8678
8779 return nums , round (total_stock , 2 ), total_amount , round (total_profit )
8880
89-
9081start_date = datetime .datetime .fromisoformat ('2010-01-01' )
9182end_date = datetime .datetime .fromisoformat ('2020-03-01' )
9283
93-
9484def calculate_found_profit_week_month ():
9585 total_amount = []
9686 total_profit = []
97-
87+ # 周定投收益
9888 for i in range (5 ):
9989 result = calculate_found_profit_by_week (start_date , end_date , i )
10090 total_amount .append (result [2 ])
10191 total_profit .append (result [3 ])
102-
92+ # 月定投收益
10393 result_month = calculate_found_profit_by_month (start_date , end_date )
10494 total_amount .append (result_month [2 ])
10595 total_profit .append (result_month [3 ])
10696 return total_amount , total_profit
10797
108-
10998total_amount , total_profit = calculate_found_profit_week_month ()
11099
111- print (total_amount )
112- print (total_profit )
113-
114- fig , ax = plt .subplots ()
115-
116-
117- ## 柱状图
118- def auto_text (rects ):
119- for rect in rects :
120- ax .text (rect .get_x (), rect .get_height (), rect .get_height (), ha = 'left' , va = 'bottom' )
121-
122-
123- def show_pic ():
124- labels = ['周一' , '周二' , '周三' , '周四' , '周五' , '月定投' ]
125- index = np .arange (len (labels ))
126- width = 0.2
127-
128- fig , ax = plt .subplots ()
129- rect1 = ax .bar (index - width / 2 , total_profit , color = 'lightcoral' , width = width , label = '投资收益' )
130- rect2 = ax .bar (index + width / 2 , total_amount , color = 'springgreen' , width = width , label = '投资金额' )
131-
132- plt .title ("投入金额 & 收益柱状图" , fontproperties = my_font )
133- plt .xticks (fontproperties = my_font )
134- ax .set_xticks (ticks = index )
135- ax .set_xticklabels (labels )
136-
137- ax .set_ylim (0 , 220000 )
138- auto_text (rect1 )
139- auto_text (rect2 )
140-
141- plt .show ()
142-
143-
144- # show_pic()
145-
146-
147- # 基金走势
148- def show_found (found_price_y ):
149- found_price_y = list (map (float , found_price_y ))
150- x = [i for i in range (0 , len (found_price_y ))]
151-
152- plt .figure (figsize = (10 , 6 ))
153-
154- plt .plot (x , found_price_y , linewidth = 1 , color = 'r' )
155-
156- plt .xlabel ('时间' , fontproperties = my_font )
157- plt .ylabel ('单位净值' , fontproperties = my_font )
158- plt .title (f"{ foundCode } 基金走势" , fontproperties = my_font )
159- plt .xticks (x [::90 ], found_price_x [::90 ], rotation = 45 )
160-
161- plt .show ()
162-
163-
164- # show_found(found_price_y)
165-
166- def calculate_found_profit ():
167- start_date = datetime .datetime .fromisoformat ('2015-06-10' )
168- end_date = datetime .datetime .fromisoformat ('2020-03-01' )
169- result = calculate_found_profit_by_month (start_date , end_date )
170- print (result )
171-
172- # calculate_found_profit()
100+ # 这部分代码在 jupyter 中 run
101+ line = (
102+ Line ()
103+ .add_xaxis (list (found_date_price .keys ()))
104+ .add_yaxis ('price' ,list (found_date_price .values ()),label_opts = opts .LabelOpts (is_show = False ))
105+ .set_global_opts (
106+ title_opts = opts .TitleOpts (title = f'{ foundCode } 基金走势图' ),
107+ xaxis_opts = opts .AxisOpts (splitline_opts = opts .SplitLineOpts (is_show = True )),
108+ yaxis_opts = opts .AxisOpts (splitline_opts = opts .SplitLineOpts (is_show = True )),
109+ )
110+ )
111+ #line.render_notebook()
112+
113+ x = ['周一' , '周二' , '周三' , '周四' , '周五' , '月定投' ]
114+ bar = (
115+ Bar ()
116+ .add_xaxis (x )
117+ .add_yaxis ('投资金额' , total_amount )
118+ .add_yaxis ('投资收益' , total_profit )
119+ .set_global_opts (
120+ title_opts = opts .TitleOpts (title = "投资总额 & 投资收益" ),
121+ xaxis_opts = opts .AxisOpts (splitline_opts = opts .SplitLineOpts (is_show = True )),
122+ yaxis_opts = opts .AxisOpts (splitline_opts = opts .SplitLineOpts (is_show = True )),
123+ )
124+ )
125+ #bar.render_notebook()
126+ # 这部分代码在 jupyter 中 run
127+
128+ start_date = datetime .datetime .fromisoformat ('2015-06-10' )
129+ end_date = datetime .datetime .fromisoformat ('2020-03-01' )
130+ result = calculate_found_profit_by_month (start_date , end_date )
131+ print (result )
0 commit comments