-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_screenshots.py
More file actions
864 lines (763 loc) · 29.4 KB
/
Copy pathgenerate_screenshots.py
File metadata and controls
864 lines (763 loc) · 29.4 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
"""Generate SVG screenshots of every major panel using **synthetic data**.
- No eToro credentials are required (the script passes dummy strings).
- No network calls — the app's refresh action is replaced with a no-op.
- A throwaway SQLite database is populated with ~30 historical snapshots so
the equity curve, sparklines and monthly-gain bars render with shape.
- Tickers (AAPL, MSFT, ...), mirror usernames (morgan_steady, ...) and
dollar amounts are entirely made up.
Run from the repo root with the venv active::
source .venv/bin/activate
python scripts/generate_screenshots.py
Outputs to ``docs/screenshots/<NN-name>.svg``.
"""
from __future__ import annotations
import asyncio
import math
import shutil
import sys
import tempfile
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from pathlib import Path
# Allow running directly from a checkout (without `pip install -e .`).
ROOT = Path(__file__).resolve().parents[1]
SRC = ROOT / "src"
if SRC.is_dir() and str(SRC) not in sys.path:
sys.path.insert(0, str(SRC))
from etorotui.api.models import ( # noqa: E402 - sys.path tweak above
ClientPortfolio,
ClosedTrade,
InstrumentMetadata,
Mirror,
MonthlyGainEntry,
Position,
UnrealizedPnL,
)
from etorotui.app import EtoroTuiApp # noqa: E402
from etorotui.config import Config # noqa: E402
from etorotui.db.repository import SnapshotRecord # noqa: E402
OUTPUT_DIR = ROOT / "docs" / "screenshots"
TERMINAL_SIZE = (190, 52)
# ---------------------------------------------------------------------------
# Synthetic data — entirely fictional. No real account numbers or usernames.
# ---------------------------------------------------------------------------
@dataclass(frozen=True)
class _Inst:
instrument_id: int
ticker: str
name: str
industry_id: int
type_id: int # 5 = stock, 6 = ETF, 16 = crypto, 19 = commodity
INSTRUMENTS: list[_Inst] = [
_Inst(1001, "AAPL", "Apple Inc.", 12, 5),
_Inst(1002, "MSFT", "Microsoft Corporation", 12, 5),
_Inst(1003, "NVDA", "NVIDIA Corporation", 12, 5),
_Inst(1004, "GOOGL", "Alphabet Inc. (Class A)", 12, 5),
_Inst(1005, "TSLA", "Tesla, Inc.", 14, 5),
_Inst(1006, "AMZN", "Amazon.com, Inc.", 11, 5),
_Inst(1007, "META", "Meta Platforms, Inc.", 12, 5),
_Inst(1008, "BRK.B", "Berkshire Hathaway (B)", 8, 5),
_Inst(1009, "VOO", "Vanguard S&P 500 ETF", 99, 6),
_Inst(1010, "BTC", "Bitcoin", 0, 16),
_Inst(1011, "ETH", "Ethereum", 0, 16),
_Inst(1012, "ASML", "ASML Holding NV", 12, 5),
_Inst(1013, "JPM", "JPMorgan Chase & Co.", 8, 5),
_Inst(1014, "V", "Visa Inc.", 8, 5),
_Inst(1015, "GLD", "SPDR Gold Trust", 99, 19),
]
INSTRUMENT_BY_ID: dict[int, _Inst] = {i.instrument_id: i for i in INSTRUMENTS}
# (instrument_id, units, invested, unrealized, days_open)
SELF_STOCKS: list[tuple[int, float, float, float, int]] = [
(1001, 32.40, 4_800.00, 1_240.50, 420),
(1002, 18.00, 7_200.00, 2_870.30, 310),
(1003, 14.50, 5_500.00, 6_310.00, 270),
(1009, 24.00, 9_300.00, 1_180.40, 720),
(1010, 0.18, 8_000.00, 3_420.00, 540),
(1005, 22.00, 5_000.00, -780.15, 200),
(1012, 5.00, 3_400.00, 215.80, 95),
(1014, 12.00, 2_700.00, 410.20, 150),
]
@dataclass(frozen=True)
class _MirrorSpec:
username: str
cid: int
age_months: int
initial_invest: float
open_unrealized: float
closed_pnl: float
available: float
deposit_summary: float
withdrawal_summary: float
is_paused: bool
risk_score: float
drawdown_pct: float
monthly_gain_pct: list[float]
holdings: list[tuple[int, float, float, float]]
"""List of (instrument_id, units, invested, unrealized) for inner positions."""
MIRRORS: list[_MirrorSpec] = [
_MirrorSpec(
username="morgan_steady",
cid=5001,
age_months=28,
initial_invest=10_000.00,
open_unrealized=480.20,
closed_pnl=1_640.50,
available=820.00,
deposit_summary=2_500.00,
withdrawal_summary=0.00,
is_paused=False,
risk_score=4.0,
drawdown_pct=-7.4,
monthly_gain_pct=[1.4, 1.9, 0.7, 1.5, 2.0, -0.4, 0.9, 1.6, 2.1, 0.3, 1.7, 1.8],
holdings=[
(1001, 8.0, 1_120.00, 165.40),
(1002, 4.5, 1_440.00, 220.10),
(1009, 6.0, 2_000.00, 95.30),
(1008, 2.0, 760.00, -22.10),
(1014, 3.5, 720.00, 21.40),
(1015, 4.0, 800.00, -10.00),
],
),
_MirrorSpec(
username="alex_macro",
cid=5002,
age_months=14,
initial_invest=6_500.00,
open_unrealized=-210.40,
closed_pnl=1_200.00,
available=350.00,
deposit_summary=1_000.00,
withdrawal_summary=200.00,
is_paused=False,
risk_score=6.0,
drawdown_pct=-15.8,
monthly_gain_pct=[3.4, -1.6, 2.8, 5.1, -3.2, 4.6, 2.1, -0.9, 3.7, 4.4, -1.1, 2.9],
holdings=[
(1010, 0.05, 1_800.00, 250.00),
(1011, 0.30, 1_200.00, -90.00),
(1015, 5.0, 1_000.00, -45.00),
(1003, 2.0, 540.00, 80.00),
],
),
_MirrorSpec(
username="priya_growth",
cid=5003,
age_months=22,
initial_invest=5_500.00,
open_unrealized=720.10,
closed_pnl=1_980.40,
available=1_120.00,
deposit_summary=1_500.00,
withdrawal_summary=0.00,
is_paused=False,
risk_score=7.0,
drawdown_pct=-22.1,
monthly_gain_pct=[5.6, 4.2, -2.4, 6.1, 3.5, 7.0, -1.2, 4.8, 5.5, -3.0, 6.4, 3.9],
holdings=[
(1003, 3.5, 1_200.00, 540.00),
(1007, 2.0, 720.00, 120.00),
(1004, 1.5, 360.00, 38.00),
(1012, 1.0, 540.00, 22.10),
(1010, 0.05, 700.00, 80.00),
],
),
_MirrorSpec(
username="chen_value",
cid=5004,
age_months=33,
initial_invest=4_500.00,
open_unrealized=90.40,
closed_pnl=480.00,
available=250.00,
deposit_summary=600.00,
withdrawal_summary=80.00,
is_paused=False,
risk_score=3.0,
drawdown_pct=-4.6,
monthly_gain_pct=[0.6, 0.9, 0.3, 1.1, 0.4, 0.7, 1.2, 0.8, 0.5, 1.0, 0.6, 0.7],
holdings=[
(1008, 4.5, 1_400.00, 30.00),
(1014, 6.0, 900.00, 14.00),
(1009, 2.0, 700.00, 22.40),
(1013, 4.0, 520.00, 8.00),
],
),
_MirrorSpec(
username="kim_tech",
cid=5005,
age_months=8,
initial_invest=2_500.00,
open_unrealized=-340.00,
closed_pnl=-110.20,
available=90.00,
deposit_summary=400.00,
withdrawal_summary=0.00,
is_paused=False,
risk_score=8.0,
drawdown_pct=-31.5,
monthly_gain_pct=[8.4, -6.2, 9.1, -8.7, 5.5, -4.3, 7.2, -3.1, 4.6, -2.4, 1.8, -3.0],
holdings=[
(1005, 2.5, 700.00, -180.00),
(1003, 1.2, 460.00, 12.00),
(1006, 1.0, 320.00, -64.00),
(1011, 0.05, 240.00, -36.00),
],
),
_MirrorSpec(
username="dani_dividend",
cid=5006,
age_months=16,
initial_invest=1_500.00,
open_unrealized=12.40,
closed_pnl=105.10,
available=60.00,
deposit_summary=200.00,
withdrawal_summary=20.00,
is_paused=True,
risk_score=2.0,
drawdown_pct=-2.8,
monthly_gain_pct=[0.4, 0.5, 0.3, 0.6, 0.4, 0.5, 0.3, 0.5, 0.4, 0.4, 0.3, 0.5],
holdings=[
(1014, 2.0, 360.00, 4.00),
(1013, 2.5, 320.00, 6.00),
(1009, 1.0, 350.00, 2.40),
(1008, 1.0, 280.00, 0.00),
],
),
]
# Pretend pending orders so the Cash & Orders panel has rows to render.
PENDING_ORDERS: list[dict] = [
{
"orderID": 4_100_001,
"instrumentID": 1003,
"isBuy": True,
"amount": 1_500.00,
"orderCreatedDate": "2026-04-26T09:30:00Z",
},
{
"orderID": 4_100_002,
"instrumentID": 1009,
"isBuy": True,
"amount": 800.00,
"orderCreatedDate": "2026-04-28T14:12:00Z",
},
{
"orderID": 4_100_003,
"instrumentID": 1010,
"isBuy": False,
"amount": 1_200.00,
"orderCreatedDate": "2026-04-30T11:05:00Z",
},
]
# Twelve months of gain %, oldest -> newest. Realistic shape: mixed ups and downs.
MONTHLY_GAIN_PCT: list[float] = [
1.2,
2.4,
-0.6,
3.1,
4.5,
-2.1,
1.8,
2.9,
3.7,
-1.4,
2.6,
4.2,
]
CASH_BALANCE = 1_280.50
# ---------------------------------------------------------------------------
# Builders for pydantic models
# ---------------------------------------------------------------------------
def _utc_iso(dt: datetime) -> str:
return dt.astimezone(UTC).isoformat().replace("+00:00", "Z")
def _build_self_position(
*,
position_id: int,
instrument_id: int,
units: float,
invested: float,
unrealized: float,
days_open: int,
is_buy: bool = True,
) -> Position:
"""Build a self-managed (mirror_id == 0) position via field aliases."""
open_dt = datetime.now(UTC) - timedelta(days=days_open)
return Position.model_validate(
{
"positionID": position_id,
"instrumentID": instrument_id,
"isBuy": is_buy,
"units": units,
"amount": invested,
"initialAmountInDollars": invested,
"openDateTime": _utc_iso(open_dt),
"openRate": invested / units if units else 0.0,
"leverage": 1,
"mirrorID": 0,
"parentPositionID": 0,
"unrealizedPnL": UnrealizedPnL.model_validate({"pnL": unrealized}).model_dump(
by_alias=True
),
}
)
def _build_mirror_position(
*,
position_id: int,
mirror_id: int,
parent_position_id: int,
instrument_id: int,
units: float,
invested: float,
unrealized: float,
days_open: int,
) -> Position:
open_dt = datetime.now(UTC) - timedelta(days=days_open)
return Position.model_validate(
{
"positionID": position_id,
"instrumentID": instrument_id,
"isBuy": True,
"units": units,
"amount": invested,
"initialAmountInDollars": invested,
"openDateTime": _utc_iso(open_dt),
"openRate": invested / units if units else 0.0,
"leverage": 1,
"mirrorID": mirror_id,
"parentPositionID": parent_position_id,
"unrealizedPnL": UnrealizedPnL.model_validate({"pnL": unrealized}).model_dump(
by_alias=True
),
}
)
def build_client_portfolio() -> ClientPortfolio:
"""Compose the full ``ClientPortfolio`` from synthetic specs."""
today = datetime.now(UTC)
self_positions: list[Position] = []
pid = 7_000_001
for iid, units, invested, unrealized, days in SELF_STOCKS:
self_positions.append(
_build_self_position(
position_id=pid,
instrument_id=iid,
units=units,
invested=invested,
unrealized=unrealized,
days_open=days,
)
)
pid += 1
mirrors: list[Mirror] = []
mpid = 8_000_001
for spec_idx, spec in enumerate(MIRRORS, start=1):
positions = []
for h_idx, (iid, units, invested, unrealized) in enumerate(spec.holdings, start=1):
positions.append(
_build_mirror_position(
position_id=mpid,
mirror_id=spec_idx,
parent_position_id=900_000 + mpid,
instrument_id=iid,
units=units,
invested=invested,
unrealized=unrealized,
days_open=int(
spec.age_months * 30 * (0.4 + 0.6 * (h_idx / len(spec.holdings)))
),
)
)
mpid += 1
started_dt = today - timedelta(days=spec.age_months * 30)
mirrors.append(
Mirror.model_validate(
{
"mirrorID": spec_idx,
"parentCID": spec.cid,
"parentUsername": spec.username,
"startedCopyDate": _utc_iso(started_dt),
"initialInvestment": spec.initial_invest,
"depositSummary": spec.deposit_summary,
"withdrawalSummary": spec.withdrawal_summary,
"availableAmount": spec.available,
"closedPositionsNetProfit": spec.closed_pnl,
"isPaused": spec.is_paused,
"positions": [p.model_dump(by_alias=True) for p in positions],
}
)
)
return ClientPortfolio.model_validate(
{
"credit": CASH_BALANCE,
"positions": [p.model_dump(by_alias=True) for p in self_positions],
"mirrors": [m.model_dump(by_alias=True) for m in mirrors],
"orders": list(PENDING_ORDERS),
}
)
def build_closed_trades() -> list[ClosedTrade]:
"""Spread ~120 fake closed trades across ~6 months for the heatmap & history."""
out: list[ClosedTrade] = []
today = datetime.now(UTC).date()
rng_seed = 42
def _pseudo(idx: int, salt: int) -> float:
nonlocal rng_seed
rng_seed = (rng_seed * 1103515245 + 12345 + idx + salt) & 0x7FFFFFFF
return rng_seed / 0x7FFFFFFF
pid = 6_000_001
for day_offset in range(170):
d = today - timedelta(days=day_offset)
# Skip weekends to make heatmap look like trading-day driven activity.
if d.weekday() >= 5 and _pseudo(day_offset, 1) > 0.3:
continue
# Most days have 0-2 closed trades; some bursty days have a few.
n = 0
roll = _pseudo(day_offset, 2)
if roll > 0.85:
n = 3
elif roll > 0.6:
n = 2
elif roll > 0.25:
n = 1
for trade_idx in range(n):
iid_choice = INSTRUMENTS[int(_pseudo(day_offset, 10 + trade_idx) * len(INSTRUMENTS))]
is_copy = _pseudo(day_offset, 20 + trade_idx) < 0.55
net_profit = (_pseudo(day_offset, 30 + trade_idx) - 0.42) * 380.0
units = round(0.05 + _pseudo(day_offset, 40 + trade_idx) * 10.0, 4)
close_dt = datetime.combine(d, datetime.min.time(), tzinfo=UTC) + timedelta(
hours=10 + trade_idx
)
open_dt = close_dt - timedelta(days=1 + int(_pseudo(day_offset, 50 + trade_idx) * 20))
out.append(
ClosedTrade.model_validate(
{
"positionId": pid,
"instrumentId": iid_choice.instrument_id,
"isBuy": True,
"units": units,
"openTimestamp": _utc_iso(open_dt),
"closeTimestamp": _utc_iso(close_dt),
"openRate": 100.0 + _pseudo(day_offset, 60) * 50,
"closeRate": 100.0 + _pseudo(day_offset, 70) * 50,
"netProfit": round(net_profit, 2),
"leverage": 1,
"parentPositionId": 999_000 + pid if is_copy else 0,
"socialTradeId": 5_000_000 + pid if is_copy else 0,
"mirrorId": (1 + (pid % len(MIRRORS))) if is_copy else 0,
}
)
)
pid += 1
return out
def build_monthly_gain_entries() -> list[MonthlyGainEntry]:
today = datetime.now(UTC).date().replace(day=1)
cursor = today
out: list[MonthlyGainEntry] = []
# MONTHLY_GAIN_PCT is oldest -> newest; we walk backwards from the
# current month so the most recent entry corresponds to MONTHLY_GAIN_PCT[-1].
for gain in reversed(MONTHLY_GAIN_PCT):
out.append(
MonthlyGainEntry.model_validate(
{
"timestamp": cursor.strftime("%Y-%m-01T00:00:00Z"),
"gain": gain,
"riskScore": 4,
}
)
)
cursor = (cursor - timedelta(days=1)).replace(day=1)
return list(reversed(out))
def build_instrument_metadata() -> list[InstrumentMetadata]:
return [
InstrumentMetadata.model_validate(
{
"instrumentID": i.instrument_id,
"symbolFull": i.ticker,
"internalSymbolFull": i.ticker,
"symbol": i.ticker,
"instrumentDisplayName": i.name,
"displayName": i.name,
"industryID": i.industry_id,
"stockIndustryID": i.industry_id,
"instrumentTypeID": i.type_id,
}
)
for i in INSTRUMENTS
]
# ---------------------------------------------------------------------------
# Repo population
# ---------------------------------------------------------------------------
def _equity_for(snapshot_index: int, total_snapshots: int, *, target: float) -> float:
"""Return a smooth-ish equity value at index ``snapshot_index``.
The curve climbs from ~0.78 * target to ``target`` with a couple of
bumps so the equity-curve panel and the summary sparkline have shape.
"""
progress = snapshot_index / max(total_snapshots - 1, 1)
base = 0.78 + 0.22 * progress
wobble = 0.025 * math.sin(progress * 9.0) + 0.012 * math.cos(progress * 21.0)
return target * (base + wobble)
def populate_repo(app: EtoroTuiApp) -> None:
"""Insert the canonical snapshot + ~30 historical points for the equity curve."""
cp = build_client_portfolio()
closed_trades = build_closed_trades()
monthly_gain = build_monthly_gain_entries()
instruments = build_instrument_metadata()
# Aggregates for the canonical row.
invested_self = sum(s[2] for s in SELF_STOCKS)
unrealized_self = sum(s[3] for s in SELF_STOCKS)
invested_copies = sum(
m.initial_invest + m.deposit_summary - m.withdrawal_summary for m in MIRRORS
)
closed_copies = sum(m.closed_pnl for m in MIRRORS)
open_unreal_copies = sum(m.open_unrealized for m in MIRRORS)
total_invested = invested_self + invested_copies
total_pnl = unrealized_self + closed_copies + open_unreal_copies
target_equity = CASH_BALANCE + total_invested + total_pnl
raw_pnl_json = (
f'{{"clientPortfolio": {cp.model_dump_json(by_alias=True)} }}' # PnlResponse shape
)
raw_portfolio_json = raw_pnl_json # The portfolio endpoint returns the same shape.
# First, write 32 historical snapshots (oldest -> newest, excluding "now").
history_count = 32
for i in range(history_count):
ts = datetime.now(UTC) - timedelta(days=(history_count - i) * 3, hours=2)
equity = _equity_for(i, history_count, target=target_equity)
# For history rows we keep raw_pnl_json minimal so they don't pollute
# rehydrate (only the most-recent snapshot's raw_pnl_json is used for
# building the SnapshotView via PortfolioService.rehydrate_from_repo).
slim_cp = ClientPortfolio.model_validate({"credit": CASH_BALANCE})
slim_pnl = f'{{"clientPortfolio": {slim_cp.model_dump_json(by_alias=True)} }}'
record = SnapshotRecord(
fetched_at=ts.isoformat(),
mode="real",
username="madpin_demo",
cid=99_001,
credit=CASH_BALANCE,
equity=equity,
total_invested=total_invested * (0.85 + 0.15 * (i / history_count)),
total_pnl=equity - CASH_BALANCE - total_invested * (0.85 + 0.15 * (i / history_count)),
raw_portfolio_json=slim_pnl,
raw_pnl_json=slim_pnl,
client_portfolio=slim_cp,
closed_trades=[],
monthly_gain=[],
)
app.repo.insert_snapshot(record)
# Canonical "current" snapshot.
canonical_ts = datetime.now(UTC).isoformat()
canonical = SnapshotRecord(
fetched_at=canonical_ts,
mode="real",
username="madpin_demo",
cid=99_001,
credit=CASH_BALANCE,
equity=target_equity,
total_invested=total_invested,
total_pnl=total_pnl,
raw_portfolio_json=raw_portfolio_json,
raw_pnl_json=raw_pnl_json,
client_portfolio=cp,
closed_trades=closed_trades,
monthly_gain=monthly_gain,
)
app.repo.insert_snapshot(canonical)
app.repo.upsert_instruments(instruments)
# Seed the in-memory market cache so the very first rehydrate already has
# ticker labels (the repo re-read happens via market.get_cached() / resolve()).
for meta in instruments:
app.market._memo[meta.instrument_id] = meta
# Pre-populate the mirror_service gain cache and the copy-risk panel's
# tradeinfo cache so panels that normally hit the network come up with
# rich content instead of em-dashes.
_seed_mirror_metadata(app)
# A couple of journal notes so the dashboard "Journal" stat is non-zero.
app.repo.add_journal_note(
target_kind="instrument",
target_id="1003",
body="NVDA: trim above $1100, redeploy into VOO.",
)
app.repo.add_journal_note(
target_kind="mirror",
target_id="kim_tech",
body="Watch drawdown — paused threshold at -10%.",
)
def _seed_mirror_metadata(app: EtoroTuiApp) -> None:
"""Inject monthly-gain + trade-info caches for every fake mirror.
Both panels (``MirrorComparePanel`` and ``CopyRiskPanel``) normally hit
``/people/{user}/gain`` and ``/people/{user}/tradeinfo`` in background
workers. Without network those calls fail, so we pre-fill the in-memory
caches with synthetic data that matches the same shapes.
"""
from etorotui.api.models import GainResponse
today = datetime.now(UTC).date().replace(day=1)
for spec in MIRRORS:
# Build 12 monthly entries from oldest to newest.
cursor = today
entries: list[MonthlyGainEntry] = []
for gain in reversed(spec.monthly_gain_pct):
entries.append(
MonthlyGainEntry.model_validate(
{
"timestamp": cursor.strftime("%Y-%m-01T00:00:00Z"),
"gain": gain,
"riskScore": spec.risk_score,
}
)
)
cursor = (cursor - timedelta(days=1)).replace(day=1)
gain_resp = GainResponse(monthly=list(reversed(entries)), yearly=[])
app.mirror_service._gain_cache[spec.username] = gain_resp
# ---------------------------------------------------------------------------
# A network-free EtoroTuiApp subclass
# ---------------------------------------------------------------------------
class ScreenshotApp(EtoroTuiApp):
"""An ``EtoroTuiApp`` whose refresh actions never touch the network."""
# CSS_PATH on the parent is resolved relative to the file the subclass
# lives in, which would point inside ``scripts/``. Pin it to the package
# asset so the screenshot script picks up the real theme.
CSS_PATH = str(SRC / "etorotui" / "theme.tcss")
def _initial_refresh(self) -> None: # type: ignore[override]
cached = self.portfolio.rehydrate_from_repo()
if cached is None:
return
self.last_snapshot = cached
self._last_snapshot_id = cached.snapshot_id
self._set_status("Demo data loaded — synthetic numbers, no network.")
for screen in list(self.screen_stack):
if hasattr(screen, "apply_snapshot"):
screen.apply_snapshot(cached)
def action_refresh(self) -> None: # type: ignore[override]
self.notify("Demo mode — refresh disabled in screenshot app.", timeout=2)
def action_refresh_tickers(self) -> None: # type: ignore[override]
self.notify("Demo mode — ticker refresh disabled.", timeout=2)
# ---------------------------------------------------------------------------
# Capture loop
# ---------------------------------------------------------------------------
# (filename, panel_id_or_action)
# Action prefixes:
# "panel:<id>" activate the named main-screen tab via focus_panel_id
# "help" push the help overlay
SHOTS: list[tuple[str, str]] = [
("01-dashboard.svg", "panel:dashboard"),
("02-stocks.svg", "panel:stocks"),
("03-mirrors.svg", "panel:mirrors"),
("04-lookthrough.svg", "panel:lookthrough"),
("05-monthly.svg", "panel:monthly"),
("06-equity-curve.svg", "panel:equity_curve"),
("07-allocation.svg", "panel:allocation"),
("08-attribution.svg", "panel:attribution"),
("09-heatmap.svg", "panel:heatmap"),
("10-trade-history.svg", "panel:trade_history"),
("11-copy-risk.svg", "panel:copy_risk"),
("12-mirror-compare.svg", "panel:mirror_compare"),
("13-cash-orders.svg", "panel:cash_orders"),
("14-whatif.svg", "panel:whatif"),
("15-help.svg", "help"),
]
def _find_main_screen(app: ScreenshotApp):
"""Locate the MainScreen instance (it sits on top of Textual's default screen)."""
from etorotui.ui.screens.main import MainScreen
for s in reversed(app.screen_stack):
if isinstance(s, MainScreen):
return s
return None
def _seed_copy_risk_panel(app: ScreenshotApp) -> None:
"""Inject synthetic TradeInfo so the Copy Risk panel shows rich rows.
The panel's tradeinfo cache is per-instance and only exists after the
panel is mounted, so this must run after ``app.run_test`` has started.
"""
from etorotui.api.models import TradeInfo
main_screen = _find_main_screen(app)
if main_screen is None:
return
panel = main_screen._panels.get("copy_risk")
if panel is None:
return
for spec in MIRRORS:
panel._tradeinfo_cache[spec.username] = TradeInfo.model_validate(
{
"username": spec.username,
"isPopularInvestor": spec.username in {"morgan_steady", "priya_growth"},
"riskScore": spec.risk_score,
"drawdown": spec.drawdown_pct,
"copiers": int(800 + spec.cid * 0.3),
"winRatio": 0.55 + (spec.risk_score - 5) * 0.02,
"aumTier": ("L" if spec.initial_invest > 5000 else "M"),
}
)
# Re-render with the freshly seeded cache.
if panel._pending_snapshot is not None:
panel._render_rows(panel._pending_snapshot)
async def _drive_whatif_panel(app: ScreenshotApp, pilot) -> None:
"""Fill in a target equity and trigger the Project button."""
from textual.widgets import Button
main_screen = _find_main_screen(app)
if main_screen is None:
return
panel = main_screen._panels.get("whatif")
if panel is None:
return
panel._target.value = "200000"
await pilot.pause()
panel.on_button_pressed(Button.Pressed(panel._compute))
await pilot.pause()
async def capture(app: ScreenshotApp) -> None:
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
async with app.run_test(size=TERMINAL_SIZE) as pilot:
# Let on_mount + _initial_refresh run, then give the layout a couple
# of frames to settle (TabbedContent needs a tick to mount panes).
for _ in range(4):
await pilot.pause()
# Seed per-panel caches that the network would otherwise populate.
_seed_copy_risk_panel(app)
await pilot.pause()
for filename, action in SHOTS:
if action == "help":
app.action_help()
for _ in range(3):
await pilot.pause()
app.save_screenshot(filename=filename, path=str(OUTPUT_DIR))
# Pop the help modal so the next iteration starts clean.
# Calling pop_screen directly is safer than firing an "escape"
# binding because some Textual builds raise during the
# binding chain check while a modal is open.
app.pop_screen()
for _ in range(2):
await pilot.pause()
continue
assert action.startswith("panel:")
panel_id = action.split(":", 1)[1]
main_screen = _find_main_screen(app)
if main_screen is None:
continue
main_screen.focus_panel_id(panel_id)
# Two pauses cover: (1) the reactive tab-active setter dispatching,
# (2) the panel's apply_snapshot + Plotext lazy first paint.
for _ in range(3):
await pilot.pause()
# Per-panel post-activation tweaks so the screenshot has content
# the static apply_snapshot path doesn't yet produce.
if panel_id == "whatif":
await _drive_whatif_panel(app, pilot)
for _ in range(2):
await pilot.pause()
app.save_screenshot(filename=filename, path=str(OUTPUT_DIR))
def main() -> int:
workdir = Path(tempfile.mkdtemp(prefix="etorotui-screenshots-"))
try:
cfg = Config()
cfg.history.db_path = str(workdir / "snapshots.db")
cfg.history.instrument_cache_path = str(workdir / "instruments.json")
cfg.history.retain_snapshots_days = 0 # never prune our demo history
app = ScreenshotApp(
config=cfg,
api_key="demo-key",
user_key="demo-user",
debug=False,
)
populate_repo(app)
asyncio.run(capture(app))
print(f"Wrote {len(SHOTS)} screenshots to {OUTPUT_DIR}")
return 0
finally:
shutil.rmtree(workdir, ignore_errors=True)
if __name__ == "__main__":
sys.exit(main())