-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2748 lines (2489 loc) · 114 KB
/
Copy pathapp.py
File metadata and controls
2748 lines (2489 loc) · 114 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
"""
Net Worth Tracker
-----------------
Flask application with SQLite backend, multi-currency support (AUD base),
and detailed portfolio analytics. All data stored in prices.db.
"""
from flask import Flask, render_template, request, jsonify, send_from_directory
import yfinance as yf
import pandas as pd
import json
import os
import sqlite3
import time
from datetime import datetime, date, timedelta
from concurrent.futures import ThreadPoolExecutor, as_completed
from apscheduler.schedulers.background import BackgroundScheduler
from werkzeug.security import generate_password_hash, check_password_hash
from flask_jwt_extended import (
JWTManager, create_access_token, jwt_required, get_jwt_identity,
)
app = Flask(__name__, template_folder="templates", static_folder="static")
# SECURITY: JWT_SECRET_KEY must be set via env var in any real deployment — the
# fallback here is only so the app doesn't hard-crash on a fresh dev checkout.
# A default secret means anyone can forge valid tokens; this is not safe to ship
# as-is to a real multi-user deployment without setting this explicitly.
app.config["JWT_SECRET_KEY"] = os.environ.get("JWT_SECRET_KEY", "dev-only-insecure-change-me")
app.config["JWT_ACCESS_TOKEN_EXPIRES"] = timedelta(days=30) # long-lived — this is a personal finance app people check occasionally, not a banking session
jwt = JWTManager(app)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.environ.get("DATA_DIR", BASE_DIR)
FRONTEND_DIST = os.path.join(BASE_DIR, "frontend", "dist")
DB_FILE = os.path.join(DATA_DIR, "prices.db")
CSV_FILE = os.path.join(DATA_DIR, "all_trades.csv")
EXCEL_FILE = os.path.join(DATA_DIR, "AllTradesReport.xlsx")
SNAPSHOT_FILE = os.path.join(DATA_DIR, "snapshots.json")
# yfinance suffixes for exchanges
EXCHANGE_SUFFIX = {
"US": "",
"NASDAQ": "",
"NYSE": "",
"ASX": ".AX",
"LSE": ".L",
"TSX": ".TO",
}
def db():
"""Create and return a database connection, initializing tables if they don't exist."""
conn = sqlite3.connect(DB_FILE, timeout=30)
# WAL lets readers and writers work concurrently instead of blocking on a
# single file lock — needed now that sync fetches multiple symbols in parallel.
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
created_at TEXT NOT NULL
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS dashboard_layout (
user_id INTEGER PRIMARY KEY,
widget_order TEXT NOT NULL DEFAULT '',
widget_visible TEXT NOT NULL DEFAULT '',
stat_keys TEXT NOT NULL DEFAULT '',
updated_at TEXT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id)
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS prices (
symbol TEXT NOT NULL,
date TEXT NOT NULL,
close REAL NOT NULL,
PRIMARY KEY (symbol, date)
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS sync_log (
symbol TEXT PRIMARY KEY,
last_synced TEXT NOT NULL,
cached_from TEXT,
cached_to TEXT
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS snapshots (
date TEXT NOT NULL,
super REAL NOT NULL,
cash REAL NOT NULL,
user_id INTEGER NOT NULL DEFAULT 1,
PRIMARY KEY (user_id, date)
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS transactions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
date TEXT NOT NULL,
exchange TEXT NOT NULL,
ticker TEXT NOT NULL,
name TEXT NOT NULL,
action TEXT NOT NULL,
units REAL NOT NULL,
price REAL NOT NULL,
currency TEXT NOT NULL,
brokerage REAL NOT NULL DEFAULT 0,
brokerage_currency TEXT NOT NULL DEFAULT 'AUD',
exch_rate REAL NOT NULL DEFAULT 1.0,
value REAL NOT NULL
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS cash_accounts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
institution TEXT,
type TEXT,
name TEXT,
balance REAL NOT NULL DEFAULT 0,
country TEXT NOT NULL DEFAULT 'AU'
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS super_holdings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
class TEXT,
allocation_pct REAL NOT NULL,
country TEXT NOT NULL
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS country_overrides (
symbol TEXT NOT NULL,
country TEXT NOT NULL,
user_id INTEGER NOT NULL DEFAULT 1,
PRIMARY KEY (user_id, symbol)
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS holding_meta (
symbol TEXT PRIMARY KEY,
sector TEXT,
industry TEXT,
long_name TEXT,
website TEXT,
logo_url TEXT
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS milestones (
id INTEGER PRIMARY KEY AUTOINCREMENT,
date TEXT NOT NULL,
title TEXT NOT NULL,
description TEXT,
category TEXT NOT NULL,
value REAL,
type TEXT DEFAULT 'achievement',
target_value REAL,
current_value REAL,
is_achieved INTEGER DEFAULT 0,
linked_metric TEXT,
achieved_date TEXT
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS records (
key TEXT NOT NULL,
value REAL NOT NULL,
date TEXT NOT NULL,
user_id INTEGER NOT NULL DEFAULT 1,
PRIMARY KEY (user_id, key)
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS holding_groups (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
symbols TEXT NOT NULL DEFAULT ''
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS dividends (
id INTEGER PRIMARY KEY AUTOINCREMENT,
date TEXT NOT NULL,
symbol TEXT NOT NULL,
ticker TEXT NOT NULL,
exchange TEXT NOT NULL,
per_share REAL NOT NULL,
units REAL NOT NULL,
currency TEXT NOT NULL,
gross_amount REAL NOT NULL,
gross_amount_aud REAL NOT NULL,
franking_pct REAL NOT NULL DEFAULT 0,
franking_credit_aud REAL NOT NULL DEFAULT 0,
withholding_tax_pct REAL NOT NULL DEFAULT 0,
net_amount_aud REAL NOT NULL,
source TEXT NOT NULL DEFAULT 'manual',
user_id INTEGER NOT NULL DEFAULT 1,
UNIQUE(user_id, symbol, date)
)
""")
# Migrate existing sync_log table — tracks sync health, not just successful ranges
for col, defn in [
("last_error", "TEXT"), # non-null when the most recent sync attempt failed
("last_attempt", "TEXT"), # timestamp of the most recent attempt, success or not
]:
try:
conn.execute(f"ALTER TABLE sync_log ADD COLUMN {col} {defn}")
except:
pass
# Migrate existing milestones table
for col, defn in [
("type", "TEXT DEFAULT 'achievement'"),
("target_value", "REAL"),
("current_value", "REAL"),
("is_achieved", "INTEGER DEFAULT 0"),
("linked_metric", "TEXT"),
("achieved_date", "TEXT"),
("linked_metrics", "TEXT"), # comma-separated list, e.g. "cash,portfolio" — supersedes linked_metric
("currency", "TEXT DEFAULT 'AUD'"), # currency the target/current value is expressed in: AUD or USD
]:
try:
conn.execute(f"ALTER TABLE milestones ADD COLUMN {col} {defn}")
except:
pass
# Multi-user migration: every table holding a person's own financial data gets a
# user_id column. Deliberately NOT applied to prices/sync_log/holding_meta — those
# are the shared market-data cache (GOOG's price is the same for every user), and
# keeping them global avoids N users redundantly hitting yfinance for the same symbol.
# Existing single-user rows get user_id=1 so pre-migration data isn't orphaned —
# whichever account is created first inherits the pre-existing data.
for table in ["transactions", "cash_accounts", "super_holdings",
"milestones", "holding_groups"]:
try:
conn.execute(f"ALTER TABLE {table} ADD COLUMN user_id INTEGER NOT NULL DEFAULT 1")
except:
pass
# snapshots originally had `date` alone as PRIMARY KEY — two users both getting a
# snapshot on the same date (e.g. the monthly auto-snapshot) would collide and
# overwrite each other. Same fix as dividends/records/country_overrides above.
existing_snap_sql = conn.execute(
"SELECT sql FROM sqlite_master WHERE type='table' AND name='snapshots'"
).fetchone()
if existing_snap_sql and "PRIMARY KEY (user_id, date)" not in existing_snap_sql[0]:
conn.execute("ALTER TABLE snapshots RENAME TO snapshots_old")
conn.execute("""
CREATE TABLE snapshots (
date TEXT NOT NULL, super REAL NOT NULL, cash REAL NOT NULL,
user_id INTEGER NOT NULL DEFAULT 1, PRIMARY KEY (user_id, date)
)
""")
has_user_id = conn.execute("PRAGMA table_info(snapshots_old)").fetchall()
if any(col[1] == "user_id" for col in has_user_id):
conn.execute("INSERT INTO snapshots (date, super, cash, user_id) SELECT date, super, cash, COALESCE(user_id, 1) FROM snapshots_old")
else:
conn.execute("INSERT INTO snapshots (date, super, cash, user_id) SELECT date, super, cash, 1 FROM snapshots_old")
conn.execute("DROP TABLE snapshots_old")
# country_overrides originally had `symbol` alone as PRIMARY KEY — two users
# overriding the same symbol's country would collide. Same fix as dividends/records.
existing_co_sql = conn.execute(
"SELECT sql FROM sqlite_master WHERE type='table' AND name='country_overrides'"
).fetchone()
if existing_co_sql and "PRIMARY KEY (user_id, symbol)" not in existing_co_sql[0]:
conn.execute("ALTER TABLE country_overrides RENAME TO country_overrides_old")
conn.execute("""
CREATE TABLE country_overrides (
symbol TEXT NOT NULL, country TEXT NOT NULL,
user_id INTEGER NOT NULL DEFAULT 1, PRIMARY KEY (user_id, symbol)
)
""")
has_user_id = conn.execute("PRAGMA table_info(country_overrides_old)").fetchall()
if any(col[1] == "user_id" for col in has_user_id):
conn.execute("INSERT INTO country_overrides (symbol, country, user_id) SELECT symbol, country, COALESCE(user_id, 1) FROM country_overrides_old")
else:
conn.execute("INSERT INTO country_overrides (symbol, country, user_id) SELECT symbol, country, 1 FROM country_overrides_old")
conn.execute("DROP TABLE country_overrides_old")
# records originally had `key` alone as PRIMARY KEY (e.g. 'portfolio_high') — two
# different users would collide and overwrite each other's all-time-high record.
# Same rebuild-required situation as dividends above.
existing_records_sql = conn.execute(
"SELECT sql FROM sqlite_master WHERE type='table' AND name='records'"
).fetchone()
if existing_records_sql and "PRIMARY KEY (user_id, key)" not in existing_records_sql[0]:
conn.execute("ALTER TABLE records RENAME TO records_old")
conn.execute("""
CREATE TABLE records (
key TEXT NOT NULL, value REAL NOT NULL, date TEXT NOT NULL,
user_id INTEGER NOT NULL DEFAULT 1, PRIMARY KEY (user_id, key)
)
""")
has_user_id = conn.execute("PRAGMA table_info(records_old)").fetchall()
if any(col[1] == "user_id" for col in has_user_id):
conn.execute("INSERT INTO records (key, value, date, user_id) SELECT key, value, date, COALESCE(user_id, 1) FROM records_old")
else:
conn.execute("INSERT INTO records (key, value, date, user_id) SELECT key, value, date, 1 FROM records_old")
conn.execute("DROP TABLE records_old")
# dividends needs UNIQUE(user_id, symbol, date), not just UNIQUE(symbol, date) — two
# different users holding the same stock would otherwise collide and overwrite each
# other's dividend rows. SQLite can't ALTER a UNIQUE constraint in place, so any
# database created before this fix needs the table rebuilt, not just a column added.
existing_sql = conn.execute(
"SELECT sql FROM sqlite_master WHERE type='table' AND name='dividends'"
).fetchone()
if existing_sql and "UNIQUE(user_id, symbol, date)" not in existing_sql[0]:
conn.execute("ALTER TABLE dividends RENAME TO dividends_old")
conn.execute("""
CREATE TABLE dividends (
id INTEGER PRIMARY KEY AUTOINCREMENT,
date TEXT NOT NULL, symbol TEXT NOT NULL, ticker TEXT NOT NULL, exchange TEXT NOT NULL,
per_share REAL NOT NULL, units REAL NOT NULL, currency TEXT NOT NULL,
gross_amount REAL NOT NULL, gross_amount_aud REAL NOT NULL,
franking_pct REAL NOT NULL DEFAULT 0, franking_credit_aud REAL NOT NULL DEFAULT 0,
withholding_tax_pct REAL NOT NULL DEFAULT 0, net_amount_aud REAL NOT NULL,
source TEXT NOT NULL DEFAULT 'manual', user_id INTEGER NOT NULL DEFAULT 1,
UNIQUE(user_id, symbol, date)
)
""")
old_cols = "id,date,symbol,ticker,exchange,per_share,units,currency,gross_amount," \
"gross_amount_aud,franking_pct,franking_credit_aud,withholding_tax_pct,net_amount_aud,source"
has_user_id = conn.execute("PRAGMA table_info(dividends_old)").fetchall()
if any(col[1] == "user_id" for col in has_user_id):
conn.execute(f"INSERT INTO dividends ({old_cols}, user_id) SELECT {old_cols}, COALESCE(user_id, 1) FROM dividends_old")
else:
conn.execute(f"INSERT INTO dividends ({old_cols}, user_id) SELECT {old_cols}, 1 FROM dividends_old")
conn.execute("DROP TABLE dividends_old")
conn.commit()
return conn
def current_user_id():
"""Int user id from the JWT — flask-jwt-extended requires string identities,
so this is the one place that casts back to int for SQL params."""
return int(get_jwt_identity())
@app.route("/api/register", methods=["POST"])
def register():
# Deliberately permissive by request: no email format required (plain usernames
# are fine), no minimum password length. This is intended for trusted personal/
# local use, not a public-facing signup — if this instance is ever exposed
# beyond your own network, this is the first thing to tighten back up.
data = request.json or {}
email = (data.get("email") or "").strip().lower()
password = data.get("password") or ""
if not email:
return jsonify({"ok": False, "error": "Username required"}), 400
if not password:
return jsonify({"ok": False, "error": "Password required"}), 400
conn = db()
if conn.execute("SELECT id FROM users WHERE email = ?", (email,)).fetchone():
conn.close()
return jsonify({"ok": False, "error": "An account with this email already exists"}), 409
cur = conn.execute(
"INSERT INTO users (email, password_hash, created_at) VALUES (?, ?, ?)",
(email, generate_password_hash(password), datetime.now().isoformat()),
)
user_id = cur.lastrowid
conn.commit()
conn.close()
token = create_access_token(identity=str(user_id))
return jsonify({"ok": True, "token": token, "user": {"id": user_id, "email": email}})
@app.route("/api/login", methods=["POST"])
def login():
data = request.json or {}
email = (data.get("email") or "").strip().lower()
password = data.get("password") or ""
conn = db()
row = conn.execute("SELECT id, password_hash FROM users WHERE email = ?", (email,)).fetchone()
conn.close()
# Deliberately identical error for "no such user" and "wrong password" — distinguishing
# them lets an attacker enumerate registered emails.
if not row or not check_password_hash(row[1], password):
return jsonify({"ok": False, "error": "Invalid email or password"}), 401
token = create_access_token(identity=str(row[0]))
return jsonify({"ok": True, "token": token, "user": {"id": row[0], "email": email}})
@app.route("/api/me", methods=["GET"])
@jwt_required()
def get_me():
conn = db()
row = conn.execute("SELECT id, email, created_at FROM users WHERE id = ?", (current_user_id(),)).fetchone()
conn.close()
if not row:
return jsonify({"ok": False}), 404
return jsonify({"id": row[0], "email": row[1], "created_at": row[2]})
@app.route("/api/dashboard-layout", methods=["GET"])
@jwt_required()
def get_dashboard_layout():
conn = db()
row = conn.execute(
"SELECT widget_order, widget_visible, stat_keys FROM dashboard_layout WHERE user_id = ?",
(current_user_id(),),
).fetchone()
conn.close()
if not row:
return jsonify({"widget_order": None, "widget_visible": None, "stat_keys": None})
return jsonify({
"widget_order": json.loads(row[0]) if row[0] else None,
"widget_visible": json.loads(row[1]) if row[1] else None,
"stat_keys": json.loads(row[2]) if row[2] else None,
})
@app.route("/api/dashboard-layout", methods=["POST"])
@jwt_required()
def save_dashboard_layout():
data = request.json or {}
conn = db()
conn.execute(
"INSERT INTO dashboard_layout (user_id, widget_order, widget_visible, stat_keys, updated_at) "
"VALUES (?, ?, ?, ?, ?) ON CONFLICT(user_id) DO UPDATE SET "
"widget_order=excluded.widget_order, widget_visible=excluded.widget_visible, "
"stat_keys=excluded.stat_keys, updated_at=excluded.updated_at",
(current_user_id(), json.dumps(data.get("widget_order")), json.dumps(data.get("widget_visible")),
json.dumps(data.get("stat_keys")), datetime.now().isoformat()),
)
conn.commit()
conn.close()
return jsonify({"ok": True})
def yf_symbol(ticker, exchange):
"""Normalize the ticker symbol for yfinance based on exchange."""
if "=X" in ticker:
return ticker
suffix = EXCHANGE_SUFFIX.get((exchange or "").upper(), "")
return f"{ticker.upper()}{suffix}"
def get_currency_from_exchange(exchange):
"""Determine instrument currency based on exchange."""
if (exchange or "").upper() in ["NASDAQ", "NYSE", "US"]:
return "USD"
return "AUD" # Default to AUD (ASX)
def get_historical_exchange_rate(conn, date_str):
"""Retrieve AUD/USD exchange rate for a given date. Try cache, then yfinance."""
# Try database cache
row = conn.execute(
"SELECT close FROM prices WHERE symbol = 'AUDUSD=X' AND date = ?", (date_str,)
).fetchone()
if row:
return float(row[0])
# Try fetching from yfinance for a short window around the date
try:
t_date = pd.Timestamp(date_str)
t = yf.Ticker("AUDUSD=X")
hist = t.history(start=t_date - timedelta(days=3), end=t_date + timedelta(days=4))
if not hist.empty:
# Find the closest date before or equal to target date
hist.index = hist.index.tz_localize(None)
available_dates = hist.index[hist.index <= t_date]
if len(available_dates) > 0:
closest_date = available_dates[-1]
else:
closest_date = hist.index[0]
rate = float(hist.loc[closest_date, "Close"])
# Cache it
conn.execute(
"INSERT OR REPLACE INTO prices (symbol, date, close) VALUES ('AUDUSD=X', ?, ?)",
(closest_date.strftime("%Y-%m-%d"), rate)
)
conn.commit()
return rate
except Exception as e:
print(f"[warning] Failed to fetch exchange rate for {date_str}: {e}")
# Fallback if everything else fails: return latest cached rate, or 0.65
fallback_row = conn.execute(
"SELECT close FROM prices WHERE symbol = 'AUDUSD=X' ORDER BY date DESC LIMIT 1"
).fetchone()
if fallback_row:
return float(fallback_row[0])
return 0.65
def ingest_excel_to_json():
"""Ingest transactions from AllTradesReport.xlsx Combined sheet to JSON file."""
if not os.path.exists(EXCEL_FILE):
return []
import openpyxl
transactions = []
conn = sqlite3.connect(DB_FILE)
try:
wb = openpyxl.load_workbook(EXCEL_FILE, read_only=True)
if "Combined" not in wb.sheetnames:
print("[error] 'Combined' sheet not found in AllTradesReport.xlsx")
return []
ws = wb["Combined"]
for idx, row in enumerate(ws.iter_rows(values_only=True)):
if idx < 3: # Skip metadata and headers (header is on row 3)
continue
if not row or row[0] is None:
continue
code = str(row[0]).strip().upper()
if code in ['TOTAL', 'CODE', 'ALL TRADES']:
continue
market = str(row[1]).strip().upper() if row[1] else ''
name = str(row[2]).strip() if row[2] else ''
dt = str(row[3])[:10] if row[3] else None
action_type = str(row[4]).strip().lower() if row[4] else ''
qty = float(row[5]) if row[5] is not None else 0.0
price = float(row[6]) if row[6] is not None else 0.0
currency = str(row[7]).strip().upper() if row[7] else ''
brokerage = float(row[9]) if row[9] is not None else 0.0
brokerage_currency = str(row[10]).strip().upper() if row[10] else ''
exch_rate = float(row[11]) if row[11] is not None else 1.0
val = float(row[12]) if row[12] is not None else 0.0
# Double-check multi-currency rate calculation
if currency == "USD" and exch_rate == 1.0:
exch_rate = get_historical_exchange_rate(conn, dt)
if val == 0.0:
sign = 1 if action_type == "buy" else -1
cost_in_instrument = (sign * abs(qty) * price) + brokerage
if currency == "USD":
val = cost_in_instrument / exch_rate
else:
val = cost_in_instrument
transactions.append({
"date": dt,
"exchange": market,
"ticker": code,
"name": name,
"action": action_type,
"units": abs(qty),
"price": price,
"currency": currency,
"brokerage": brokerage,
"brokerage_currency": brokerage_currency,
"exch_rate": exch_rate,
"value": val
})
# Sort chronologically
transactions.sort(key=lambda x: x["date"])
with open(DATA_FILE, "w", encoding="utf-8") as f:
json.dump(transactions, f, indent=2)
print(f"[backend] Successfully auto-ingested {len(transactions)} trades from Excel.")
except Exception as e:
print(f"[error] Failed to ingest Excel: {e}")
finally:
conn.close()
return transactions
def ingest_csv_to_json():
"""Ingest transactions from CSV to JSON file."""
if not os.path.exists(CSV_FILE):
return []
import csv
transactions = []
conn = sqlite3.connect(DB_FILE)
try:
with open(CSV_FILE, mode='r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for idx, row in enumerate(reader):
code = row["Code"].strip().upper()
market = row["Market Code"].strip().upper()
name = row["Name"].strip()
dt = row["Date"].strip()
action_type = row["Type"].strip().lower()
qty = float(row["Qty"])
price = float(row["Price"])
currency = row["Instrument Currency"].strip().upper()
brokerage_str = row.get("Brokerage", "0").strip()
brokerage = float(brokerage_str) if brokerage_str else 0.0
brokerage_currency = row.get("Brokerage Currency", currency).strip().upper()
exch_rate_str = row.get("Exch. Rate", "").strip()
exch_rate = float(exch_rate_str) if exch_rate_str else 1.0
val_str = row.get("Value", "").strip()
val = float(val_str) if val_str else 0.0
# Double-check multi-currency rate calculation
if currency == "USD" and exch_rate == 1.0:
exch_rate = get_historical_exchange_rate(conn, dt)
if val == 0.0:
sign = 1 if action_type == "buy" else -1
cost_in_instrument = (sign * abs(qty) * price) + brokerage
if currency == "USD":
val = cost_in_instrument / exch_rate
else:
val = cost_in_instrument
transactions.append({
"date": dt,
"exchange": market,
"ticker": code,
"name": name,
"action": action_type,
"units": abs(qty),
"price": price,
"currency": currency,
"brokerage": brokerage,
"brokerage_currency": brokerage_currency,
"exch_rate": exch_rate,
"value": val
})
# Sort chronologically
transactions.sort(key=lambda x: x["date"])
with open(DATA_FILE, "w", encoding="utf-8") as f:
json.dump(transactions, f, indent=2)
print(f"[backend] Successfully auto-ingested {len(transactions)} trades from CSV.")
except Exception as e:
print(f"[error] Failed to ingest CSV: {e}")
finally:
conn.close()
return transactions
def load_transactions(user_id):
"""Load one user's transactions from DB."""
conn = db()
rows = conn.execute(
"SELECT id, date, exchange, ticker, name, action, units, price, currency, "
"brokerage, brokerage_currency, exch_rate, value FROM transactions "
"WHERE user_id = ? ORDER BY date, id", (user_id,)
).fetchall()
conn.close()
cols = ["id", "date", "exchange", "ticker", "name", "action", "units", "price",
"currency", "brokerage", "brokerage_currency", "exch_rate", "value"]
return [dict(zip(cols, row)) for row in rows]
def save_transactions(txns, user_id):
"""Save transactions to DB (full replace for this user only, sorted by date)."""
txns_sorted = sorted(txns, key=lambda x: x.get("date", ""))
cols = ("date", "exchange", "ticker", "name", "action", "units", "price",
"currency", "brokerage", "brokerage_currency", "exch_rate", "value")
conn = db()
conn.execute("DELETE FROM transactions WHERE user_id = ?", (user_id,))
conn.executemany(
f"INSERT INTO transactions ({','.join(cols)}, user_id) VALUES ({','.join('?' * len(cols))}, ?)",
[[t.get(c, 0 if c in ("units","price","brokerage","exch_rate","value") else "") for c in cols] + [user_id]
for t in txns_sorted]
)
conn.commit()
conn.close()
# ─── Cash Accounts, Super Holdings, Country Overrides ───────
def load_cash_accounts(user_id):
conn = db()
rows = conn.execute(
"SELECT institution, type, name, balance, country FROM cash_accounts WHERE user_id = ? ORDER BY id", (user_id,)
).fetchall()
conn.close()
return [{"institution": r[0], "type": r[1], "name": r[2], "balance": r[3], "country": r[4]} for r in rows]
def save_cash_accounts(accounts, user_id):
conn = db()
conn.execute("DELETE FROM cash_accounts WHERE user_id = ?", (user_id,))
conn.executemany(
"INSERT INTO cash_accounts (institution, type, name, balance, country, user_id) VALUES (?,?,?,?,?,?)",
[(a.get("institution",""), a.get("type",""), a.get("name",""), a.get("balance",0), a.get("country","AU"), user_id) for a in accounts]
)
conn.commit()
conn.close()
def load_super_holdings(user_id):
conn = db()
rows = conn.execute(
"SELECT name, class, allocation_pct, country FROM super_holdings WHERE user_id = ? ORDER BY id", (user_id,)
).fetchall()
conn.close()
return [{"name": r[0], "class": r[1], "allocation_pct": r[2], "country": r[3]} for r in rows]
def save_super_holdings(holdings, user_id):
conn = db()
conn.execute("DELETE FROM super_holdings WHERE user_id = ?", (user_id,))
conn.executemany(
"INSERT INTO super_holdings (name, class, allocation_pct, country, user_id) VALUES (?,?,?,?,?)",
[(h.get("name",""), h.get("class",""), h.get("allocation_pct",0), h.get("country",""), user_id) for h in holdings]
)
conn.commit()
conn.close()
def load_country_overrides(user_id):
conn = db()
rows = conn.execute("SELECT symbol, country FROM country_overrides WHERE user_id = ?", (user_id,)).fetchall()
conn.close()
return {r[0]: r[1] for r in rows}
def save_country_overrides(overrides, user_id):
conn = db()
conn.execute("DELETE FROM country_overrides WHERE user_id = ?", (user_id,))
conn.executemany(
"INSERT INTO country_overrides (symbol, country, user_id) VALUES (?,?,?)",
[(k, v, user_id) for k, v in overrides.items()]
)
conn.commit()
conn.close()
def load_holding_meta():
conn = db()
rows = conn.execute(
"SELECT symbol, sector, industry, long_name, website, logo_url FROM holding_meta"
).fetchall()
conn.close()
return {r[0]: {"sector": r[1], "industry": r[2], "longName": r[3], "website": r[4], "logo_url": r[5]} for r in rows}
def save_holding_meta_one(symbol, entry):
"""Upsert a single symbol's metadata. Safe to call concurrently from multiple
sync threads — unlike a delete-all-then-reinsert-all pattern, this can't lose
another thread's in-flight write."""
conn = db()
conn.execute(
"INSERT INTO holding_meta (symbol, sector, industry, long_name, website, logo_url) VALUES (?,?,?,?,?,?) "
"ON CONFLICT(symbol) DO UPDATE SET sector=excluded.sector, industry=excluded.industry, "
"long_name=excluded.long_name, website=excluded.website, logo_url=excluded.logo_url",
(symbol, entry.get("sector", ""), entry.get("industry", ""), entry.get("longName", ""),
entry.get("website", ""), entry.get("logo_url", "")),
)
conn.commit()
conn.close()
def fetch_holding_meta(ticker, exchange):
"""Fetch sector, industry, logo from yfinance for a ticker. Returns dict or None."""
ysym = yf_symbol(ticker, exchange)
conn = db()
existing = conn.execute(
"SELECT sector, industry, long_name, website, logo_url FROM holding_meta WHERE symbol = ?", (ysym,)
).fetchone()
conn.close()
if existing:
return {"sector": existing[0], "industry": existing[1], "longName": existing[2], "website": existing[3], "logo_url": existing[4]}
try:
t = yf.Ticker(ysym)
info = t.info
website = info.get("website", "")
logo_url = ""
if website:
# Use Google Favicons service to pull the company's logo
logo_url = f"https://www.google.com/s2/favicons?domain={website.replace('https://','').replace('http://','').split('/')[0]}&sz=64"
entry = {
"sector": info.get("sector", ""),
"industry": info.get("industry", ""),
"longName": info.get("longName", ""),
"website": website,
"logo_url": logo_url,
}
save_holding_meta_one(ysym, entry)
return entry
except Exception as e:
print(f"[meta] Failed to fetch metadata for {ysym}: {e}")
return None
def get_holding_country(ticker, exchange, name, user_id):
"""Determine country for a holding: override > exchange heuristic > 'Unknown'."""
sym = yf_symbol(ticker, exchange)
overrides = load_country_overrides(user_id)
if sym in overrides:
return overrides[sym]
# Heuristic: US exchanges → US, ASX → AU, else based on name
ex_upper = (exchange or "").upper()
if ex_upper in ("NASDAQ", "NYSE", "US"):
return "US"
if ex_upper == "ASX":
return "AU"
return "Unknown"
def get_total_cash(user_id):
"""Sum all cash account balances."""
accounts = load_cash_accounts(user_id)
return round(sum(a.get("balance", 0) for a in accounts), 2)
# ─── End Config Helpers ────────────────────────────────────
def seed_historical_snapshots():
"""Seed the snapshots table from snapshots.json on first run (when table is empty)."""
conn = db()
count = conn.execute("SELECT COUNT(*) FROM snapshots").fetchone()[0]
conn.close()
if count > 0:
return
if not os.path.exists(SNAPSHOT_FILE):
return
try:
with open(SNAPSHOT_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
conn = db()
for entry in data:
conn.execute(
"INSERT OR REPLACE INTO snapshots (date, super, cash) VALUES (?, ?, ?)",
(entry["date"], entry["super"], entry["cash"]),
)
conn.commit()
conn.close()
print(f"[backend] Loaded {len(data)} cash/super snapshots from snapshots.json.")
except Exception as e:
print(f"[backend] Failed to seed snapshots: {e}")
def _fetch_with_retry(fn, attempts=2, delay=1.5):
"""Run fn() with a couple of retries for transient network/rate-limit errors."""
last_exc = None
for i in range(attempts):
try:
return fn()
except Exception as e:
last_exc = e
if i < attempts - 1:
time.sleep(delay)
raise last_exc
def sync_symbol(symbol, needed_start, needed_end, force=False):
"""Fetch and cache only missing historical daily close prices for symbol.
Opens its own DB connection so it's safe to call from a worker thread.
Returns (ok, message)."""
conn = db()
try:
# 15-minute cooldown check
row = conn.execute(
"SELECT cached_from, cached_to, last_synced FROM sync_log WHERE symbol = ?", (symbol,)
).fetchone()
now = pd.Timestamp.now()
if row is not None and not force:
cached_to = pd.Timestamp(row[1])
last_synced = pd.Timestamp(row[2])
if now - last_synced < timedelta(minutes=15) and needed_end < cached_to:
return True, "Cached recently"
# Yahoo doesn't publish a daily candle for a day that hasn't closed yet —
# asking for "today" via the daily endpoint reliably throws a
# "possibly delisted; no price data found" error, every symbol, every day,
# until market close. Today's live price comes from the intraday fetch
# below instead, so daily requests never go past the last fully elapsed day.
daily_cap = pd.Timestamp(date.today()) - timedelta(days=1)
ranges_to_fetch = []
if row is None:
ranges_to_fetch.append((needed_start, needed_end))
else:
cached_from = pd.Timestamp(row[0])
cached_to = pd.Timestamp(row[1])
if needed_start < cached_from:
ranges_to_fetch.append((needed_start, cached_from - timedelta(days=1)))
if needed_end > cached_to:
ranges_to_fetch.append((cached_to + timedelta(days=1), needed_end))
# Unconditionally (re)fetch the most recently closed trading day, even if
# cached_to already reaches it — a sync that ran while the market was still
# open only captures an in-progress intraday snapshot for that date, and
# that snapshot's own date makes cached_to look "caught up" even though the
# value isn't final. This guarantees it eventually gets overwritten by the
# real close, instead of getting permanently stuck (which is what was
# happening: the gap-fill range above collapses to an empty/inverted range
# once cached_to already equals daily_cap, so that date was never revisited).
ranges_to_fetch.append((daily_cap, daily_cap))
errors = []
for f_start, f_end in ranges_to_fetch:
f_end = min(f_end, daily_cap)
if f_start > f_end:
continue
try:
hist = _fetch_with_retry(
lambda: yf.Ticker(symbol).history(start=f_start, end=f_end + timedelta(days=1))
)
if hist.empty:
continue
hist.index = hist.index.tz_localize(None)
rows = [
(symbol, d.strftime("%Y-%m-%d"), float(c))
for d, c in hist["Close"].items()
]
conn.executemany(
"INSERT OR REPLACE INTO prices (symbol, date, close) VALUES (?, ?, ?)",
rows,
)
except Exception as e:
msg = str(e)
# yfinance raises this for any window with zero rows (market holiday,
# exchange-specific non-trading day, etc.) — genuinely benign, not a
# sync failure, so don't record it as an error.
if "possibly delisted" in msg.lower() or "no price data found" in msg.lower():
print(f"[sync] No data for {symbol} {f_start.date()} -> {f_end.date()} (holiday/non-trading day, not an error)")
continue
errors.append(msg)
print(f"[sync] Failed to fetch {symbol} {f_start.date()} -> {f_end.date()}: {e}")
# Fetch today's intraday price so we have live data even before market close.
# yfinance daily history() excludes the incomplete current day; intraday 1m
# data includes it as soon as the first trade prints.
try:
intraday = _fetch_with_retry(
lambda: yf.Ticker(symbol).history(period="1d", interval="1m")
)
if not intraday.empty:
intraday.index = intraday.index.tz_localize(None)
latest = intraday.iloc[-1]
latest_date = latest.name.strftime("%Y-%m-%d")
latest_close = float(latest["Close"])
# Only insert if this date is not already covered by daily history
existing = conn.execute(
"SELECT 1 FROM prices WHERE symbol = ? AND date = ?",
(symbol, latest_date),
).fetchone()
if not existing:
conn.execute(
"INSERT OR REPLACE INTO prices (symbol, date, close) VALUES (?, ?, ?)",
(symbol, latest_date, latest_close),
)
except Exception as e:
# Intraday is best-effort — a failure here alone shouldn't mark the whole
# sync as failed as long as daily history above succeeded.
print(f"[sync] Failed to fetch intraday for {symbol}: {e}")
# last_attempt/last_error record every attempt, success or not, so the UI can
# show accurate sync health even when a symbol has been failing for days.
# last_synced/cached_from/cached_to only advance on a clean, error-free run —
# using the ACTUAL date range present in the prices table, not the requested
# range, so cached_to isn't advanced to today when nothing was actually stored.
if errors:
conn.execute(
"INSERT INTO sync_log (symbol, last_synced, cached_from, cached_to, last_error, last_attempt) "
"VALUES (?, COALESCE((SELECT last_synced FROM sync_log WHERE symbol = ?), ?), "
"(SELECT cached_from FROM sync_log WHERE symbol = ?), (SELECT cached_to FROM sync_log WHERE symbol = ?), ?, ?) "
"ON CONFLICT(symbol) DO UPDATE SET last_error = excluded.last_error, last_attempt = excluded.last_attempt",
(symbol, symbol, now.isoformat(), symbol, symbol, "; ".join(errors), now.isoformat()),
)
else:
actual_range = conn.execute(
"SELECT MIN(date), MAX(date) FROM prices WHERE symbol = ?", (symbol,)
).fetchone()
if actual_range and actual_range[0] is not None:
conn.execute(
"INSERT INTO sync_log (symbol, last_synced, cached_from, cached_to, last_error, last_attempt) "
"VALUES (?, ?, ?, ?, NULL, ?) "
"ON CONFLICT(symbol) DO UPDATE SET last_synced = excluded.last_synced, "
"cached_from = excluded.cached_from, cached_to = excluded.cached_to, "
"last_error = NULL, last_attempt = excluded.last_attempt",
(symbol, now.isoformat(), actual_range[0], actual_range[1], now.isoformat()),
)
conn.commit()
if not ranges_to_fetch:
return True, "Up to date"
if errors:
return False, "; ".join(errors)
return True, "Synced successfully"
finally:
conn.close()
@app.route("/", defaults={"path": ""})
@app.route("/<path:path>")
def serve_spa(path):
if path.startswith("api/"):
return jsonify({"error": "not found"}), 404
full = os.path.join(FRONTEND_DIST, path)
if path and os.path.exists(full):
return send_from_directory(FRONTEND_DIST, path)
return send_from_directory(FRONTEND_DIST, "index.html")
@app.route("/api/transactions", methods=["GET"])
@jwt_required()
def get_transactions():
"""Retrieve list of transactions enriched with current price and gain/loss."""
txns = load_transactions(current_user_id())
if not txns:
return jsonify([])
# Get latest prices for all symbols
conn = db()
latest_prices = {}
rows = conn.execute("""
SELECT symbol, close FROM prices
WHERE (symbol, date) IN (
SELECT symbol, MAX(date) FROM prices GROUP BY symbol
)
""").fetchall()
for sym, close in rows:
latest_prices[sym] = close