-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
871 lines (781 loc) · 32.4 KB
/
app.py
File metadata and controls
871 lines (781 loc) · 32.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
865
866
867
868
869
870
871
"""
Crypto Direction Game - Streamlit App
A modular Streamlit-based game for predicting crypto price direction
with regime filtering, trade simulation, timed mode, and bias analytics.
"""
from __future__ import annotations
import random
from pathlib import Path
import pandas as pd
import streamlit as st
from config import GameConfig, DEFAULT_CONFIG
from regimes import compute_regimes_for_asset, filter_windows_by_regime
from trade_engine import classify_outcome, simulate_trade
from stats_tracker import SessionStats
from bias_analytics import render_bias_dashboard
from market_cap import get_market_caps, filter_symbols_by_market_cap
from metrics import load_metrics, get_available_metrics, filter_symbols_by_metric
# ---------------------------------------------------------------------------
# Config & Data Loading (cached)
# ---------------------------------------------------------------------------
@st.cache_data
def load_market_caps() -> dict[str, float]:
"""Load market caps from market_caps.csv."""
return get_market_caps()
@st.cache_data
def load_metrics_cached(symbol: str) -> pd.DataFrame | None:
"""Load metrics for a symbol. Cached."""
return load_metrics(symbol)
@st.cache_data
def filter_symbols_by_metric_cached(symbols: tuple[str, ...], metric: str) -> tuple[str, ...]:
"""Filter symbols to those with valid metric data. Cached."""
return tuple(filter_symbols_by_metric(list(symbols), metric))
@st.cache_data
def load_candles(symbol: str, candles_dir: str) -> pd.DataFrame | None:
"""Load candle data for a symbol."""
path = Path(candles_dir) / f"{symbol}USDT.csv"
if not path.exists():
return None
df = pd.read_csv(path)
df["datetime"] = pd.to_datetime(df["datetime"])
return df
@st.cache_data
def load_all_regimes(
symbols: tuple[str, ...],
candles_dir: str,
window_days: int,
forward_days: int,
threshold: float,
adx_trending: float,
adx_ranging: float,
volatility_days: int,
step: int = 6,
) -> dict[str, pd.DataFrame]:
"""Pre-compute regimes for assets. Cached. step=6 samples ~1 window/day for 4h data."""
config = GameConfig(
window_days=window_days,
forward_days=forward_days,
threshold=threshold,
adx_threshold_trending=adx_trending,
adx_threshold_ranging=adx_ranging,
volatility_days=volatility_days,
)
result = {}
for sym in symbols:
df = load_candles(sym, candles_dir)
if df is not None and len(df) > 100:
regimes = compute_regimes_for_asset(df, config, step=step)
if len(regimes) > 0:
result[sym] = regimes
return result
@st.dialog("Rules & How to Play")
def show_rules_dialog():
st.markdown("""
## What is this game?
A **pattern recognition and trading simulation** game. You see a historical price chart and predict whether the price will go **UP**, **DOWN**, or **SAME** over the next 14 days.
## Goal
Improve your **trading intuition** and **pattern recognition** while building **objective stats** about your performance. Track accuracy, bias, streak sensitivity, and (in Trade Mode) simulated PnL.
## How it works
1. **Configure** settings and click **Apply Settings & Prepare Game**
2. Click **Start Round** to see a price chart (asset and dates hidden until you answer)
3. Predict: **↑ UP** (price rises >5%), **→ SAME** (within ±5%), or **↓ DOWN** (price falls >5%)
4. After submitting, the future period is revealed and your result is shown
5. Click **Next Round** to continue
## Modes
- **Classification Mode**: Track accuracy only
- **Trade Simulation Mode**: Simulate long/short positions, track equity, PnL, and bust risk (game ends if equity falls below 5%)
## Tips
- Use **Regime Filters** to practice in specific market conditions
- Use **Market Cap** filters to focus on majors, large caps, etc.
- Check the **Bias Dashboard** to spot prediction biases and streak patterns
""")
def get_available_symbols(candles_dir: str) -> list[str]:
"""List available symbols from candles dir."""
path = Path(candles_dir)
if not path.exists():
return []
symbols = []
for f in path.glob("*USDT.csv"):
symbols.append(f.stem.replace("USDT", ""))
return sorted(symbols)
# ---------------------------------------------------------------------------
# Session State
# ---------------------------------------------------------------------------
def init_session_state():
if "stats" not in st.session_state:
st.session_state.stats = SessionStats()
if "current_round" not in st.session_state:
st.session_state.current_round = None
if "answer_submitted" not in st.session_state:
st.session_state.answer_submitted = False
if "timer_start" not in st.session_state:
st.session_state.timer_start = None
if "game_ready" not in st.session_state:
st.session_state.game_ready = False
if "pool" not in st.session_state:
st.session_state.pool = []
# ---------------------------------------------------------------------------
# UI Components
# ---------------------------------------------------------------------------
def render_equity_curve(stats: SessionStats):
"""Mini equity curve in sidebar."""
if not stats.trade_returns:
return
import plotly.graph_objects as go
equity = stats.equity_curve
fig = go.Figure()
fig.add_trace(go.Scatter(
y=equity,
mode="lines",
line=dict(color="#00d4aa", width=2),
fill="tozeroy",
))
fig.update_layout(
title="Equity Curve",
height=200,
margin=dict(l=20, r=20, t=40, b=20),
xaxis=dict(showticklabels=False),
yaxis=dict(title=""),
template="plotly_dark",
paper_bgcolor="rgba(0,0,0,0)",
plot_bgcolor="rgba(0,0,0,0)",
)
st.plotly_chart(fig, use_container_width=True, config={"displayModeBar": False})
def render_unified_chart(
df: pd.DataFrame,
start_idx: int,
end_idx: int,
config: GameConfig,
symbol: str,
show_future: bool = False,
entry_price: float | None = None,
exit_price: float | None = None,
reveal: bool = False,
use_metrics: bool = False,
selected_metric: str | None = None,
metric_style: str = "line",
):
"""
Single chart: historical (60-day) + optional future (14-day) attached to the right.
Volume bars below price. When reveal=False: hide asset name and time axis.
"""
import plotly.graph_objects as go
from plotly.subplots import make_subplots
df = df.copy()
df.columns = [c.lower() for c in df.columns]
hist = df.iloc[start_idx:end_idx]
has_metric = use_metrics and selected_metric
fig = make_subplots(
rows=2,
cols=1,
shared_xaxes=True,
vertical_spacing=0.03,
row_heights=[0.7, 0.3],
subplot_titles=("Price", "Volume"),
specs=[[{"secondary_y": has_metric}], [{}]],
)
fig.add_trace(
go.Candlestick(
x=hist["datetime"],
open=hist["open"],
high=hist["high"],
low=hist["low"],
close=hist["close"],
name="OHLC",
),
row=1,
col=1,
)
# Metric overlay: load, merge, plot on right y-axis with raw values
# Metrics are often daily; forward-fill to align with 4h candles for a continuous line
if use_metrics and selected_metric:
metrics_df = load_metrics_cached(symbol)
if metrics_df is not None and selected_metric in metrics_df.columns:
merged = hist[["datetime", "close"]].copy()
merged = merged.merge(
metrics_df[["timestamp", selected_metric]],
left_on="datetime",
right_on="timestamp",
how="left",
)
vals = merged[selected_metric].ffill() # forward-fill: metrics are often daily, propagate to 4h
if vals.notna().any():
x_vals = merged["datetime"]
y_vals = vals # raw values for right axis
trace_kw = dict(row=1, col=1, secondary_y=True)
if metric_style == "bar":
fig.add_trace(
go.Bar(
x=x_vals,
y=y_vals,
name=selected_metric,
marker_color="#ffa726",
opacity=0.6,
),
**trace_kw,
)
elif metric_style == "area":
fig.add_trace(
go.Scatter(
x=x_vals,
y=y_vals,
mode="lines",
name=selected_metric,
line=dict(color="#ffa726", width=1.5),
fill="tozeroy",
fillcolor="rgba(255, 167, 38, 0.2)",
),
**trace_kw,
)
elif metric_style == "scatter":
fig.add_trace(
go.Scatter(
x=x_vals,
y=y_vals,
mode="markers",
name=selected_metric,
marker=dict(color="#ffa726", size=4, symbol="circle"),
),
**trace_kw,
)
else:
fig.add_trace(
go.Scatter(
x=x_vals,
y=y_vals,
mode="lines",
name=selected_metric,
line=dict(color="#ffa726", width=1.5, dash="dot"),
),
**trace_kw,
)
colors = ["#26a69a" if c >= o else "#ef5350" for c, o in zip(hist["close"], hist["open"])]
fig.add_trace(
go.Bar(x=hist["datetime"], y=hist["volume"], marker_color=colors, name="Volume"),
row=2,
col=1,
)
if show_future:
exit_idx = end_idx + config.forward_candles - 1
if exit_idx < len(df):
future = df.iloc[end_idx : exit_idx + 1]
fig.add_trace(
go.Scatter(
x=future["datetime"],
y=future["close"],
mode="lines+markers",
name="Future",
line=dict(color="#00d4aa", width=2),
),
row=1,
col=1,
)
if entry_price is not None and exit_price is not None:
fig.add_hline(y=entry_price * (1 + config.threshold), line_dash="dash", line_color="green", annotation_text="+5%", row=1, col=1)
fig.add_hline(y=entry_price * (1 - config.threshold), line_dash="dash", line_color="red", annotation_text="-5%", row=1, col=1)
fig.add_hline(y=entry_price, line_dash="dot", line_color="gray", annotation_text="Entry", row=1, col=1)
fig.add_hline(y=exit_price, line_dash="dot", line_color="orange", annotation_text="Exit", row=1, col=1)
layout = dict(
height=600,
xaxis_rangeslider_visible=False,
template="plotly_dark",
)
if reveal:
layout["title"] = f"{symbol} — {config.window_days}-day window" + (" + 14-day future" if show_future else "")
else:
layout["title"] = ""
if has_metric and selected_metric:
layout["yaxis2"] = dict(
title=dict(text=selected_metric, font=dict(color="#ffa726")),
showgrid=False,
tickfont=dict(color="#ffa726"),
)
fig.update_layout(**layout)
if not reveal:
fig.update_xaxes(showticklabels=False)
st.plotly_chart(fig, use_container_width=True)
# ---------------------------------------------------------------------------
# Main App
# ---------------------------------------------------------------------------
def main():
st.set_page_config(page_title="Crypto Direction Game", layout="wide", initial_sidebar_state="expanded")
st.title("Crypto Direction Game")
init_session_state()
config = DEFAULT_CONFIG
candles_dir = config.candles_dir
symbols = get_available_symbols(candles_dir)
if not symbols:
st.error("No candle data found. Place CSV files in candles_4h/")
return
# Load market caps from CSV for filter
market_caps = load_market_caps()
# Sidebar: Config (mode outside form so toggle updates UI immediately)
with st.sidebar:
st.header("Settings")
if st.button("Rules", help="How to play and what the game is about"):
show_rules_dialog()
mode = st.radio(
"Mode",
["Classification Mode", "Trade Simulation Mode"],
index=0,
key="mode_radio",
help="Classification: track accuracy only. Trade Simulation: simulate positions, track equity and PnL.",
)
trade_mode = mode == "Trade Simulation Mode"
st.subheader("Metrics")
use_metrics = st.checkbox(
"Use metrics",
value=st.session_state.get("use_metrics_checkbox", st.session_state.get("use_metrics", False)),
key="use_metrics_checkbox",
help="Overlay a selected metric on the price chart. Metric values are scaled to fit the chart.",
)
available_metrics = get_available_metrics()
selected_metric = None
if use_metrics and available_metrics:
selected_metric = st.selectbox(
"Metric",
options=available_metrics,
key="metric_selectbox",
help="Metric to overlay on the price chart.",
)
metric_style = st.selectbox(
"Metric style",
options=["line", "bar", "area", "scatter"],
key="metric_style_selectbox",
help="How to display the metric: line, bar, area fill, or scatter points.",
)
else:
metric_style = "line"
with st.form("settings_form", clear_on_submit=False):
timed_mode = st.checkbox(
"Timed Mode",
value=False,
help="Answer within the timer or it counts as incorrect.",
)
position_pct = 100
if trade_mode:
position_pct = st.slider(
"Position size (% of equity)",
0,
100,
100,
help="How much of your equity to risk per trade. Lower = less risk, slower equity growth.",
)
cfg_window = st.slider(
"Sample period (days)",
30,
120,
config.window_days,
key="cfg_window",
help="Length of the historical chart you see before making a prediction.",
)
st.subheader("Regime Filters")
trend_opts = ["trending", "ranging", "neutral"]
vol_opts = ["low", "medium", "high"]
prior_opts = ["strong_up", "strong_down", "mild"]
trend_filter = st.multiselect(
"Trend",
trend_opts,
default=[],
help="Filter by ADX trend: trending (strong direction), ranging (sideways), or neutral.",
)
volatility_filter = st.multiselect(
"Volatility",
vol_opts,
default=[],
help="Filter by 14-day realized volatility: low, medium, or high.",
)
prior_move_filter = st.multiselect(
"Prior Move",
prior_opts,
default=[],
help="Filter by price move over the sample period: strong up (>20%), strong down (<-20%), or mild.",
)
st.subheader("Market Cap")
cap_opts = ["majors", "large_caps", "mid_caps", "small_caps"]
cap_labels = {
"majors": "Majors (>$5B)",
"large_caps": "Large caps ($500M–$5B)",
"mid_caps": "Mid caps ($50M–$500M)",
"small_caps": "Small caps (<$50M)",
}
market_cap_filter = st.multiselect(
"Market cap tiers",
options=cap_opts,
format_func=lambda x: cap_labels[x],
default=[],
help="Filter assets by market cap. Empty = all assets.",
)
filtered_symbols = (
filter_symbols_by_market_cap(symbols, market_caps, market_cap_filter)
if market_cap_filter and market_caps
else symbols
)
if not filtered_symbols:
filtered_symbols = symbols
# When Use metrics is enabled, keep only assets with valid metric data
if use_metrics and selected_metric:
filtered_symbols = list(
filter_symbols_by_metric_cached(tuple(filtered_symbols), selected_metric)
)
if not filtered_symbols:
st.warning(
f"No assets have valid data for metric '{selected_metric}'. "
"Disable Use metrics or choose another metric."
)
n_symbols = len(filtered_symbols)
num_assets = st.slider(
"Assets to sample from",
min_value=1,
max_value=max(1, n_symbols),
value=min(n_symbols, max(1, n_symbols)),
help="Number of assets to randomly sample rounds from. More = more variety.",
)
with st.expander("Advanced Config"):
cfg_forward = st.number_input(
"forward_days",
7,
30,
config.forward_days,
key="cfg_forward",
help="Days into the future you're predicting (hold period in Trade Mode).",
)
cfg_thresh = st.number_input(
"threshold",
0.01,
0.20,
float(config.threshold),
0.01,
key="cfg_thresh",
help="Price move threshold for UP/DOWN. Above +threshold = UP, below -threshold = DOWN.",
)
cfg_adx_t = st.number_input(
"ADX trending",
15.0,
40.0,
config.adx_threshold_trending,
1.0,
key="cfg_adx_t",
help="ADX above this = trending regime.",
)
cfg_adx_r = st.number_input(
"ADX ranging",
10.0,
25.0,
config.adx_threshold_ranging,
1.0,
key="cfg_adx_r",
help="ADX below this = ranging regime.",
)
cfg_vol = st.number_input(
"volatility_days",
7,
30,
config.volatility_days,
key="cfg_vol",
help="Lookback for realized volatility calculation.",
)
cfg_timer = int(
st.number_input(
"timer_seconds",
1,
30,
config.timer_seconds,
key="cfg_timer",
help="Seconds to answer in Timed Mode.",
)
)
config = GameConfig(
window_days=cfg_window,
forward_days=cfg_forward,
threshold=cfg_thresh,
adx_threshold_trending=cfg_adx_t,
adx_threshold_ranging=cfg_adx_r,
volatility_days=cfg_vol,
timer_seconds=cfg_timer,
)
apply_clicked = st.form_submit_button("Apply Settings & Prepare Game")
if apply_clicked:
# Reset session state for fresh start with new settings
st.session_state.current_round = None
st.session_state.answer_submitted = False
if "pending_result" in st.session_state:
del st.session_state.pending_result
if "timer_start" in st.session_state:
del st.session_state.timer_start
if "countdown" in st.session_state:
del st.session_state.countdown
with st.spinner("Computing regimes (may take a moment)..."):
sample_symbols = tuple(list(filtered_symbols)[:num_assets])
all_regimes = load_all_regimes(
sample_symbols,
candles_dir,
config.window_days,
config.forward_days,
config.threshold,
config.adx_threshold_trending,
config.adx_threshold_ranging,
config.volatility_days,
step=6,
)
pool = []
for sym, regimes_df in all_regimes.items():
filtered = filter_windows_by_regime(
regimes_df,
trend_filter or None,
volatility_filter or None,
prior_move_filter or None,
)
for _, row in filtered.iterrows():
pool.append((sym, int(row["start_idx"]), dict(row)))
st.session_state.pool = pool
st.session_state.game_config = config
st.session_state.game_ready = len(pool) > 0
st.session_state.position_pct = position_pct
st.session_state.use_metrics = use_metrics
st.session_state.selected_metric = selected_metric if use_metrics else None
st.session_state.metric_style = metric_style if use_metrics else "line"
if trade_mode:
st.session_state.stats.equity = 1.0
st.session_state.stats.bust = False
if st.session_state.game_ready:
st.success(f"Ready! {len(pool)} windows available.")
else:
st.warning("No windows match filters. Relax filters and apply again.")
st.rerun()
config = st.session_state.get("game_config", config)
pool = st.session_state.get("pool", [])
# Sidebar: Stats & Equity
with st.sidebar:
stats = st.session_state.stats
st.subheader("Stats")
st.metric("Accuracy", f"{stats.accuracy:.1%}")
if trade_mode:
st.metric("Equity", f"{stats.equity:.1%}")
st.metric("Cumulative PnL", f"{stats.cumulative_pnl:.2%}")
st.metric("Win Rate", f"{stats.win_rate:.1%}")
st.metric("Sharpe", f"{stats.sharpe_ratio:.2f}")
st.metric("Max DD", f"{stats.max_drawdown:.1%}")
st.metric("Avg Win", f"{stats.avg_win:.2%}")
st.metric("Avg Loss", f"{stats.avg_loss:.2%}")
render_equity_curve(stats)
if timed_mode:
st.metric("Timed Accuracy", f"{stats.timed_correct / stats.timed_total:.1%}" if stats.timed_total else "N/A")
st.metric("Untimed Accuracy", f"{stats.untimed_correct / stats.untimed_total:.1%}" if stats.untimed_total else "N/A")
# Main area: Round or Start
if st.session_state.current_round is None:
if not st.session_state.game_ready or not pool:
st.info(
"Configure settings in the sidebar and click **Apply Settings & Prepare Game** to start."
)
st.divider()
render_bias_dashboard(st.session_state.stats, st)
return
st.subheader("Ready to play")
if st.button("Start Round", type="primary", use_container_width=True):
sym, start_idx, regime = random.choice(pool)
st.session_state.current_round = {
"symbol": sym,
"start_idx": start_idx,
"regime": regime,
}
st.session_state.answer_submitted = False
if timed_mode:
st.session_state.timer_start = pd.Timestamp.now()
st.rerun()
st.divider()
render_bias_dashboard(st.session_state.stats, st)
return
# In round
round_data = st.session_state.current_round
symbol = round_data["symbol"]
start_idx = round_data["start_idx"]
regime = round_data["regime"]
df = load_candles(symbol, candles_dir)
if df is None:
st.error("Failed to load data")
st.session_state.current_round = None
st.rerun()
return
df = df.copy()
df.columns = [c.lower() for c in df.columns]
end_idx = start_idx + config.window_candles
window_df = df.iloc[start_idx:end_idx]
# Timer (if timed mode)
if timed_mode and not st.session_state.answer_submitted:
elapsed = (pd.Timestamp.now() - st.session_state.timer_start).total_seconds()
remaining = max(0, config.timer_seconds - elapsed)
if remaining <= 0:
# Auto-submit as "No Answer"
entry_price = float(window_df.iloc[-1]["close"])
exit_price = float(df.iloc[end_idx + config.forward_candles - 1]["close"])
actual = classify_outcome(entry_price, exit_price, config.threshold)
regime_key = f"{regime.get('trend', '?')}/{regime.get('volatility', '?')}/{regime.get('prior_move', '?')}"
position_pct = st.session_state.get("position_pct", 100)
st.session_state.stats.record(
prediction=None,
actual=actual,
correct=False,
trade_return=0.0,
regime_key=regime_key,
was_timed=True,
position_pct=position_pct,
)
st.session_state.answer_submitted = True
st.session_state.pending_result = {
"prediction": None,
"actual": actual,
"correct": False,
"trade_return": 0.0,
"trade_result": type("TradeResult", (), {"entry_price": entry_price, "exit_price": exit_price})(),
"was_timed": True,
"timed_out": True,
}
st.rerun()
st.progress(remaining / config.timer_seconds)
st.caption(f"Time remaining: {remaining:.1f}s")
# Unified chart (historical only when guessing; + future when revealed)
show_future = st.session_state.answer_submitted and "pending_result" in st.session_state
entry_px = None
exit_px = None
if show_future and "pending_result" in st.session_state:
pr = st.session_state.pending_result
tr = pr.get("trade_result")
if tr is not None:
entry_px = getattr(tr, "entry_price", None)
exit_px = getattr(tr, "exit_price", None)
if entry_px is None:
entry_px = float(df.iloc[end_idx - 1]["close"])
exit_px = float(df.iloc[end_idx + config.forward_candles - 1]["close"])
use_metrics = st.session_state.get("use_metrics", False)
selected_metric = st.session_state.get("selected_metric")
metric_style = st.session_state.get("metric_style", "line")
render_unified_chart(
df, start_idx, end_idx, config, symbol,
show_future=show_future,
entry_price=entry_px,
exit_price=exit_px,
reveal=show_future,
use_metrics=use_metrics,
selected_metric=selected_metric,
metric_style=metric_style,
)
# Buttons (only if not submitted)
if not st.session_state.answer_submitted:
st.markdown("""
<style>
section.main [data-testid="column"]:nth-of-type(1) button { background-color: #22c55e !important; color: white !important; }
section.main [data-testid="column"]:nth-of-type(2) button { background-color: #6b7280 !important; color: white !important; }
section.main [data-testid="column"]:nth-of-type(3) button { background-color: #ef4444 !important; color: white !important; }
</style>
""", unsafe_allow_html=True)
col1, col2, col3 = st.columns(3)
with col1:
if st.button("↑ UP", use_container_width=True, key="btn_up"):
submit_answer("UP", df, symbol, start_idx, regime, config, trade_mode, timed_mode)
with col2:
if st.button("→ SAME", use_container_width=True, key="btn_same"):
submit_answer("SAME", df, symbol, start_idx, regime, config, trade_mode, timed_mode)
with col3:
if st.button("↓ DOWN", use_container_width=True, key="btn_down"):
submit_answer("DOWN", df, symbol, start_idx, regime, config, trade_mode, timed_mode)
return
# Result reveal
if "pending_result" in st.session_state:
res = st.session_state.pending_result
actual = res["actual"]
correct = res["correct"]
trade_return = res["trade_return"]
trade_result = res.get("trade_result")
timed_out = res.get("timed_out", False)
if timed_out:
st.warning("Time's up! Counted as incorrect.")
else:
if correct:
st.success(f"Correct! Actual: {actual}")
else:
st.error(f"Incorrect. Actual: {actual}")
if trade_mode and trade_result is not None:
st.metric("Trade Return", f"{trade_return:.2%}")
# Chart with future is already shown above (unified chart)
stats = st.session_state.stats
pool = st.session_state.get("pool", [])
config = st.session_state.get("game_config", DEFAULT_CONFIG)
if stats.bust:
st.error("You're bust! Equity fell below 5% of initial.")
if st.button("New Game", type="primary"):
st.session_state.stats = SessionStats()
del st.session_state.pending_result
st.session_state.current_round = None
st.rerun()
elif st.button("Next Round", type="primary") and pool:
_start_next_round(pool, config, timed_mode)
st.rerun()
st.divider()
render_bias_dashboard(st.session_state.stats, st)
return
def _start_next_round(pool: list, config: GameConfig, timed_mode: bool) -> None:
"""Clear result and start a new round from pool."""
del st.session_state.pending_result
sym, start_idx, regime = random.choice(pool)
st.session_state.current_round = {
"symbol": sym,
"start_idx": start_idx,
"regime": regime,
}
st.session_state.answer_submitted = False
if timed_mode:
st.session_state.timer_start = pd.Timestamp.now()
def submit_answer(
prediction: str,
df: pd.DataFrame,
symbol: str,
start_idx: int,
regime: dict,
config: GameConfig,
trade_mode: bool,
timed_mode: bool,
):
"""Process answer and store result."""
end_idx = start_idx + config.window_candles
exit_idx = end_idx + config.forward_candles - 1
if exit_idx >= len(df):
st.error("Insufficient data")
return
df = df.copy()
df.columns = [c.lower() for c in df.columns]
entry_price = float(df.iloc[end_idx - 1]["close"])
exit_price = float(df.iloc[exit_idx]["close"])
actual = classify_outcome(entry_price, exit_price, config.threshold)
correct = prediction == actual
trade_return = 0.0
trade_result = None
if trade_mode:
trade_result = simulate_trade(df, start_idx, prediction, config)
if trade_result:
trade_return = trade_result.trade_return
regime_key = f"{regime.get('trend', '?')}/{regime.get('volatility', '?')}/{regime.get('prior_move', '?')}"
stats = st.session_state.stats
position_pct = st.session_state.get("position_pct", 100)
stats.record(
prediction=prediction,
actual=actual,
correct=correct,
trade_return=trade_return,
regime_key=regime_key,
was_timed=timed_mode,
position_pct=position_pct,
)
st.session_state.answer_submitted = True
st.session_state.pending_result = {
"prediction": prediction,
"actual": actual,
"correct": correct,
"trade_return": trade_return,
"trade_result": trade_result,
"was_timed": timed_mode,
"timed_out": False,
}
st.rerun()
if __name__ == "__main__":
main()