Skip to content

Commit 848e717

Browse files
committed
add code
1 parent 13c4fd7 commit 848e717

File tree

5 files changed

+254
-90
lines changed

5 files changed

+254
-90
lines changed
Lines changed: 49 additions & 90 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,24 @@
11
import json
22
import datetime
33
import 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

88
foundCode = '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-
5650
def 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-
9081
start_date = datetime.datetime.fromisoformat('2010-01-01')
9182
end_date = datetime.datetime.fromisoformat('2020-03-01')
9283

93-
9484
def 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-
10998
total_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)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
5
Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
1+
import pygame, sys, random
2+
from pygame.locals import *
3+
4+
# 颜色配置
5+
snake_color = pygame.Color("#8B7D1C")
6+
food_color = pygame.Color("#8B0000")
7+
background_color = pygame.Color("#BACB03")
8+
text_color = pygame.Color("#EFEFEF")
9+
10+
speed = 5
11+
# 长度单位
12+
pixel = 15
13+
line = 44
14+
row = 36
15+
window_width = pixel * line
16+
window_high = pixel * row
17+
18+
point_left_up = [pixel * 2, pixel * 4]
19+
point_left_down = [pixel * 2, pixel * (row - 2)]
20+
point_right_up = [pixel * (line - 2), pixel * 4]
21+
point_right_down = [pixel * (line - 2), pixel * (row - 2)]
22+
23+
# 蛇头位置
24+
snake_head = [pixel * 8, pixel * 8]
25+
# 蛇身
26+
snake_body = [[snake_head[0] - x * pixel, snake_head[1]] for x in range(5)]
27+
# 方向
28+
direction_right = 0
29+
direction_up = 90
30+
direction_left = 180
31+
direction_down = 270
32+
move = {direction_right: [pixel, 0], direction_left: [-pixel, 0],
33+
direction_up: [0, -pixel], direction_down: [0, pixel]}
34+
35+
# 分数设置
36+
score = 5
37+
filename = 'db.txt'
38+
39+
40+
def write_score(content):
41+
with open(filename, 'w+') as f:
42+
f.write(str(content))
43+
44+
45+
def read_score():
46+
with open(filename, 'w+') as f:
47+
result = f.readline()
48+
return 0 if result.strip() == '' else int(result)
49+
50+
51+
def init():
52+
# 初始化
53+
pygame.init()
54+
# new a window
55+
my_screen = pygame.display.set_mode((window_width, window_high), 0, 32)
56+
# 设置标题
57+
pygame.display.set_caption("Greedy Snake")
58+
return my_screen
59+
60+
61+
# 游戏结束
62+
def game_over(max_score, current_score):
63+
if max_score < current_score:
64+
write_score(current_score)
65+
pygame.quit()
66+
sys.exit()
67+
68+
69+
screen = init()
70+
time_clock = pygame.time.Clock()
71+
72+
73+
# 画边线
74+
def draw_box():
75+
for point in [[point_left_up, point_right_up], [point_right_up, point_right_down],
76+
[point_right_down, point_left_down], [point_left_down, point_left_up]]:
77+
pygame.draw.line(screen, snake_color, point[0], point[1], 1)
78+
79+
80+
def is_alive():
81+
# 越界 -> game over
82+
if (snake_head[0] < point_left_up[0] or snake_head[0] > (point_right_down[0] - pixel) or
83+
snake_head[1] < point_left_up[1] or snake_head[1] > (point_right_down[1]) - pixel):
84+
return False
85+
86+
# 头触碰到身体 -> game over
87+
if snake_head in snake_body:
88+
return False
89+
90+
return True
91+
92+
93+
# 随机产生食物
94+
def create_food():
95+
while True:
96+
x = random.randint(point_left_up[0] / pixel, point_right_down[0] / pixel - 1) * pixel
97+
y = random.randint(point_left_up[1] / pixel, point_right_down[1] / pixel - 1) * pixel
98+
if [x, y] not in snake_body:
99+
break
100+
return [x, y]
101+
102+
103+
def draw_snake(food_position):
104+
# 画蛇
105+
for point in snake_body:
106+
pygame.draw.rect(screen, snake_color, Rect(point[0], point[1], pixel, pixel))
107+
# 画食物
108+
pygame.draw.rect(screen, food_color, Rect(food_position[0], food_position[1], pixel, pixel))
109+
110+
111+
def display_message(text, color, size, postion):
112+
font = pygame.font.Font(None, size)
113+
text = font.render(text, True, color)
114+
screen.blit(text, postion)
115+
pygame.display.update()
116+
117+
118+
# 入口函数
119+
def run():
120+
food_position = create_food()
121+
max_score = read_score()
122+
current_score = 0
123+
is_dead = False
124+
origin_direction = direction_right
125+
target_direction = origin_direction
126+
while True:
127+
# 监听键盘按键 退出 OR 换方向
128+
for event in pygame.event.get():
129+
if event.type == pygame.QUIT:
130+
game_over(max_score, current_score)
131+
if event.type == KEYDOWN:
132+
# 方向键 or asdw 控制方向
133+
if event.key == K_RIGHT or event.key == K_d:
134+
target_direction = direction_right
135+
if event.key == K_LEFT or event.key == K_a:
136+
target_direction = direction_left
137+
if event.key == K_UP or event.key == K_w:
138+
target_direction = direction_up
139+
if event.key == K_DOWN or event.key == K_s:
140+
target_direction = direction_down
141+
# esc 退出
142+
if event.key == K_ESCAPE:
143+
game_over(max_score, current_score)
144+
# 夹角为 90 or 270 可以转换方向
145+
angle = abs(origin_direction - target_direction)
146+
if angle == 90 or angle == 270:
147+
origin_direction = target_direction
148+
149+
if not is_dead:
150+
snake_head[0] += move[origin_direction][0]
151+
snake_head[1] += move[origin_direction][1]
152+
153+
if not is_dead and is_alive():
154+
# 按 origin_direction 方向运动
155+
snake_body.insert(0, list(snake_head))
156+
# 吃到食物后重新生成
157+
if snake_head[0] == food_position[0] and snake_head[1] == food_position[1]:
158+
food_position = create_food()
159+
current_score += score
160+
else:
161+
# 移除最后一格
162+
snake_body.pop()
163+
else:
164+
is_dead = True
165+
166+
# 画背景
167+
screen.fill(background_color)
168+
# 画边框
169+
draw_box()
170+
# 画蛇
171+
draw_snake(food_position)
172+
# 刷新画面
173+
pygame.display.update()
174+
# 更新分数
175+
display_message(f"{current_score}/{max_score}", text_color, 30, (pixel * 2, pixel * 2))
176+
if is_dead:
177+
display_message(f"Game Over", text_color, 50, (pixel * 16, pixel * 15))
178+
# 控制游戏速度
179+
time_clock.tick(speed)
180+
181+
182+
if __name__ == '__main__':
183+
run()

0 commit comments

Comments
 (0)