-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1475 lines (1266 loc) · 53.9 KB
/
app.py
File metadata and controls
1475 lines (1266 loc) · 53.9 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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import uuid
import os
import csv
import io
import re
import subprocess
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
import requests as req
import pdfplumber
from flask import Flask, render_template, jsonify, request
app = Flask(__name__)
PORTFOLIO_FILE = os.path.join(os.path.dirname(__file__), "portfolio.json")
# In-memory price cache
_price_cache = {}
_historical_cache = {}
_usd_inr_rate = None
def load_portfolio():
if not os.path.exists(PORTFOLIO_FILE):
return {"investments": []}
with open(PORTFOLIO_FILE, "r") as f:
return json.load(f)
def save_portfolio(data):
with open(PORTFOLIO_FILE, "w") as f:
json.dump(data, f, indent=2)
def yahoo_fetch(url):
"""Fetch URL via curl to avoid Yahoo's Python requests blocking."""
try:
result = subprocess.run(
["curl", "-s", "-H", "User-Agent: Mozilla/5.0", url],
capture_output=True, text=True, timeout=15
)
if result.returncode == 0 and result.stdout.strip():
return json.loads(result.stdout)
except Exception as e:
print("yahoo_fetch error: {}".format(e))
return None
def yahoo_chart(ticker, period="1d", interval="1d", range_start=None, range_end=None):
"""Fetch data from Yahoo Finance v8 chart API."""
url = "https://query1.finance.yahoo.com/v8/finance/chart/{}?interval={}".format(ticker, interval)
if range_start and range_end:
p1 = int(datetime.strptime(range_start, "%Y-%m-%d").timestamp())
p2 = int(datetime.strptime(range_end, "%Y-%m-%d").timestamp())
url += "&period1={}&period2={}".format(p1, p2)
else:
url += "&range={}".format(period)
data = yahoo_fetch(url)
if data:
result = data.get("chart", {}).get("result")
if result and len(result) > 0:
return result[0]
return None
def get_usd_inr_rate():
global _usd_inr_rate
if _usd_inr_rate:
return _usd_inr_rate
chart = yahoo_chart("USDINR=X", period="1d")
if chart:
close = chart.get("meta", {}).get("regularMarketPrice")
if close:
_usd_inr_rate = float(close)
return _usd_inr_rate
_usd_inr_rate = 83.0
return _usd_inr_rate
def get_current_price(inv):
"""Get current price for a market-traded investment. Returns price in INR."""
inv_id = inv["id"]
if inv_id in _price_cache:
return _price_cache[inv_id]
price = None
inv_type = inv["type"]
if inv_type in ("stock", "etf", "gold_etf"):
ticker = inv["ticker"]
chart = yahoo_chart(ticker, period="5d")
if chart:
price = chart.get("meta", {}).get("regularMarketPrice")
if price is None:
closes = chart.get("indicators", {}).get("quote", [{}])[0].get("close", [])
closes = [c for c in closes if c is not None]
if closes:
price = closes[-1]
elif inv_type == "mutual_fund":
scheme_code = inv["scheme_code"]
try:
resp = req.get("https://api.mfapi.in/mf/{}/latest".format(scheme_code), timeout=10)
data = resp.json()
if "data" in data and len(data["data"]) > 0:
price = float(data["data"][0]["nav"])
except Exception as e:
print("Error fetching MF {}: {}".format(scheme_code, e))
elif inv_type == "crypto":
coin_id = inv["coin_id"]
try:
resp = req.get(
"https://api.coingecko.com/api/v3/simple/price?ids={}&vs_currencies=inr".format(coin_id),
timeout=10,
)
data = resp.json()
if coin_id in data:
price = float(data[coin_id]["inr"])
except Exception as e:
print("Error fetching crypto {}: {}".format(coin_id, e))
if price is not None:
price = float(price)
_price_cache[inv_id] = price
return price
def calculate_fd_value(inv, as_of_date=None):
"""Calculate FD value with compounding."""
principal = float(inv["principal"])
rate = float(inv["interest_rate"]) / 100
start = datetime.strptime(inv["start_date"], "%Y-%m-%d")
maturity = datetime.strptime(inv["maturity_date"], "%Y-%m-%d")
compounding = inv.get("compounding", "quarterly")
if as_of_date is None:
as_of_date = datetime.now()
elif isinstance(as_of_date, str):
as_of_date = datetime.strptime(as_of_date, "%Y-%m-%d")
if as_of_date < start:
return 0
if as_of_date > maturity:
return 0
n_map = {"monthly": 12, "quarterly": 4, "half_yearly": 2, "yearly": 1}
n = n_map.get(compounding, 4)
years = (as_of_date - start).days / 365.25
value = principal * ((1 + rate / n) ** (n * years))
return round(value, 2)
def calculate_pf_value(inv, as_of_date=None):
"""Calculate PF value with annual compounding on contributions."""
rate = float(inv["interest_rate"]) / 100
contributions = inv.get("contributions", [])
if as_of_date is None:
as_of_date = datetime.now()
elif isinstance(as_of_date, str):
as_of_date = datetime.strptime(as_of_date, "%Y-%m-%d")
total = 0
for c in contributions:
c_date = datetime.strptime(c["date"], "%Y-%m-%d")
if c_date > as_of_date:
continue
years = (as_of_date - c_date).days / 365.25
amount = float(c["amount"])
total += amount * ((1 + rate) ** years)
return round(total, 2)
def get_historical_prices(inv, start_date, end_date=None):
"""Get historical prices for market-traded investments."""
inv_id = inv["id"]
cache_key = "{}_{}".format(inv_id, start_date)
if cache_key in _historical_cache:
return _historical_cache[cache_key]
if end_date is None:
end_date = datetime.now().strftime("%Y-%m-%d")
prices = {}
inv_type = inv["type"]
if inv_type in ("stock", "etf", "gold_etf"):
chart = yahoo_chart(inv["ticker"], interval="1d", range_start=start_date, range_end=end_date)
if chart:
timestamps = chart.get("timestamp", [])
closes = chart.get("indicators", {}).get("quote", [{}])[0].get("close", [])
for i, ts in enumerate(timestamps):
if i < len(closes) and closes[i] is not None:
d = datetime.fromtimestamp(ts).strftime("%Y-%m-%d")
prices[d] = float(closes[i])
elif inv_type == "mutual_fund":
try:
resp = req.get("https://api.mfapi.in/mf/{}".format(inv["scheme_code"]), timeout=30)
data = resp.json()
if "data" in data:
for entry in data["data"]:
d = datetime.strptime(entry["date"], "%d-%m-%Y").strftime("%Y-%m-%d")
if start_date <= d <= end_date:
prices[d] = float(entry["nav"])
except Exception as e:
print("Error fetching MF history: {}".format(e))
elif inv_type == "crypto":
try:
# CoinGecko free API limits to 365 days of history
earliest = datetime.strptime(start_date, "%Y-%m-%d")
max_start = datetime.now() - timedelta(days=364)
if earliest < max_start:
earliest = max_start
start_ts = int(earliest.timestamp())
end_ts = int(datetime.strptime(end_date, "%Y-%m-%d").timestamp())
resp = req.get(
"https://api.coingecko.com/api/v3/coins/{}/market_chart/range"
"?vs_currency=inr&from={}&to={}".format(inv["coin_id"], start_ts, end_ts),
timeout=30,
)
data = resp.json()
if "prices" in data:
for ts, price in data["prices"]:
d = datetime.fromtimestamp(ts / 1000).strftime("%Y-%m-%d")
prices[d] = float(price)
except Exception as e:
print("Error fetching crypto history: {}".format(e))
_historical_cache[cache_key] = prices
return prices
def get_inflation_data():
"""Fetch India CPI data from World Bank API. Returns dict of year -> CPI index.
Extrapolates missing recent years using last known year-over-year rate."""
try:
resp = req.get(
"https://api.worldbank.org/v2/country/IN/indicator/FP.CPI.TOTL?format=json&per_page=50&date=2000:2026",
timeout=10,
)
data = resp.json()
if len(data) > 1 and data[1]:
cpi = {}
for entry in data[1]:
if entry["value"] is not None:
cpi[int(entry["date"])] = float(entry["value"])
# Extrapolate missing years up to current year using last known YoY rate
if cpi:
latest = max(cpi.keys())
current_year = datetime.now().year
if latest >= 2 and (latest - 1) in cpi:
yoy_rate = cpi[latest] / cpi[latest - 1]
else:
yoy_rate = 1.05 # ~5% default India inflation
for y in range(latest + 1, current_year + 2):
cpi[y] = cpi[y - 1] * yoy_rate
return cpi
except Exception as e:
print("Error fetching CPI data: {}".format(e))
return None
def auto_generate_scheduled():
"""Auto-generate pending recurring entries for all investments with schedules."""
portfolio = load_portfolio()
investments = portfolio.get("investments", [])
changed = False
for inv in investments:
schedule = inv.get("schedule")
if not schedule:
continue
amount = float(schedule["amount"])
day = int(schedule.get("day", 1))
start = datetime.strptime(schedule["start_date"], "%Y-%m-%d")
end_str = schedule.get("end_date")
end = datetime.strptime(end_str, "%Y-%m-%d") if end_str else datetime.now()
inv_type = inv["type"]
current = start.replace(day=min(day, 28))
while current <= end:
date_str = current.strftime("%Y-%m-%d")
if inv_type == "pf":
existing_dates = {c["date"] for c in inv.get("contributions", [])}
if date_str not in existing_dates:
inv.setdefault("contributions", []).append({
"id": str(uuid.uuid4())[:8],
"date": date_str,
"amount": str(amount),
})
changed = True
else:
existing_dates = {t["date"] for t in inv.get("transactions", [])}
if date_str not in existing_dates:
buy_price = schedule.get("buy_price")
if buy_price:
qty = amount / float(buy_price)
inv.setdefault("transactions", []).append({
"id": str(uuid.uuid4())[:8],
"date": date_str,
"quantity": str(round(qty, 4)),
"buy_price": str(buy_price),
})
else:
inv.setdefault("transactions", []).append({
"id": str(uuid.uuid4())[:8],
"date": date_str,
"quantity": "0",
"buy_price": str(amount),
})
changed = True
current += relativedelta(months=1)
if changed:
save_portfolio(portfolio)
return changed
def calculate_xirr(cash_flows):
"""Calculate XIRR given a list of (date_string, amount) tuples.
Negative amounts = money going out (investments), positive = money coming in (current value).
Returns annualized return as a decimal (e.g. 0.12 for 12%), or None if it can't converge."""
if not cash_flows or len(cash_flows) < 2:
return None
# Parse dates and amounts
flows = []
for date_str, amount in cash_flows:
dt = datetime.strptime(date_str, "%Y-%m-%d")
flows.append((dt, float(amount)))
flows.sort(key=lambda x: x[0])
d0 = flows[0][0]
# Newton's method to find rate where NPV = 0
def npv(rate):
return sum(amt / ((1 + rate) ** ((dt - d0).days / 365.25)) for dt, amt in flows)
def dnpv(rate):
return sum(-((dt - d0).days / 365.25) * amt / ((1 + rate) ** ((dt - d0).days / 365.25 + 1)) for dt, amt in flows)
rate = 0.1 # initial guess
for _ in range(200):
n = npv(rate)
d = dnpv(rate)
if abs(d) < 1e-12:
break
new_rate = rate - n / d
# Clamp to avoid divergence
new_rate = max(new_rate, -0.99)
if abs(new_rate - rate) < 1e-9:
return round(new_rate * 100, 2)
rate = new_rate
# Check if it converged
if abs(npv(rate)) < 1.0:
return round(rate * 100, 2)
return None
@app.route("/")
def index():
return render_template("index.html")
@app.route("/api/portfolio")
def get_portfolio():
# Auto-generate any pending scheduled entries
auto_generate_scheduled()
portfolio = load_portfolio()
investments = portfolio.get("investments", [])
results = []
total_value = 0
total_invested = 0
for inv in investments:
item = {**inv}
inv_type = inv["type"]
if inv_type == "fd":
current_value = calculate_fd_value(inv)
invested = float(inv["principal"]) if current_value > 0 else 0
item["current_value"] = current_value
item["invested"] = invested
elif inv_type == "pf":
current_value = calculate_pf_value(inv)
invested = sum(float(c["amount"]) for c in inv.get("contributions", []))
item["current_value"] = current_value
item["invested"] = invested
else:
price = get_current_price(inv)
transactions = inv.get("transactions", [])
total_qty = sum(float(t["quantity"]) for t in transactions)
invested = sum(float(t["quantity"]) * float(t["buy_price"]) for t in transactions)
current_value = (price * total_qty) if price else 0
item["current_price"] = price
item["total_quantity"] = round(total_qty, 2)
item["current_value"] = round(current_value, 2)
item["invested"] = round(invested, 2)
if item["current_value"]:
item["gain_loss"] = round(item["current_value"] - item["invested"], 2)
item["gain_loss_pct"] = round(
((item["current_value"] - item["invested"]) / item["invested"] * 100) if item["invested"] else 0, 2
)
else:
item["gain_loss"] = 0
item["gain_loss_pct"] = 0
# Per-investment XIRR
today = datetime.now().strftime("%Y-%m-%d")
inv_flows = []
if inv_type == "fd":
if item["current_value"] > 0:
inv_flows.append((inv["start_date"], -float(inv["principal"])))
inv_flows.append((today, item["current_value"]))
elif inv_type == "pf":
for c in inv.get("contributions", []):
inv_flows.append((c["date"], -float(c["amount"])))
if item["current_value"] > 0:
inv_flows.append((today, item["current_value"]))
else:
for t in inv.get("transactions", []):
amt = float(t["quantity"]) * float(t["buy_price"])
if amt > 0:
inv_flows.append((t["date"], -amt))
if item["current_value"] > 0:
inv_flows.append((today, item["current_value"]))
item["xirr"] = calculate_xirr(inv_flows) if len(inv_flows) >= 2 else None
total_value += item["current_value"]
total_invested += item["invested"]
results.append(item)
# Calculate portfolio XIRR
today = datetime.now().strftime("%Y-%m-%d")
xirr_flows = []
for inv in investments:
inv_type = inv["type"]
if inv_type == "fd":
current_value = calculate_fd_value(inv)
if current_value > 0:
xirr_flows.append((inv["start_date"], -float(inv["principal"])))
xirr_flows.append((today, current_value))
elif inv_type == "pf":
for c in inv.get("contributions", []):
xirr_flows.append((c["date"], -float(c["amount"])))
pf_val = calculate_pf_value(inv)
if pf_val > 0:
xirr_flows.append((today, pf_val))
else:
price = get_current_price(inv)
for t in inv.get("transactions", []):
amt = float(t["quantity"]) * float(t["buy_price"])
xirr_flows.append((t["date"], -amt))
total_qty = sum(float(t["quantity"]) for t in inv.get("transactions", []))
if price and total_qty > 0:
xirr_flows.append((today, price * total_qty))
xirr_val = calculate_xirr(xirr_flows) if xirr_flows else None
return jsonify(
{
"investments": results,
"total_value": round(total_value, 2),
"total_invested": round(total_invested, 2),
"total_gain_loss": round(total_value - total_invested, 2),
"total_gain_loss_pct": round(
((total_value - total_invested) / total_invested * 100) if total_invested else 0, 2
),
"xirr": xirr_val,
}
)
def _find_existing(investments, inv_type, data):
"""Find an existing investment that matches the new one being added."""
for inv in investments:
if inv["type"] != inv_type:
continue
if inv_type in ("stock", "etf", "gold_etf") and inv.get("ticker") == data.get("ticker"):
return inv
if inv_type == "mutual_fund" and inv.get("scheme_code") == data.get("scheme_code"):
return inv
if inv_type == "crypto" and inv.get("coin_id") == data.get("coin_id"):
return inv
if inv_type == "pf" and inv.get("name") == data.get("name"):
return inv
return None
@app.route("/api/investment", methods=["POST"])
def add_investment():
data = request.json
portfolio = load_portfolio()
inv_type = data["type"]
# Check if this investment already exists — if so, append transaction
existing = _find_existing(portfolio.get("investments", []), inv_type, data)
if existing and inv_type in ("stock", "etf", "gold_etf", "mutual_fund", "crypto"):
if data.get("transaction"):
t = data["transaction"]
t["id"] = str(uuid.uuid4())[:8]
existing.setdefault("transactions", []).append(t)
save_portfolio(portfolio)
return jsonify({"status": "ok", "id": existing["id"]})
if existing and inv_type == "pf":
if data.get("contribution"):
c = data["contribution"]
c["id"] = str(uuid.uuid4())[:8]
existing.setdefault("contributions", []).append(c)
if data.get("interest_rate"):
existing["interest_rate"] = data["interest_rate"]
save_portfolio(portfolio)
return jsonify({"status": "ok", "id": existing["id"]})
# No existing match — create new investment
inv_id = str(uuid.uuid4())[:8]
investment = {"id": inv_id, "type": inv_type, "name": data["name"], "category": data.get("category", inv_type)}
if inv_type in ("stock", "etf", "gold_etf"):
investment["ticker"] = data["ticker"]
investment["transactions"] = []
if data.get("transaction"):
t = data["transaction"]
t["id"] = str(uuid.uuid4())[:8]
investment["transactions"].append(t)
elif inv_type == "mutual_fund":
investment["scheme_code"] = data["scheme_code"]
investment["transactions"] = []
if data.get("transaction"):
t = data["transaction"]
t["id"] = str(uuid.uuid4())[:8]
investment["transactions"].append(t)
elif inv_type == "crypto":
investment["coin_id"] = data["coin_id"]
investment["transactions"] = []
if data.get("transaction"):
t = data["transaction"]
t["id"] = str(uuid.uuid4())[:8]
investment["transactions"].append(t)
elif inv_type == "pf":
investment["interest_rate"] = data["interest_rate"]
investment["contributions"] = []
if data.get("contribution"):
c = data["contribution"]
c["id"] = str(uuid.uuid4())[:8]
investment["contributions"].append(c)
elif inv_type == "fd":
investment["principal"] = data["principal"]
investment["interest_rate"] = data["interest_rate"]
investment["start_date"] = data["start_date"]
investment["maturity_date"] = data["maturity_date"]
investment["compounding"] = data.get("compounding", "quarterly")
portfolio["investments"].append(investment)
save_portfolio(portfolio)
return jsonify({"status": "ok", "id": inv_id})
@app.route("/api/investment/<inv_id>", methods=["DELETE"])
def delete_investment(inv_id):
portfolio = load_portfolio()
portfolio["investments"] = [i for i in portfolio["investments"] if i["id"] != inv_id]
save_portfolio(portfolio)
_price_cache.pop(inv_id, None)
return jsonify({"status": "ok"})
@app.route("/api/investment/<inv_id>", methods=["PUT"])
def edit_investment(inv_id):
data = request.json
portfolio = load_portfolio()
for inv in portfolio["investments"]:
if inv["id"] == inv_id:
inv["name"] = data.get("name", inv["name"])
# Handle type change
new_type = data.get("type")
if new_type and new_type != inv["type"]:
inv["type"] = new_type
inv["category"] = data.get("category", new_type)
inv_type = inv["type"]
# Update type-specific fields
if inv_type in ("stock", "etf", "gold_etf"):
if data.get("ticker"):
inv["ticker"] = data["ticker"]
inv.setdefault("transactions", [])
elif inv_type == "mutual_fund":
if data.get("scheme_code"):
inv["scheme_code"] = data["scheme_code"]
inv.setdefault("transactions", [])
elif inv_type == "crypto":
if data.get("coin_id"):
inv["coin_id"] = data["coin_id"]
inv.setdefault("transactions", [])
elif inv_type == "pf":
if data.get("interest_rate") is not None:
inv["interest_rate"] = data["interest_rate"]
inv.setdefault("contributions", [])
elif inv_type == "fd":
for key in ("principal", "interest_rate", "start_date", "maturity_date", "compounding"):
if data.get(key) is not None:
inv[key] = data[key]
break
save_portfolio(portfolio)
_price_cache.pop(inv_id, None)
return jsonify({"status": "ok"})
@app.route("/api/investment/<inv_id>/transaction", methods=["POST"])
def add_transaction(inv_id):
data = request.json
portfolio = load_portfolio()
for inv in portfolio["investments"]:
if inv["id"] == inv_id:
t = {**data, "id": str(uuid.uuid4())[:8]}
if inv["type"] == "pf":
inv.setdefault("contributions", []).append(t)
else:
inv.setdefault("transactions", []).append(t)
break
save_portfolio(portfolio)
return jsonify({"status": "ok"})
@app.route("/api/investment/<inv_id>/transaction/<txn_id>", methods=["DELETE"])
def delete_transaction(inv_id, txn_id):
portfolio = load_portfolio()
for inv in portfolio["investments"]:
if inv["id"] == inv_id:
if inv["type"] == "pf":
inv["contributions"] = [c for c in inv.get("contributions", []) if c["id"] != txn_id]
else:
inv["transactions"] = [t for t in inv.get("transactions", []) if t["id"] != txn_id]
break
save_portfolio(portfolio)
return jsonify({"status": "ok"})
@app.route("/api/investment/<inv_id>/transaction/<txn_id>", methods=["PUT"])
def edit_transaction(inv_id, txn_id):
data = request.json
portfolio = load_portfolio()
for inv in portfolio["investments"]:
if inv["id"] == inv_id:
if inv["type"] == "pf":
for c in inv.get("contributions", []):
if c["id"] == txn_id:
c["date"] = data.get("date", c["date"])
c["amount"] = data.get("amount", c["amount"])
break
else:
for t in inv.get("transactions", []):
if t["id"] == txn_id:
t["date"] = data.get("date", t["date"])
t["quantity"] = data.get("quantity", t["quantity"])
t["buy_price"] = data.get("buy_price", t["buy_price"])
break
break
save_portfolio(portfolio)
return jsonify({"status": "ok"})
@app.route("/api/refresh", methods=["POST"])
def refresh_prices():
global _price_cache, _historical_cache, _usd_inr_rate
_price_cache = {}
_historical_cache = {}
_usd_inr_rate = None
return jsonify({"status": "ok"})
@app.route("/api/exchange-rate")
def exchange_rate():
rate = get_usd_inr_rate()
return jsonify({"usd_inr": rate})
@app.route("/api/historical")
def historical():
view = request.args.get("view", "value") # "value", "returns", or "current"
use_inflation = request.args.get("inflation", "false") == "true"
use_benchmark = request.args.get("benchmark", "false") == "true"
portfolio = load_portfolio()
investments = portfolio.get("investments", [])
if not investments:
return jsonify({"dates": [], "values": [], "invested": []})
now = datetime.now()
# Find earliest date across all investments
all_dates = []
for inv in investments:
if inv["type"] == "fd":
all_dates.append(inv["start_date"])
elif inv["type"] == "pf":
for c in inv.get("contributions", []):
all_dates.append(c["date"])
else:
for t in inv.get("transactions", []):
all_dates.append(t["date"])
if not all_dates:
return jsonify({"dates": [], "values": [], "invested": []})
start_date = min(all_dates)
end_date = now.strftime("%Y-%m-%d")
# Fetch historical prices for all market investments
hist_prices = {}
for inv in investments:
if inv["type"] in ("stock", "etf", "gold_etf", "mutual_fund", "crypto"):
hist_prices[inv["id"]] = get_historical_prices(inv, start_date, end_date)
# Generate weekly date points
current = datetime.strptime(start_date, "%Y-%m-%d")
end = datetime.strptime(end_date, "%Y-%m-%d")
date_points = []
while current <= end:
date_points.append(current.strftime("%Y-%m-%d"))
current += timedelta(days=7)
if date_points and date_points[-1] != end_date:
date_points.append(end_date)
# Get inflation data if needed
cpi_data = None
if use_inflation:
cpi_data = get_inflation_data()
values = []
invested_values = []
for dp in date_points:
total = 0
total_invested = 0
dp_dt = datetime.strptime(dp, "%Y-%m-%d")
for inv in investments:
inv_type = inv["type"]
if inv_type == "fd":
maturity = datetime.strptime(inv["maturity_date"], "%Y-%m-%d") if inv.get("maturity_date") else None
start = datetime.strptime(inv["start_date"], "%Y-%m-%d")
if view == "current":
# Skip matured FDs in current holdings view
if maturity and now > maturity:
continue
if dp_dt >= start:
total += calculate_fd_value(inv, dp)
else:
# Extrapolate backwards: discount the principal
principal = float(inv["principal"])
rate = float(inv["interest_rate"]) / 100
compounding = inv.get("compounding", "quarterly")
n_map = {"monthly": 12, "quarterly": 4, "half_yearly": 2, "yearly": 1}
n = n_map.get(compounding, 4)
years_back = (start - dp_dt).days / 365.25
total += principal / ((1 + rate / n) ** (n * years_back))
elif dp_dt >= start:
fd_val = calculate_fd_value(inv, dp)
total += fd_val
if fd_val > 0:
total_invested += float(inv["principal"])
elif inv_type == "pf":
total += calculate_pf_value(inv, dp)
total_invested += sum(float(c["amount"]) for c in inv.get("contributions", []) if c["date"] <= dp)
else:
transactions = inv.get("transactions", [])
prices = hist_prices.get(inv["id"], {})
# Find nearest price (look back up to 7 days)
price = None
for offset in range(7):
check_date = (dp_dt - timedelta(days=offset)).strftime("%Y-%m-%d")
if check_date in prices:
price = prices[check_date]
break
if price is None:
continue
if view == "current":
qty = sum(float(t["quantity"]) for t in transactions)
else:
active_txns = [t for t in transactions if t["date"] <= dp]
qty = sum(float(t["quantity"]) for t in active_txns)
invested = sum(float(t["quantity"]) * float(t["buy_price"]) for t in active_txns)
total_invested += invested
total += price * qty
# Apply inflation adjustment (interpolate monthly within years)
if use_inflation and cpi_data:
dp_year = dp_dt.year
now_year = now.year
now_month = now.month
# Interpolate CPI for the date point
cpi_y = cpi_data.get(dp_year, cpi_data.get(min(cpi_data.keys(), key=lambda y: abs(y - dp_year))))
cpi_y_next = cpi_data.get(dp_year + 1, cpi_y * 1.05)
frac = (dp_dt.month - 1) / 12.0
dp_cpi = cpi_y + (cpi_y_next - cpi_y) * frac
# Interpolate CPI for now
now_cpi_y = cpi_data.get(now_year, cpi_data.get(max(cpi_data.keys())))
now_cpi_next = cpi_data.get(now_year + 1, now_cpi_y * 1.05)
now_frac = (now_month - 1) / 12.0
now_cpi = now_cpi_y + (now_cpi_next - now_cpi_y) * now_frac
if dp_cpi:
factor = now_cpi / dp_cpi
total = total * factor
total_invested = total_invested * factor
values.append(round(total, 2))
invested_values.append(round(total_invested, 2))
result = {"dates": date_points, "values": values, "invested": invested_values}
# Add Nifty 50 benchmark data if requested
# Simulates: "what if every rupee invested went into Nifty 50 instead?"
if use_benchmark and date_points:
nifty_inv = {"id": "_nifty50", "type": "stock", "ticker": "^NSEI"}
nifty_prices = get_historical_prices(nifty_inv, date_points[0], date_points[-1])
def get_nifty_price(date_str):
dt = datetime.strptime(date_str, "%Y-%m-%d")
for offset in range(7):
check = (dt - timedelta(days=offset)).strftime("%Y-%m-%d")
if check in nifty_prices:
return nifty_prices[check]
return None
# Collect all cash flows: (date, amount) for each investment
# For zero-cost acquisitions, use market value at acquisition date
cash_flows = []
for inv in investments:
inv_type = inv["type"]
if inv_type == "fd":
cash_flows.append((inv["start_date"], float(inv["principal"])))
elif inv_type == "pf":
for c in inv.get("contributions", []):
cash_flows.append((c["date"], float(c["amount"])))
else:
inv_prices = hist_prices.get(inv["id"], {})
for t in inv.get("transactions", []):
qty = float(t["quantity"])
buy_price = float(t["buy_price"])
if buy_price > 0:
amt = qty * buy_price
elif qty > 0 and inv_prices:
# Zero-cost acquisition: use market value at acquisition date
t_dt = datetime.strptime(t["date"], "%Y-%m-%d")
mkt_price = None
for offset in range(7):
check = (t_dt - timedelta(days=offset)).strftime("%Y-%m-%d")
if check in inv_prices:
mkt_price = inv_prices[check]
break
amt = qty * mkt_price if mkt_price else 0
else:
amt = 0
cash_flows.append((t["date"], amt))
# Sort cash flows by date
cash_flows.sort(key=lambda x: x[0])
# For each cash flow, compute Nifty units bought
nifty_units = [] # list of (date, units)
for cf_date, cf_amount in cash_flows:
price = get_nifty_price(cf_date)
if price and price > 0 and cf_amount > 0:
nifty_units.append((cf_date, cf_amount / price))
# Portfolio Value / Returns benchmark: "what if every rupee invested went into Nifty 50?"
# For each date point, sum units accumulated so far × current Nifty price
benchmark_values = []
cf_idx = 0
cumulative_units = 0.0
for dp in date_points:
# Accumulate units from cash flows up to this date
while cf_idx < len(nifty_units) and nifty_units[cf_idx][0] <= dp:
cumulative_units += nifty_units[cf_idx][1]
cf_idx += 1
nifty_price = get_nifty_price(dp)
if nifty_price is not None and cumulative_units > 0:
benchmark_values.append(round(cumulative_units * nifty_price, 2))
else:
benchmark_values.append(None)
result["benchmark"] = benchmark_values
return jsonify(result)
@app.route("/api/historical-allocation")
def historical_allocation():
"""Return allocation breakdown by category at each date point."""
portfolio = load_portfolio()
investments = portfolio.get("investments", [])
if not investments:
return jsonify({"dates": [], "allocations": {}})
now = datetime.now()
# Find earliest date across all investments
all_dates = []
for inv in investments:
if inv["type"] == "fd":
all_dates.append(inv["start_date"])
elif inv["type"] == "pf":
for c in inv.get("contributions", []):
all_dates.append(c["date"])
else:
for t in inv.get("transactions", []):
all_dates.append(t["date"])
if not all_dates:
return jsonify({"dates": [], "allocations": {}})
start_date = min(all_dates)
end_date = now.strftime("%Y-%m-%d")
# Fetch historical prices for all market investments
hist_prices = {}
for inv in investments:
if inv["type"] in ("stock", "etf", "gold_etf", "mutual_fund", "crypto"):
hist_prices[inv["id"]] = get_historical_prices(inv, start_date, end_date)
# Generate weekly date points
current = datetime.strptime(start_date, "%Y-%m-%d")
end = datetime.strptime(end_date, "%Y-%m-%d")
date_points = []
while current <= end:
date_points.append(current.strftime("%Y-%m-%d"))
current += timedelta(days=7)
if date_points and date_points[-1] != end_date:
date_points.append(end_date)
# Track values per category at each date point
categories = set()
# Initialize: list of dicts, one per date point
alloc_per_date = [{} for _ in date_points]
for dp_idx, dp in enumerate(date_points):
dp_dt = datetime.strptime(dp, "%Y-%m-%d")
for inv in investments:
inv_type = inv["type"]
cat = inv.get("category", inv_type)
val = 0
if inv_type == "fd":
start = datetime.strptime(inv["start_date"], "%Y-%m-%d")
if dp_dt >= start:
val = calculate_fd_value(inv, dp)
elif inv_type == "pf":
val = calculate_pf_value(inv, dp)
else:
transactions = inv.get("transactions", [])
prices = hist_prices.get(inv["id"], {})
price = None
for offset in range(7):
check_date = (dp_dt - timedelta(days=offset)).strftime("%Y-%m-%d")
if check_date in prices:
price = prices[check_date]
break
if price is not None:
active_txns = [t for t in transactions if t["date"] <= dp]
qty = sum(float(t["quantity"]) for t in active_txns)
val = price * qty
if val > 0:
categories.add(cat)
alloc_per_date[dp_idx][cat] = alloc_per_date[dp_idx].get(cat, 0) + val
# Build response: allocations keyed by category, each a list parallel to dates
allocations = {}
for cat in categories:
allocations[cat] = [round(alloc_per_date[i].get(cat, 0), 2) for i in range(len(date_points))]
return jsonify({"dates": date_points, "allocations": allocations})
@app.route("/api/search/stock")
def search_stock():
q = request.args.get("q", "")