Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
2172 lines (1913 loc) · 93.3 KB
/
Copy pathserver.py
File metadata and controls
2172 lines (1913 loc) · 93.3 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
#!/usr/bin/env python3
"""Twin: an iPhone-ready investing + day-trading companion.
Wraps two MIT-licensed skill packs by Jake Schincariol:
* day-trader-skill (scanner, entry, exit, 10,000-replay Time Machine, sizing, risk)
* trader-skill (copy an investor's 13F, news, budget, rebalance)
and adds accounts, a risk/personality profile, paper trading, a goal planner
(10,000 simulated futures), a news feed and a guide.
Standard library only. Practice by default; real orders are sent only after a
signed-in user connects their own Alpaca keys and confirms a preview (see broker.py).
python apps/twin/server.py # http://127.0.0.1:8765 on this computer
python apps/twin/server.py --lan # also reachable from your phone on the same Wi-Fi
Set TWIN_DATA (or the legacy TRADE_TWIN_DATA) to keep accounts somewhere else.
"""
import argparse
import hashlib
import hmac
import importlib.util
import io
import math
import json
from concurrent.futures import ThreadPoolExecutor
import os
import random
import re
import secrets
import shutil
import socket
import ssl
import subprocess
import sys
import tempfile
import threading
import time
import urllib.parse
import urllib.request
import webbrowser
import zipfile
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
# Prefer IPv4 when a host has both: urllib tries addresses one by one (no "happy eyeballs"),
# so a network with a broken IPv6 route would otherwise stall every market-data call.
_original_getaddrinfo = socket.getaddrinfo
def _ipv4_first_getaddrinfo(*args, **kwargs):
infos = _original_getaddrinfo(*args, **kwargs)
return sorted(infos, key=lambda info: info[0] != socket.AF_INET)
socket.getaddrinfo = _ipv4_first_getaddrinfo
APP_DIR = Path(__file__).resolve().parent
DAY = APP_DIR / "vendor" / "day-trader-skill"
INV = APP_DIR / "vendor" / "trader-skill"
DAY_FIX = DAY / "tests" / "fixtures"
STATIC = APP_DIR / "web"
# TRADE_TWIN_DATA is still accepted so existing installs keep their accounts after the rename.
DATA = Path(os.environ.get("TWIN_DATA") or os.environ.get("TRADE_TWIN_DATA") or APP_DIR / "data").resolve()
USERS_FILE = DATA / "users.json"
SESSIONS_FILE = DATA / "sessions.json"
SESSION_DAYS = 30
LOCK = threading.RLock()
# Routes that read-modify-write the profile run under LOCK so quick double taps can't lose updates.
PROFILE_WRITE_PATHS = {"/api/profile", "/api/quiz", "/api/paper", "/api/paper/order",
"/api/paper/copy", "/api/paper/reset", "/api/broker/order",
"/api/indonesia/wallet/save", "/api/wallet/transfer"}
# Demo mode replays the day-trader-skill README trade: TSLA, 2026-10-19, 10:15 ET.
DEMO_NOW = "2026-10-19 10:15"
DEMO_NOW_ISO = "2026-10-19T14:15:00Z"
DEMO_DATE = "2026-10-19"
TOOL = {
"scanner": DAY / "trader-scanner" / "scan.py",
"news": DAY / "trader-news" / "news.py",
"entry": DAY / "trader-entry" / "entry.py",
"exit": DAY / "trader-exit" / "exit.py",
"timemachine": DAY / "trader-timemachine" / "timemachine.py",
"budget": DAY / "trader-budget" / "size.py",
"risk": DAY / "trader-risk" / "check.py",
"broker": DAY / "trader-broker" / "ticket.py",
"alerts": DAY / "trader-alerts" / "alerts.py",
"copycat": INV / "trader-copycat" / "edgar13f.py",
}
VERSION = "1.15.0"
class AppError(Exception):
pass
# --------------------------------------------------------------- TLS + HTTP
def ca_bundle_path():
"""macOS' bundled Python often lacks CA roots (CERTIFICATE_VERIFY_FAILED).
Export the system roots once and use them for every HTTPS call."""
if os.environ.get("SSL_CERT_FILE") and os.path.isfile(os.environ["SSL_CERT_FILE"]):
return os.environ["SSL_CERT_FILE"]
if sys.platform != "darwin":
return None
bundle = DATA / "cacert.pem"
if not bundle.exists():
DATA.mkdir(parents=True, exist_ok=True)
pem = subprocess.run(
[
"security", "find-certificate", "-a", "-p",
"/System/Library/Keychains/SystemRootCertificates.keychain",
"/Library/Keychains/System.keychain",
],
capture_output=True,
text=True,
).stdout
if "BEGIN CERTIFICATE" in pem:
bundle.write_text(pem)
return str(bundle) if bundle.exists() else None
CA_BUNDLE = ca_bundle_path()
TOOL_ENV = dict(os.environ)
if CA_BUNDLE:
TOOL_ENV["SSL_CERT_FILE"] = CA_BUNDLE
SSL_CTX = ssl.create_default_context(cafile=CA_BUNDLE) if CA_BUNDLE else ssl.create_default_context()
_cache = {}
sys.path.insert(0, str(APP_DIR))
import broker as broker_mod # noqa: E402 (local module next to this file)
import live_quotes # noqa: E402
def http_json(url, ttl=60):
hit = _cache.get(url)
if hit and time.time() - hit[0] < ttl:
return hit[1]
last_error = None
for host in ("query2", "query1"):
target = url.replace("query2.", host + ".")
request = urllib.request.Request(target, headers={"User-Agent": "Mozilla/5.0 (Twin)"})
try:
with urllib.request.urlopen(request, timeout=20, context=SSL_CTX) as resp:
data = json.loads(resp.read().decode("utf-8"))
_cache[url] = (time.time(), data)
return data
except Exception as exc: # network, HTTP or JSON error: try the other host
last_error = exc
raise AppError("market data unavailable (%s)" % last_error)
# ------------------------------------------------------------- market data
RANGES = {
"1D": ("1d", "5m", 60),
"1W": ("5d", "30m", 300),
"1M": ("1mo", "1d", 900),
"3M": ("3mo", "1d", 900),
"1Y": ("1y", "1d", 3600),
"5Y": ("5y", "1wk", 3600 * 6),
}
# Some exchanges quote in minor units (pence, cents, agorot); Twin always uses the major unit.
MINOR_UNITS = {"GBp": ("GBP", 100), "GBX": ("GBP", 100), "ZAc": ("ZAR", 100), "ILA": ("ILS", 100)}
FX_FALLBACK = {}
FX_TIME = {} # currency -> epoch seconds of the quote behind the rate
FX_TTL = 60 # seconds; Yahoo FX quotes update continuously while FX markets are open
def fx_usd(currency):
"""US dollars per one unit of `currency` (Yahoo FX), refreshed at most every FX_TTL seconds."""
currency = (currency or "USD").upper()
if currency == "USD":
return 1.0
if FAKE_MARKET is not None and currency in FAKE_MARKET.get("fx_usd", {}):
return FAKE_MARKET["fx_usd"][currency]
if not re.fullmatch(r"[A-Z]{3}", currency):
raise AppError("unknown currency %s" % currency)
try:
# USDxxx=X keeps full precision (16,500 IDR); xxxUSD=X is rounded to 4 decimals by Yahoo.
doc = http_json("https://query2.finance.yahoo.com/v8/finance/chart/USD%s%%3DX?range=1d&interval=1d" % currency, ttl=FX_TTL)
meta = ((doc.get("chart") or {}).get("result") or [{}])[0].get("meta") or {}
inverse = meta.get("regularMarketPrice")
rate = 1 / inverse if inverse else None
if rate:
FX_TIME[currency] = meta.get("regularMarketTime") or int(time.time())
except AppError:
rate = None
if rate:
FX_FALLBACK[currency] = rate
return rate
if currency in FX_FALLBACK:
return FX_FALLBACK[currency]
raise AppError("no exchange rate for %s" % currency)
SEARCH_TYPES = {"EQUITY": "Stock", "ETF": "ETF", "INDEX": "Index", "MUTUALFUND": "Fund"}
def search(query):
"""Find stocks, ETFs and indices on any exchange Yahoo Finance covers."""
query = (query or "").strip()
if not 1 <= len(query) <= 40:
raise AppError("type a company name or ticker")
url = "https://query2.finance.yahoo.com/v1/finance/search?" + urllib.parse.urlencode({
"q": query, "quotesCount": 15, "newsCount": 0, "listsCount": 0, "enableFuzzyQuery": "true",
})
doc = http_json(url, ttl=300)
results = []
for item in doc.get("quotes") or []:
kind = SEARCH_TYPES.get(item.get("quoteType"))
symbol = item.get("symbol")
if not kind or not symbol or not re.fullmatch(r"[A-Za-z0-9.\-^=]{1,12}", symbol):
continue
results.append({
"symbol": symbol.upper(),
"name": item.get("longname") or item.get("shortname") or symbol,
"exchange": item.get("exchDisp") or item.get("exchange"),
"type": kind,
})
return results[:12]
WORLD_FILE = APP_DIR / "web" / "demo" / "world.json"
WORLD_LIVE_STOCKS = 80
_world_meta = {}
def world_markets():
"""The curated global universe with live quotes (snapshot values fill any gaps)."""
if not _world_meta:
data = json.loads(WORLD_FILE.read_text())
_world_meta.update({k: data[k] for k in ("universe", "indices", "quotes", "fx_usd", "snapshot_taken")})
# Live quotes for the indices and the core list (first entries); the rest of the 300+ symbols come
# from the hourly snapshot so the World screen stays fast. Any symbol is live on its own stock page.
live_symbols = [item["symbol"] for item in _world_meta["indices"] + _world_meta["universe"][:WORLD_LIVE_STOCKS]]
symbols = live_symbols
live, errors = {}, {}
def fetch_one(symbol):
try:
return symbol, quote(symbol), None
except AppError as exc:
return symbol, None, str(exc)
with ThreadPoolExecutor(max_workers=8) as pool:
for symbol, data, error in pool.map(fetch_one, symbols):
if data:
live[symbol] = data
else:
errors[symbol] = error
live[symbol] = dict(_world_meta["quotes"].get(symbol, {}), stale=True)
for symbol, q in _world_meta["quotes"].items():
if symbol not in live:
live[symbol] = dict(q, snapshot=True)
fx = dict(_world_meta["fx_usd"])
for item in _world_meta["universe"]:
q = live.get(item["symbol"]) or {}
if q.get("fx_usd") and not q.get("stale"):
fx[q.get("currency")] = q["fx_usd"]
return {
"universe": _world_meta["universe"],
"indices": _world_meta["indices"],
"quotes": live,
"fx_usd": fx,
"errors": errors,
"as_of": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC"),
"fx_as_of": max(FX_TIME.values()) if FX_TIME else None,
}
def clean_symbol(value):
symbol = (value or "").strip().upper()
if not re.fullmatch(r"[A-Z0-9.\-^=]{1,12}", symbol):
raise AppError("enter a ticker symbol, e.g. AAPL")
return symbol
def chart(symbol, span="1D"):
symbol = clean_symbol(symbol)
rng, interval, ttl = RANGES.get(span, RANGES["1D"])
url = "https://query2.finance.yahoo.com/v8/finance/chart/%s?range=%s&interval=%s&includePrePost=false" % (
urllib.parse.quote(symbol), rng, interval)
doc = http_json(url, ttl=ttl)
result = (doc.get("chart") or {}).get("result")
if not result:
raise AppError("no data for %s" % symbol)
result = result[0]
meta = result.get("meta", {})
currency, divisor = MINOR_UNITS.get(meta.get("currency") or "USD", (meta.get("currency") or "USD", 1))
stamps = result.get("timestamp") or []
closes = ((result.get("indicators") or {}).get("quote") or [{}])[0].get("close") or []
points = [[t, round(c / divisor, 4)] for t, c in zip(stamps, closes) if c is not None]
def major(value):
return value / divisor if value is not None else None
price = major(meta.get("regularMarketPrice"))
prev = major(meta.get("chartPreviousClose")) if span == "1D" else (points[0][1] if points else None)
if span == "1D" and meta.get("previousClose"):
prev = major(meta.get("previousClose"))
return {
"symbol": symbol,
"name": meta.get("longName") or meta.get("shortName") or symbol,
"price": price,
"prev": prev,
"change": (price - prev) if price is not None and prev else None,
"change_pct": ((price / prev - 1) * 100) if price is not None and prev else None,
"currency": currency,
"fx_usd": fx_usd(currency),
"fx_time": FX_TIME.get(currency) if currency != "USD" else None,
"exchange": meta.get("fullExchangeName") or meta.get("exchangeName"),
"timezone": meta.get("exchangeTimezoneName"),
"time": meta.get("regularMarketTime"),
"day_high": major(meta.get("regularMarketDayHigh")),
"day_low": major(meta.get("regularMarketDayLow")),
"high52": major(meta.get("fiftyTwoWeekHigh")),
"low52": major(meta.get("fiftyTwoWeekLow")),
"volume": meta.get("regularMarketVolume"),
"span": span,
"points": points,
}
# Tests only: TWIN_FAKE_QUOTES points at a JSON file {"quotes": {...}, "fx_usd": {...}} used instead of Yahoo.
FAKE_MARKET = json.loads(Path(os.environ["TWIN_FAKE_QUOTES"]).read_text()) if os.environ.get("TWIN_FAKE_QUOTES") else None
def quote(symbol):
if FAKE_MARKET is not None:
symbol = clean_symbol(symbol)
if symbol not in FAKE_MARKET.get("quotes", {}):
raise AppError("no data for %s" % symbol)
return dict(FAKE_MARKET["quotes"][symbol], symbol=symbol)
data = chart(symbol, "1D")
data = dict(data)
data["spark"] = [p[1] for p in data.pop("points")][::3]
return data
def quotes(symbols):
out, errors = {}, {}
for symbol in symbols:
try:
out[symbol] = quote(symbol)
except AppError as exc:
errors[symbol] = str(exc)
return {"quotes": out, "errors": errors}
def monthly_returns(symbol):
"""Total-return monthly series (adjusted close, so dividends count).
Uses an explicit period1/period2 window: with range=max Yahoo silently
switches long histories (e.g. AAPL since 1984) to quarterly bars. Returns are
only taken between consecutive calendar months, so a gap can never be
mistaken for a one-month move."""
symbol = clean_symbol(symbol)
url = "https://query2.finance.yahoo.com/v8/finance/chart/%s?period1=0&period2=%d&interval=1mo" % (
urllib.parse.quote(symbol), int(time.time() // 86400 * 86400))
doc = http_json(url, ttl=3600 * 12)
result = (doc.get("chart") or {}).get("result")
if not result:
raise AppError("no history for %s" % symbol)
result = result[0]
stamps = result.get("timestamp") or []
adj = ((result.get("indicators") or {}).get("adjclose") or [{}])[0].get("adjclose")
if not adj:
adj = result["indicators"]["quote"][0]["close"]
by_month = {}
for ts, value in zip(stamps, adj):
if value is not None and value > 0:
by_month[datetime.fromtimestamp(ts, timezone.utc).strftime("%Y-%m")] = value
current = datetime.now(timezone.utc).strftime("%Y-%m")
by_month.pop(current, None) # the unfinished month is not a full month of returns
def index(month):
year, mon = month.split("-")
return int(year) * 12 + int(mon)
series = {}
months = sorted(by_month)
for prev, month in zip(months, months[1:]):
if index(month) - index(prev) == 1:
series[month] = by_month[month] / by_month[prev] - 1
return series
def pct(values, q):
ordered = sorted(values)
return ordered[min(len(ordered) - 1, int(q * len(ordered)))]
def goal_sim(weights, years, initial, monthly, goal, paths=10000, seed=19, block=12):
"""10,000 possible futures for a portfolio, built from its own history.
Block bootstrap: each simulated year is a random run of 12 consecutive real
months (so bad stretches stay together), rebalanced monthly to the weights."""
if not weights:
raise AppError("pick at least one ticker")
if len(weights) > 8:
raise AppError("use at most 8 tickers per simulation")
weights = {clean_symbol(k): number(v, "weight", low=0) for k, v in weights.items()}
total = sum(weights.values())
if not math.isfinite(total) or total <= 0:
raise AppError("at least one weight must be positive")
weights = {k: v / total for k, v in weights.items() if v > 0}
series = {sym: monthly_returns(sym) for sym in weights}
all_months = sorted(set.intersection(*[set(s) for s in series.values()]))
# Keep one unbroken calendar run: missing months must never be stitched together.
runs = []
for month in all_months:
if not runs or month_serial(month) != month_serial(runs[-1][-1]) + 1:
runs.append([])
runs[-1].append(month)
months = max(runs, key=lambda run: (len(run), run[-1]), default=[])
if len(months) < 60:
raise AppError("need at least 5 years of shared history; %d months available" % len(months))
history = [sum(w * series[s][m] for s, w in weights.items()) for m in months]
if any(not math.isfinite(r) or r < -1 for r in history):
raise AppError("invalid historical returns; simulation refused")
block = int(number(block, "block size", low=1, high=len(history)))
n_months = int(years * 12)
rng = random.Random(seed)
yearly = [[] for _ in range(int(years) + 1)]
finals = []
worst_drawdowns = []
for _ in range(paths):
value = float(initial)
unit_value = 1.0
peak = 1.0
worst = 0.0
yearly[0].append(value)
m = 0
while m < n_months:
start = rng.randrange(len(history) - block + 1)
for k in range(block):
if m >= n_months:
break
period_return = history[start + k]
value = (value + monthly) * (1 + period_return)
# Measure investment drawdown on unit value, not on deposit-inflated cash.
unit_value *= 1 + period_return
peak = max(peak, unit_value)
worst = min(worst, unit_value / peak - 1)
m += 1
if m % 12 == 0:
yearly[m // 12].append(value)
finals.append(value)
worst_drawdowns.append(worst)
contributed = initial + monthly * n_months
bands = [[round(pct(v, q), 2) for q in (0.05, 0.25, 0.5, 0.75, 0.95)] for v in yearly]
# what the history itself looks like
growth = 1.0
peak = 1.0
max_dd = 0.0
for r in history:
growth *= 1 + r
peak = max(peak, growth)
max_dd = min(max_dd, growth / peak - 1)
n_years_hist = len(history) / 12
cagr = growth ** (1 / n_years_hist) - 1
mean = sum(history) / len(history)
var = sum((r - mean) ** 2 for r in history) / (len(history) - 1)
worst_12 = min(compound(history[i:i + 12]) for i in range(len(history) - 11))
return {
"weights": {k: round(v * 100, 2) for k, v in weights.items()},
"years": years,
"initial": initial,
"monthly": monthly,
"goal": goal,
"paths": paths,
"seed": seed,
"contributed": round(contributed, 2),
"bands": bands,
"median": round(pct(finals, 0.5), 2),
"p5": round(pct(finals, 0.05), 2),
"p95": round(pct(finals, 0.95), 2),
"p_goal": round(sum(1 for v in finals if v >= goal) / paths, 4) if goal else None,
"p_loss": round(sum(1 for v in finals if v < contributed) / paths, 4),
"median_worst_drop": round(pct(worst_drawdowns, 0.5) * 100, 1),
"bad_case_worst_drop": round(pct(worst_drawdowns, 0.05) * 100, 1),
"history": {
"from": months[0],
"to": months[-1],
"months": len(months),
"cagr_pct": round(cagr * 100, 2),
"vol_pct": round((var ** 0.5) * (12 ** 0.5) * 100, 2),
"max_drawdown_pct": round(max_dd * 100, 1),
"worst_12m_pct": round(worst_12 * 100, 1),
},
"note": "Built from %s's own monthly total returns %s to %s (block bootstrap, 12-month blocks, "
"rebalanced monthly). Not a prediction: the future can be worse than any stretch in this history."
% ("/".join(weights), months[0], months[-1]),
"warnings": history_warnings(len(months)) + (
["Missing shared months: using the longest consecutive history only."]
if len(months) != len(all_months) else []),
"drawdown_basis": "time-weighted unit value; deposits excluded",
"assumptions": [
"Nominal dollars; inflation, taxes, transaction fees and trading slippage are excluded.",
"Contributions at the start of each month; fixed weights rebalanced monthly.",
"Historical sample estimates, not calibrated forecasts or guaranteed outcomes."
],
}
def month_serial(month):
year, mon = month.split("-")
return int(year) * 12 + int(mon)
def history_warnings(n_months):
years = n_months / 12
if years < 20:
return ["Only %.0f years of shared history, which may not include a full crash and recovery. "
"Results are likely too optimistic. For a longer record try SPY (since 1993) "
"or a mix like SPY + AGG." % years]
return []
def compound(seq):
"""Total return of a run of monthly returns."""
growth = 1.0
for r in seq:
growth *= 1 + r
return growth - 1
# ------------------------------------------------------------ users + sessions
def reject_json_constant(value):
raise ValueError("non-finite JSON value")
def load_json(path, default):
try:
return json.loads(path.read_text())
except (OSError, ValueError):
return default
def save_json(path, data):
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(path.name + "." + secrets.token_hex(8) + ".tmp")
try:
tmp.write_text(json.dumps(data, indent=2, allow_nan=False))
tmp.chmod(0o600)
tmp.replace(path)
finally:
tmp.unlink(missing_ok=True)
def number(value, name, low=None, high=None, default=None):
"""Parse a user-supplied number: finite, within [low, high], else a friendly AppError."""
if value in (None, ""):
if default is not None:
return default
raise AppError("%s is required" % name)
if isinstance(value, bool):
raise AppError("%s must be a number, not a boolean" % name)
try:
result = float(value)
except (TypeError, ValueError):
raise AppError("%s must be a number" % name)
if not math.isfinite(result):
raise AppError("%s must be a real number" % name)
if low is not None and result < low:
raise AppError("%s must be at least %s" % (name, low))
if high is not None and result > high:
raise AppError("%s must be at most %s" % (name, high))
return result
def hash_password(password, salt):
return hashlib.pbkdf2_hmac("sha256", password.encode(), bytes.fromhex(salt), 200_000).hex()
def user_dir(uid):
return DATA / "users" / uid
def profile_path(uid):
return user_dir(uid) / "profile.json"
def default_profile(name, email):
return {
"name": name,
"email": email,
"created": datetime.now(timezone.utc).isoformat(timespec="seconds"),
"onboarded": False,
"quiz": None,
"watchlist": ["SPY", "AAPL", "MSFT", "NVDA", "TSLA"],
"budget": 5000,
"limits": None,
"paper": {
"start_cash": 10000.0,
"cash": 10000.0,
"positions": {},
"history": [],
"snapshots": [],
},
"goal": {"tickers": "SPY", "years": 20, "initial": 1000, "monthly": 200, "target": 100000},
"guide_done": [],
}
def signup(username, password, name, email):
username = (username or "").strip().lower()
if not re.fullmatch(r"[a-z0-9_.]{3,24}", username):
raise AppError("username: 3-24 letters, numbers, dot or underscore")
if len(password or "") < 8:
raise AppError("password must be at least 8 characters")
if not name or not name.strip():
raise AppError("enter your name")
email = (email or "").strip()
if email and not re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+", email):
raise AppError("that email does not look right")
with LOCK:
users = load_json(USERS_FILE, {"users": {}})
if username in users["users"]:
raise AppError("that username is taken")
salt = secrets.token_hex(16)
uid = secrets.token_hex(8)
users["users"][username] = {"id": uid, "salt": salt, "hash": hash_password(password, salt)}
save_json(USERS_FILE, users)
save_json(profile_path(uid), default_profile(name.strip(), email))
return uid
_failed_logins = {}
def login(username, password, ip):
now = time.time()
attempts = [t for t in _failed_logins.get(ip, []) if now - t < 300]
if len(attempts) >= 10:
raise AppError("too many attempts; wait 5 minutes")
users = load_json(USERS_FILE, {"users": {}})["users"]
record = users.get((username or "").strip().lower())
if not record or not hmac.compare_digest(record["hash"], hash_password(password or "", record["salt"])):
attempts.append(now)
_failed_logins[ip] = attempts
raise AppError("wrong username or password")
return record["id"]
def new_session(uid):
token = secrets.token_urlsafe(32)
with LOCK:
sessions = load_json(SESSIONS_FILE, {})
sessions[token] = {"uid": uid, "expires": time.time() + SESSION_DAYS * 86400}
sessions = {k: v for k, v in sessions.items() if v["expires"] > time.time()}
save_json(SESSIONS_FILE, sessions)
return token
def session_user(token):
if not token:
return None
entry = load_json(SESSIONS_FILE, {}).get(token)
if not entry or entry["expires"] < time.time():
return None
return entry["uid"]
def end_session(token):
with LOCK:
sessions = load_json(SESSIONS_FILE, {})
sessions.pop(token, None)
save_json(SESSIONS_FILE, sessions)
def get_profile(uid):
profile = load_json(profile_path(uid), None)
if profile is None:
raise AppError("profile missing")
return profile
def put_profile(uid, profile):
with LOCK:
save_json(profile_path(uid), profile)
# ------------------------------------------------------- personality profile
ARCHETYPES = {
"builder": {
"title": "Steady Builder",
"emoji": "🌱",
"summary": "You value sleep over thrills. Long horizon, low tolerance for big swings: "
"regular investing into broad index funds fits you best.",
"focus": "invest",
"suggest": "Start in Invest → Goal planner with a broad index fund (e.g. SPY) and a monthly amount.",
},
"grower": {
"title": "Balanced Grower",
"emoji": "🌳",
"summary": "Growth-minded but measured. You can ride out normal dips; a core of index funds "
"plus a few companies you understand suits you.",
"focus": "invest",
"suggest": "Build a core with the Goal planner, then explore Copy an investor with paper money.",
},
"opportunist": {
"title": "Opportunity Hunter",
"emoji": "🦊",
"summary": "Curious, research-driven, comfortable with volatility. You like picking stocks and "
"following smart money, holding for weeks to years.",
"focus": "invest",
"suggest": "Try Copy an investor, follow your watchlist news, and paper-trade your ideas first.",
},
"trader": {
"title": "Active Trader",
"emoji": "⚡",
"summary": "Fast, hands-on and loss-tolerant, with time to watch the market. Day trading is a "
"skill game where most beginners lose — your edge is strict rules and small risk.",
"focus": "trade",
"suggest": "Learn the Trade flow in Demo, then paper-trade live setups. Let the Time Machine veto bad odds.",
},
}
# risk level 1..5 -> rule-of-thumb limits (app conventions, not advice)
RISK_TABLE = {
1: {"risk_pct": 0.25, "trades": 1, "min_rr": 2.0, "target": "2R", "cash_buffer": 20, "max_pos": 25},
2: {"risk_pct": 0.5, "trades": 2, "min_rr": 2.0, "target": "2R", "cash_buffer": 15, "max_pos": 35},
3: {"risk_pct": 0.75, "trades": 3, "min_rr": 1.5, "target": "1.5R", "cash_buffer": 10, "max_pos": 50},
4: {"risk_pct": 1.0, "trades": 3, "min_rr": 1.5, "target": "1.5R", "cash_buffer": 10, "max_pos": 60},
5: {"risk_pct": 1.0, "trades": 4, "min_rr": 1.0, "target": "1R", "cash_buffer": 10, "max_pos": 75},
}
def score_quiz(answers):
"""answers: {question_id: option_index}. Scores are defined in the client's QUIZ list
and echoed here so the server is the single source of the result."""
risk = answers.get("risk_points", [])
style = answers.get("style_points", [])
flags = answers.get("flags", [])
if not risk or not style:
raise AppError("answer every question")
if not isinstance(risk, list) or not isinstance(style, list) or len(risk) > 20 or len(style) > 20:
raise AppError("invalid assessment answers")
risk = [number(value, "risk answer", low=1, high=5) for value in risk]
style = [number(value, "style answer", low=1, high=5) for value in style]
risk_avg = sum(risk) / len(risk) # 1..5
style_avg = sum(style) / len(style) # 1 (long-term investor) .. 5 (active trader)
level = max(1, min(5, int(math.floor(risk_avg + 0.5))))
if style_avg >= 3.8 and level >= 3:
key = "trader"
elif style_avg >= 2.8 and level >= 3:
key = "opportunist"
elif level >= 3 or style_avg >= 2.5:
key = "grower"
else:
key = "builder"
cautions = []
if "no_emergency_fund" in flags:
cautions.append("Build an emergency fund (3–6 months of expenses) before taking real market risk.")
level = min(level, 2)
if "need_money_soon" in flags:
cautions.append("Money you need within ~3 years usually belongs in cash or short-term bonds, not stocks.")
level = min(level, 2)
if "panic_seller" in flags:
cautions.append("You said you'd sell after a big drop. Automate investing and avoid checking prices daily.")
if key == "trader" and "beginner" in flags:
cautions.append("You're new: stay on paper money until you have 50+ planned trades logged.")
if key == "trader" and level < 3:
key = "opportunist"
return {
"archetype": key,
"risk_level": level,
"style_score": round(style_avg, 2),
"risk_score": round(risk_avg, 2),
"cautions": cautions,
"taken": datetime.now(timezone.utc).isoformat(timespec="seconds"),
**ARCHETYPES[key],
}
def limits_for(level, budget):
row = RISK_TABLE[level]
per_trade = round(budget * row["risk_pct"] / 100, 2)
return {
"budget": budget,
"risk_pct": row["risk_pct"],
"max_loss_per_trade_usd": per_trade,
"max_daily_loss_usd": round(per_trade * 3, 2),
"max_trades_per_day": row["trades"],
"min_reward_risk": row["min_rr"],
"default_target": row["target"],
"cash_buffer_pct": row["cash_buffer"],
"max_position_pct": row["max_pos"],
"max_order_usd": round(budget * row["max_pos"] / 100, 2),
"flat_by": "15:55",
"no_entries_before": "09:45",
"no_entries_after": "15:30",
}
def sync_trader_config(uid, profile):
"""Write the user's limits into each day-trader workspace's config.json."""
limits = profile.get("limits") or limits_for(2, profile.get("budget", 5000))
agent = "%s %s" % (profile.get("name", "").replace(" ", ""), profile.get("email", "")) if profile.get("email") else ""
for mode in ("demo", "live"):
root = trader_root(uid, mode)
path = root / "trader" / "config.json"
config = load_json(path, None) or load_json(DAY / "trader-budget" / "config.example.json", {})
for key in ("budget", "max_loss_per_trade_usd", "max_daily_loss_usd", "max_trades_per_day",
"min_reward_risk", "cash_buffer_pct", "max_position_pct", "max_order_usd",
"flat_by", "no_entries_before", "no_entries_after"):
if key in limits:
config[key] = limits[key]
config["sec_user_agent"] = agent
config.update({"paper": True, "allow_options": False, "allow_margin": False, "allow_short": False})
save_json(path, config)
def trader_root(uid, mode):
root = user_dir(uid) / ("demo" if mode == "demo" else "live")
(root / "trader" / "state").mkdir(parents=True, exist_ok=True)
config = root / "trader" / "config.json"
if not config.exists():
shutil.copy(DAY / "trader-budget" / "config.example.json", config)
return root
# ------------------------------------------------------------ paper trading
def paper_value(paper, prices):
"""Cash plus holdings in US dollars; `prices` are already converted to USD."""
holdings = sum(pos["qty"] * prices.get(sym, pos["cost"] / max(pos["qty"], 1e-9)) for sym, pos in paper["positions"].items())
return round(paper["cash"] + holdings, 2)
def usd_price(q):
"""A quote's price in US dollars (practice cash is kept in USD)."""
price = q.get("price")
rate = q.get("fx_usd") if q.get("fx_usd") is not None else fx_usd(q.get("currency"))
return price * rate if price is not None else None
def paper_state(profile):
paper = profile["paper"]
symbols = list(paper["positions"])
data = quotes(symbols) if symbols else {"quotes": {}, "errors": {}}
prices = {s: usd_price(q) for s, q in data["quotes"].items() if q.get("price") is not None}
rows = []
for sym, pos in paper["positions"].items():
q = data["quotes"].get(sym, {})
price_usd = prices.get(sym) or pos["cost"] / pos["qty"]
rows.append({
"symbol": sym,
"name": q.get("name", sym),
"qty": round(pos["qty"], 6),
"avg_cost": round(pos["cost"] / pos["qty"], 4),
"price": price_usd,
"local_price": q.get("price"),
"currency": q.get("currency", "USD"),
"fx_usd": q.get("fx_usd", 1.0),
"value": round(pos["qty"] * price_usd, 2),
"gain": round(pos["qty"] * price_usd - pos["cost"], 2),
"gain_pct": round((pos["qty"] * price_usd / pos["cost"] - 1) * 100, 2) if pos["cost"] else 0,
"day_pct": q.get("change_pct"),
"spark": q.get("spark", []),
})
rows.sort(key=lambda r: -r["value"])
value = paper_value(paper, prices)
today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
snaps = paper.setdefault("snapshots", [])
if snaps and snaps[-1][0] == today:
snaps[-1][1] = value
else:
snaps.append([today, value])
# Money moved to or from the rupiah wallet is a deposit or withdrawal, not a gain or loss.
contributions = float(paper.get("contributions") or 0)
basis = paper["start_cash"] + contributions
return {
"cash": round(paper["cash"], 2),
"start_cash": paper["start_cash"],
"contributions": round(contributions, 2),
"basis": round(basis, 2),
"value": value,
"gain": round(value - basis, 2),
"gain_pct": round((value / basis - 1) * 100, 2) if basis > 0 else 0.0,
"transfers": paper.get("transfers", [])[:20],
"positions": rows,
"history": paper["history"][-50:][::-1],
"snapshots": snaps[-365:],
"errors": data["errors"],
}
def paper_order(profile, symbol, side, dollars=None, qty=None, note=""):
symbol = clean_symbol(symbol)
if side not in ("buy", "sell"):
raise AppError("side must be buy or sell")
paper = profile["paper"]
# Validate the amount before any price lookup.
amount = number(dollars, "amount", low=0) if dollars not in (None, "") else None
shares = number(qty, "quantity", low=0, default=0.0) if amount is None else None
if not (amount or shares):
raise AppError("enter an amount")
q = quote(symbol)
local_price = q["price"]
if not local_price:
raise AppError("no price for %s" % symbol)
price = usd_price(q) # practice cash is in USD; convert foreign listings at the delayed FX rate
qty = amount / price if amount is not None else shares
pos = paper["positions"].get(symbol)
if side == "buy":
cost = qty * price
if cost > paper["cash"] + 0.005:
raise AppError("not enough paper cash ($%.2f available)" % paper["cash"])
paper["cash"] -= cost
if pos:
pos["qty"] += qty
pos["cost"] += cost
else:
paper["positions"][symbol] = {"qty": qty, "cost": cost}
elif side == "sell":
if not pos or pos["qty"] + 1e-9 < qty:
raise AppError("you hold %.4f %s" % (pos["qty"] if pos else 0, symbol))
avg = pos["cost"] / pos["qty"]
paper["cash"] += qty * price
pos["qty"] -= qty
pos["cost"] -= avg * qty
if pos["qty"] < 1e-6:
del paper["positions"][symbol]
else:
raise AppError("side must be buy or sell")
paper["history"].append({
"time": datetime.now(timezone.utc).isoformat(timespec="seconds"),
"side": side,
"symbol": symbol,
"qty": round(qty, 6),
"price": local_price,
"currency": q.get("currency", "USD"),
"fx_usd": q.get("fx_usd", 1.0),
"amount": round(qty * price, 2),
"note": note,
})
return {"symbol": symbol, "side": side, "qty": round(qty, 6), "price": local_price,
"currency": q.get("currency", "USD"), "fx_usd": q.get("fx_usd", 1.0), "amount": round(qty * price, 2)}
# ------------------------------------------------------------ skill tools
def run_tool(uid, mode, args, timeout=180):
root = trader_root(uid, mode)
command = [sys.executable] + [str(a) for a in args]
try:
proc = subprocess.run(command, cwd=root, env=TOOL_ENV, capture_output=True, text=True, timeout=timeout)
except subprocess.TimeoutExpired:
raise AppError("that took too long; try again with fewer symbols")
data = None
if proc.stdout.strip():
try:
data = json.loads(proc.stdout)
except ValueError:
data = None
return {
"ok": proc.returncode == 0,
"code": proc.returncode,
"data": data,
"stdout": proc.stdout if data is None else "",
"stderr": proc.stderr.strip(),
}
def opt(args, flag, value):
if value not in (None, ""):
args += [flag, str(value)]
PIPELINE_STEPS = ("entry", "exit", "timemachine", "budget", "risk", "broker")
PIPELINE_FILES = ("entry.json", "plan.json", "timemachine.json", "orders.json", "state/risk.json")
TRADE_LOCKS = {}
def day_trade_step(uid, step, mode, params, run_id=None):
"""Bind every hand-off to one completed run and the current limits.
Clear stale outputs before attempting a new step; reject interleaved tabs,
old tokens, expired live runs, and a ticket without a successful risk check.
"""
with LOCK:
run_lock = TRADE_LOCKS.setdefault((uid, mode), threading.RLock())
with run_lock:
if step in ("clock", "scanner"):