Hakureirm commited on
Commit
b168a2d
·
verified ·
1 Parent(s): 3618234

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -0
app.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import numpy as np
4
+ import plotly.express as px
5
+ from datetime import datetime
6
+
7
+ def calculate_schedule(
8
+ principal: float,
9
+ deposit: float,
10
+ annual_rate: float,
11
+ compounding: str,
12
+ display_freq: str,
13
+ years: int
14
+ ):
15
+ """计算从1个复利期到指定年限的终值和利息,支持不同复利及显示频率"""
16
+ # 复利周期次数映射
17
+ freq_map = {"Annual": 1, "Monthly": 12, "Daily": 365}
18
+ m = freq_map[compounding]
19
+ total_periods = years * m
20
+ r_m = (annual_rate / 100) / m # 每期利率
21
+
22
+ periods, fv_list = [], []
23
+ for t in range(1, total_periods + 1):
24
+ fv_t = principal * (1 + r_m)**t + deposit * (((1 + r_m)**t - 1)/r_m)
25
+ # 根据展示频率筛选
26
+ if display_freq == "Yearly" and t % m == 0:
27
+ periods.append(t // m)
28
+ fv_list.append(fv_t)
29
+ elif display_freq == "Monthly" and compounding == "Monthly":
30
+ periods.append(t)
31
+ fv_list.append(fv_t)
32
+ elif display_freq == "Daily" and compounding == "Daily":
33
+ periods.append(t)
34
+ fv_list.append(fv_t)
35
+
36
+ # 构造 DataFrame
37
+ df = pd.DataFrame({
38
+ display_freq: periods,
39
+ "Future Value (RMB)": np.round(fv_list, 2),
40
+ "Total Invested (RMB)": np.round(principal + deposit * np.array(periods), 2),
41
+ })
42
+ df["Interest Earned (RMB)"] = df["Future Value (RMB)"] - df["Total Invested (RMB)"]
43
+
44
+ # 绘制折线图
45
+ fig = px.line(
46
+ df,
47
+ x=display_freq,
48
+ y="Future Value (RMB)",
49
+ title=f"Compound Growth over Time ({display_freq})"
50
+ )
51
+ fig.update_layout(xaxis_title=display_freq, yaxis_title="Future Value (RMB)")
52
+
53
+ return df, fig
54
+
55
+ with gr.Blocks() as demo:
56
+ gr.Markdown("## 复利计算器\n输入参数,实时查看复利终值及曲线图")
57
+ with gr.Row():
58
+ principal = gr.Number(label="初始本金 (RMB)", value=20000)
59
+ deposit = gr.Number(label="每期定投 (RMB)", value=5000)
60
+ annual_rate = gr.Number(label="年化收益率 (%)", value=10.22)
61
+ with gr.Row():
62
+ compounding = gr.Radio(
63
+ choices=["Annual", "Monthly", "Daily"],
64
+ label="复利频率",
65
+ value="Monthly"
66
+ )
67
+ display_freq = gr.Radio(
68
+ choices=["Yearly", "Monthly", "Daily"],
69
+ label="结果展示频率",
70
+ value="Yearly"
71
+ )
72
+ years = gr.Slider(1, 50, value=41, label="计算年限 (年)")
73
+ result_table = gr.Dataframe(headers=["Period", "Future Value (RMB)", "Total Invested (RMB)", "Interest Earned (RMB)"])
74
+ result_plot = gr.Plot()
75
+
76
+ # 绑定事件
77
+ demo.load(
78
+ fn=calculate_schedule,
79
+ inputs=[principal, deposit, annual_rate, compounding, display_freq, years],
80
+ outputs=[result_table, result_plot]
81
+ )
82
+
83
+ demo.launch()