-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
487 lines (417 loc) · 18.8 KB
/
Copy pathapp.py
File metadata and controls
487 lines (417 loc) · 18.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
import flet as ft
import numpy as np
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg
import matplotlib
matplotlib.use('Agg')
from io import BytesIO
import base64
from threading import Timer
from typing import Callable
# Configuration Constants
WEEKS_PER_YEAR = 52
DEFAULT_CHART_DPI = 80
CHART_FIGSIZE = (14, 10)
DEBOUNCE_DELAY = 0.3
def calculate_pv_annuity(payment: float, annual_rate: float, years: float, freq: int = 52) -> float:
"""Calculate the present value of an annuity.
Args:
payment: Periodic payment amount
annual_rate: Annual interest rate (as decimal, e.g., 0.05 for 5%)
years: Number of years
freq: Payment frequency per year (default: 52 for weekly)
Returns:
Present value of the annuity
"""
if annual_rate == 0:
return payment * years * freq
periodic_rate = annual_rate / freq
total_periods = years * freq
pv = payment * ((1 - (1 + periodic_rate) ** (-total_periods)) / periodic_rate)
return pv
def calculate_real_value(nominal_value: float, inflation_rate: float, years: float) -> float:
"""Calculate the real (inflation-adjusted) value of a nominal amount.
Args:
nominal_value: Nominal dollar amount
inflation_rate: Annual inflation rate (as decimal)
years: Number of years in the future
Returns:
Real value in today's dollars
"""
return nominal_value / ((1 + inflation_rate) ** years)
def calculate_net_worth_with_expenses(initial_amount: float, weekly_payment: float, annual_return: float,
weekly_expenses: float, years: float, is_lump_sum: bool = True) -> np.ndarray:
"""Calculate net worth over time accounting for expenses and investment returns.
Args:
initial_amount: Starting lump sum (used if is_lump_sum=True)
weekly_payment: Weekly annuity payment (used if is_lump_sum=False)
annual_return: Annual investment return rate (as decimal)
weekly_expenses: Weekly expense amount
years: Time horizon in years
is_lump_sum: If True, model lump sum scenario; if False, model annuity scenario
Returns:
Array of net worth values for each week
"""
total_weeks = int(years * WEEKS_PER_YEAR)
net_worth = np.zeros(total_weeks + 1)
if is_lump_sum:
net_worth[0] = initial_amount
weekly_rate = annual_return / WEEKS_PER_YEAR
for week in range(1, total_weeks + 1):
net_worth[week] = net_worth[week-1] * (1 + weekly_rate) - weekly_expenses
if net_worth[week] < 0:
net_worth[week] = 0
else:
net_worth[0] = 0
weekly_rate = annual_return / WEEKS_PER_YEAR
for week in range(1, total_weeks + 1):
net_income = weekly_payment - weekly_expenses
net_worth[week] = net_worth[week-1] * (1 + weekly_rate) + net_income
if net_worth[week] < 0:
net_worth[week] = 0
return net_worth
def find_breakeven_rate(lump_sum: float, weekly_payment: float, years: float) -> float:
"""Find the break-even interest rate where annuity PV equals lump sum.
Args:
lump_sum: Lump sum amount
weekly_payment: Weekly annuity payment
years: Time horizon in years
Returns:
Break-even annual interest rate (as decimal)
"""
rates = np.linspace(0.001, 0.20, 1000)
for rate in rates:
pv = calculate_pv_annuity(weekly_payment, rate, years)
if pv <= lump_sum:
return rate
return rates[-1]
class TVMAnalyzerApp:
def __init__(self, page: ft.Page):
self.page = page
self.page.title = "TVM Analyzer"
self.page.theme_mode = ft.ThemeMode.LIGHT
self.page.padding = 10
self.lump_sum = 1_000_000
self.weekly_payment = 1_000
self.return_rate = 0.05
self.inflation_rate = 0.03
self.weekly_expenses = 500
self.lifespan = 65
self.update_timer = None
self.debounce_delay = DEBOUNCE_DELAY
self.slider_value_texts = {}
self.slider_controls = {}
self.warning_banner = ft.Container(
content=ft.Row([
ft.Icon(ft.Icons.WARNING_AMBER_ROUNDED, color=ft.Colors.ORANGE_900, size=20),
ft.Text(
"WARNING: Weekly payment is less than or equal to expenses. This is financially unsustainable!",
size=12,
weight=ft.FontWeight.BOLD,
color=ft.Colors.ORANGE_900
)
], tight=True),
bgcolor=ft.Colors.ORANGE_100,
border=ft.border.all(2, ft.Colors.ORANGE_700),
border_radius=5,
padding=10,
visible=False
)
self.chart_container = ft.Container(
content=ft.Text("Loading charts...", size=16),
expand=True,
bgcolor=ft.Colors.WHITE,
border_radius=10,
padding=2
)
self.metrics_container = ft.Container(
content=ft.Column([
ft.Text("Decision Metrics", size=20, weight=ft.FontWeight.BOLD),
ft.Divider(),
]),
bgcolor=ft.Colors.BLUE_50,
border_radius=10,
padding=10,
)
self.build_ui()
self.update_analysis()
def build_ui(self):
controls_column = ft.Column([
self.warning_banner,
ft.Text("Parameters", size=20, weight=ft.FontWeight.BOLD),
ft.Divider(height=5),
ft.Text("Lump Sum Amount", size=12, weight=ft.FontWeight.W_500),
self.create_slider_with_label(
key="lump_sum",
min_val=500_000,
max_val=2_000_000,
value=self.lump_sum,
divisions=30,
format_func=lambda v: f"${v:,.0f}",
on_change=self.on_lump_sum_change
),
ft.Text("Weekly Annuity Payment", size=12, weight=ft.FontWeight.W_500),
self.create_slider_with_label(
key="weekly_payment",
min_val=50,
max_val=10_000,
value=self.weekly_payment,
divisions=100,
format_func=lambda v: f"${v:,.0f}",
on_change=self.on_weekly_payment_change
),
ft.Text("Investment Return Rate", size=12, weight=ft.FontWeight.W_500),
self.create_slider_with_label(
key="return_rate",
min_val=0,
max_val=0.15,
value=self.return_rate,
divisions=30,
format_func=lambda v: f"{v:.1%}",
on_change=self.on_return_rate_change
),
ft.Text("Inflation Rate", size=12, weight=ft.FontWeight.W_500),
self.create_slider_with_label(
key="inflation_rate",
min_val=0,
max_val=0.10,
value=self.inflation_rate,
divisions=20,
format_func=lambda v: f"{v:.1%}",
on_change=self.on_inflation_change
),
ft.Text("Weekly Expenses", size=12, weight=ft.FontWeight.W_500),
self.create_slider_with_label(
key="weekly_expenses",
min_val=0,
max_val=10_000,
value=self.weekly_expenses,
divisions=100,
format_func=lambda v: f"${v:,.0f}",
on_change=self.on_expenses_change
),
ft.Text("Expected Lifespan (years)", size=12, weight=ft.FontWeight.W_500),
self.create_slider_with_label(
key="lifespan",
min_val=20,
max_val=120,
value=self.lifespan,
divisions=100,
format_func=lambda v: f"{v:.0f} years",
on_change=self.on_lifespan_change
),
], scroll=ft.ScrollMode.AUTO, spacing=5)
controls_panel = ft.Container(
content=controls_column,
expand=1,
padding=10,
bgcolor=ft.Colors.GREY_200,
border_radius=10,
)
chart_panel = ft.Container(
content=self.chart_container,
expand=3,
)
metrics_panel = ft.Container(
content=ft.Column([
self.metrics_container
], scroll=ft.ScrollMode.AUTO),
expand=1,
padding=5,
)
main_row = ft.Row([
controls_panel,
ft.VerticalDivider(width=1),
chart_panel,
ft.VerticalDivider(width=1),
metrics_panel,
], expand=True, spacing=0)
self.page.add(main_row)
def create_slider_with_label(self, key: str, min_val: float, max_val: float, value: float,
divisions: int, format_func: Callable[[float], str],
on_change: Callable) -> ft.Column:
value_text = ft.Text(
f"Min: {format_func(min_val)} | Current: {format_func(value)} | Max: {format_func(max_val)}",
size=10,
color=ft.Colors.GREY_900
)
self.slider_value_texts[key] = value_text
slider = ft.Slider(
min=min_val,
max=max_val,
value=value,
divisions=divisions,
label=format_func(value),
on_change=on_change,
active_color=ft.Colors.BLUE_700,
inactive_color=ft.Colors.BLUE_200
)
self.slider_controls[key] = slider
return ft.Column([
slider,
value_text
], spacing=0)
def validate_annuity_payment(self) -> bool:
"""Validate that weekly payment exceeds expenses and update UI accordingly.
Returns:
True if payment is sustainable, False otherwise
"""
if self.weekly_payment <= self.weekly_expenses:
self.slider_controls["weekly_payment"].active_color = ft.Colors.RED
self.slider_controls["weekly_payment"].inactive_color = ft.Colors.RED_200
self.warning_banner.visible = True
return False
else:
self.slider_controls["weekly_payment"].active_color = None
self.slider_controls["weekly_payment"].inactive_color = None
self.warning_banner.visible = False
return True
def debounced_update(self):
if self.update_timer:
self.update_timer.cancel()
self.update_timer = Timer(self.debounce_delay, self.update_analysis)
self.update_timer.start()
def on_lump_sum_change(self, e):
self.lump_sum = e.control.value
e.control.label = f"${e.control.value:,.0f}"
self.slider_value_texts["lump_sum"].value = f"Min: $500,000 | Current: ${e.control.value:,.0f} | Max: $2,000,000"
self.page.update()
self.debounced_update()
def on_weekly_payment_change(self, e):
self.weekly_payment = e.control.value
e.control.label = f"${e.control.value:,.0f}"
self.slider_value_texts["weekly_payment"].value = f"Min: $50 | Current: ${e.control.value:,.0f} | Max: $10,000"
self.validate_annuity_payment()
self.page.update()
self.debounced_update()
def on_return_rate_change(self, e):
self.return_rate = e.control.value
e.control.label = f"{e.control.value:.1%}"
self.slider_value_texts["return_rate"].value = f"Min: 0.0% | Current: {e.control.value:.1%} | Max: 15.0%"
self.page.update()
self.debounced_update()
def on_inflation_change(self, e):
self.inflation_rate = e.control.value
e.control.label = f"{e.control.value:.1%}"
self.slider_value_texts["inflation_rate"].value = f"Min: 0.0% | Current: {e.control.value:.1%} | Max: 10.0%"
self.page.update()
self.debounced_update()
def on_expenses_change(self, e):
self.weekly_expenses = e.control.value
e.control.label = f"${e.control.value:,.0f}"
self.slider_value_texts["weekly_expenses"].value = f"Min: $0 | Current: ${e.control.value:,.0f} | Max: $10,000"
self.validate_annuity_payment()
self.page.update()
self.debounced_update()
def on_lifespan_change(self, e):
self.lifespan = e.control.value
e.control.label = f"{e.control.value:.0f} years"
self.slider_value_texts["lifespan"].value = f"Min: 20 years | Current: {e.control.value:.0f} years | Max: 120 years"
self.page.update()
self.debounced_update()
def update_analysis(self):
breakeven_rate = find_breakeven_rate(self.lump_sum, self.weekly_payment, self.lifespan)
net_worth_lump = calculate_net_worth_with_expenses(
self.lump_sum, 0, self.return_rate, self.weekly_expenses, self.lifespan, True
)
net_worth_annuity = calculate_net_worth_with_expenses(
0, self.weekly_payment, self.return_rate, self.weekly_expenses, self.lifespan, False
)
final_lump = net_worth_lump[-1]
final_annuity = net_worth_annuity[-1]
optimal_choice = "Lump Sum" if final_lump > final_annuity else "Annuity"
advantage = abs(final_lump - final_annuity)
self.metrics_container.content = ft.Column([
ft.Text("Decision Metrics", size=20, weight=ft.FontWeight.BOLD),
ft.Divider(),
ft.Text(f"Break-even Rate: {breakeven_rate:.2%}", size=14),
ft.Text(f"Current Return: {self.return_rate:.2%}", size=14),
ft.Divider(),
ft.Text(f"Final Net Worth (Lump Sum): ${final_lump:,.0f}", size=14),
ft.Text(f"Final Net Worth (Annuity): ${final_annuity:,.0f}", size=14),
ft.Divider(),
ft.Text(f"Optimal Choice: {optimal_choice}", size=16, weight=ft.FontWeight.BOLD,
color=ft.Colors.GREEN_700),
ft.Text(f"Advantage: ${advantage:,.0f}", size=14, color=ft.Colors.GREEN_600),
])
chart_image = self.generate_charts()
self.chart_container.content = ft.Image(
src_base64=chart_image,
fit=ft.ImageFit.CONTAIN,
)
self.page.update()
def generate_charts(self) -> str:
"""Generate all analysis charts using thread-safe OO Matplotlib API.
Returns:
Base64-encoded PNG image of the charts
"""
fig = Figure(figsize=CHART_FIGSIZE, dpi=DEFAULT_CHART_DPI)
canvas = FigureCanvasAgg(fig)
gs = fig.add_gridspec(2, 2, hspace=0.25, wspace=0.25, left=0.08, right=0.98, top=0.96, bottom=0.06)
rates = np.linspace(0.001, 0.15, 200)
pv_values = [calculate_pv_annuity(self.weekly_payment, r, self.lifespan) for r in rates]
ax1 = fig.add_subplot(gs[0, 0])
ax1.plot(rates * 100, np.array(pv_values) / 1e6, label='Annuity PV', color='blue', linewidth=2)
ax1.axhline(y=self.lump_sum / 1e6, color='red', linestyle='-', label='Lump Sum', linewidth=2)
ax1.axvline(x=self.return_rate * 100, color='green', linestyle='--', alpha=0.7, label='Current Rate')
ax1.set_title('Break-Even Analysis', fontsize=14, fontweight='bold')
ax1.set_xlabel('Annual Return Rate (%)', fontsize=12)
ax1.set_ylabel('Present Value ($ Millions)', fontsize=12)
ax1.tick_params(labelsize=10)
ax1.grid(True, alpha=0.3)
ax1.legend(fontsize=10)
net_worth_lump = calculate_net_worth_with_expenses(
self.lump_sum, 0, self.return_rate, self.weekly_expenses, self.lifespan, True
)
net_worth_annuity = calculate_net_worth_with_expenses(
0, self.weekly_payment, self.return_rate, self.weekly_expenses, self.lifespan, False
)
weeks = np.arange(len(net_worth_lump))
years = weeks / 52
ax2 = fig.add_subplot(gs[0, 1])
ax2.plot(years, net_worth_lump / 1e6, label='Lump Sum', color='red', linewidth=2)
ax2.plot(years, net_worth_annuity / 1e6, label='Annuity', color='blue', linewidth=2)
ax2.set_title('Net Worth Over Time (After Expenses)', fontsize=14, fontweight='bold')
ax2.set_xlabel('Years', fontsize=12)
ax2.set_ylabel('Net Worth ($ Millions)', fontsize=12)
ax2.tick_params(labelsize=10)
ax2.grid(True, alpha=0.3)
ax2.legend(fontsize=10)
real_lump = np.array([calculate_real_value(nw, self.inflation_rate, y)
for nw, y in zip(net_worth_lump, years)])
real_annuity = np.array([calculate_real_value(nw, self.inflation_rate, y)
for nw, y in zip(net_worth_annuity, years)])
ax3 = fig.add_subplot(gs[1, 0])
ax3.plot(years, real_lump / 1e6, label='Lump Sum (Real)', color='darkred', linewidth=2)
ax3.plot(years, real_annuity / 1e6, label='Annuity (Real)', color='darkblue', linewidth=2)
ax3.set_title('Real Purchasing Power (Inflation-Adjusted)', fontsize=14, fontweight='bold')
ax3.set_xlabel('Years', fontsize=12)
ax3.set_ylabel('Real Value ($ Millions)', fontsize=12)
ax3.tick_params(labelsize=10)
ax3.grid(True, alpha=0.3)
ax3.legend(fontsize=10)
years_annual = np.arange(0, int(self.lifespan) + 1)
annual_income_annuity = np.full(len(years_annual), self.weekly_payment * 52)
annual_expenses = np.full(len(years_annual), self.weekly_expenses * 52)
ax4 = fig.add_subplot(gs[1, 1])
x = np.arange(len(years_annual))
width = 0.35
ax4.bar(x - width/2, annual_income_annuity / 1000, width, label='Annuity Income', color='blue', alpha=0.7)
ax4.bar(x + width/2, annual_expenses / 1000, width, label='Expenses', color='red', alpha=0.7)
ax4.axhline(y=self.lump_sum / 1000, color='green', linestyle='--', label='Lump Sum (one-time)', linewidth=2)
ax4.set_title('Annual Cash Flow Comparison', fontsize=14, fontweight='bold')
ax4.set_xlabel('Years', fontsize=12)
ax4.set_ylabel('Amount ($1000s)', fontsize=12)
ax4.tick_params(labelsize=10)
ax4.set_xticks([0, int(self.lifespan/4), int(self.lifespan/2), int(3*self.lifespan/4), int(self.lifespan)])
ax4.grid(True, alpha=0.3, axis='y')
ax4.legend(fontsize=10)
buf = BytesIO()
canvas.print_png(buf)
buf.seek(0)
img_base64 = base64.b64encode(buf.read()).decode()
return img_base64
def main(page: ft.Page):
TVMAnalyzerApp(page)
if __name__ == "__main__":
ft.app(target=main)