-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
813 lines (663 loc) · 26.8 KB
/
Copy pathapp.py
File metadata and controls
813 lines (663 loc) · 26.8 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
"""
app.py — StockReplay Flask application.
Session cookie only holds mutable state (~300 bytes).
Static scenario data (dates, briefing, etc.) is stored on disk.
This avoids Flask's 4KB cookie limit which was causing the "finishes immediately" bug.
"""
import json
import os
import re
import sqlite3
import uuid
import logging
from pathlib import Path
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass
import bcrypt
from flask import Flask, render_template, request, jsonify, session, redirect, url_for, g
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from stock_data import (
search_ticker,
get_stock_info,
get_current_price,
fetch_daily_ohlcv,
STOCK_META,
LOGO_MAP,
)
from game_engine import (
pick_scenario,
get_performance_rating,
build_chart_data,
FEATURED_SCENARIOS,
)
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
app = Flask(__name__)
_flask_secret = os.environ.get("FLASK_SECRET")
if not _flask_secret:
raise RuntimeError(
"FLASK_SECRET environment variable is not set. "
"Set it to a strong random value (e.g. `python -c \"import secrets; print(secrets.token_hex(32))\"`)."
)
app.secret_key = _flask_secret
# Session cookie hardening
app.config["SESSION_COOKIE_HTTPONLY"] = True # Prevent JS from reading the session cookie
app.config["SESSION_COOKIE_SAMESITE"] = "Lax" # CSRF mitigation
# SESSION_COOKIE_SECURE should be True in production (HTTPS).
# Set FLASK_HTTPS=1 in your production environment.
app.config["SESSION_COOKIE_SECURE"] = os.environ.get("FLASK_HTTPS", "") == "1"
# ---------------------------------------------------------------------------
# Rate limiter — in-memory storage, no Redis required
# ---------------------------------------------------------------------------
limiter = Limiter(
get_remote_address,
app=app,
default_limits=[],
storage_uri="memory://",
)
DB_PATH = "stockreplay.db"
SCENARIO_DIR = Path("cache/scenarios")
SCENARIO_DIR.mkdir(parents=True, exist_ok=True)
TRADES_DIR = Path("cache/trades")
TRADES_DIR.mkdir(parents=True, exist_ok=True)
# ---------------------------------------------------------------------------
# Auth helpers
# ---------------------------------------------------------------------------
_USERNAME_RE = re.compile(r'^[a-zA-Z0-9_]{3,20}$')
def _hash_password(plain: str) -> str:
return bcrypt.hashpw(plain.encode(), bcrypt.gensalt(12)).decode()
def _check_password(plain: str, hashed: str) -> bool:
try:
return bcrypt.checkpw(plain.encode(), hashed.encode())
except Exception:
return False
# ---------------------------------------------------------------------------
# Scenario file store (keeps session cookie tiny)
# ---------------------------------------------------------------------------
def _scenario_path(sid: str) -> Path:
return SCENARIO_DIR / f"{sid}.json"
def save_scenario(sid, data):
"""Persist static scenario data to disk."""
with open(_scenario_path(sid), "w", encoding="utf-8") as f:
json.dump(data, f)
def load_scenario(sid):
"""Load static scenario data from disk."""
p = _scenario_path(sid)
if not p.exists():
return None
try:
with open(p, encoding="utf-8") as f:
return json.load(f)
except (json.JSONDecodeError, IOError):
return None
# ---------------------------------------------------------------------------
# Trades file store — keeps trades OFF the session cookie (fixes 4KB overflow)
# ---------------------------------------------------------------------------
def _trades_path(sid: str) -> Path:
return TRADES_DIR / f"{sid}.json"
def _load_trades(sid: str) -> list:
p = _trades_path(sid)
if not p.exists():
return []
try:
with open(p, encoding="utf-8") as f:
return json.load(f)
except (json.JSONDecodeError, IOError):
return []
def _save_trades(sid: str, trades: list):
with open(_trades_path(sid), "w", encoding="utf-8") as f:
json.dump(trades, f)
# ---------------------------------------------------------------------------
# Request-scoped OHLCV cache (avoid repeated downloads per request)
# ---------------------------------------------------------------------------
def get_ohlcv(ticker):
"""Fetch OHLCV data, cached for the lifetime of this request via Flask g."""
key = f"ohlcv_{ticker.upper()}"
if not hasattr(g, key):
setattr(g, key, fetch_daily_ohlcv(ticker))
return getattr(g, key)
# ---------------------------------------------------------------------------
# Database
# ---------------------------------------------------------------------------
def get_db():
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
return conn
def init_db():
with get_db() as conn:
# Users table
conn.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
created_at TEXT DEFAULT (datetime('now'))
)
""")
# Leaderboard — original columns
conn.execute("""
CREATE TABLE IF NOT EXISTS leaderboard (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ticker TEXT NOT NULL,
difficulty TEXT NOT NULL,
start_cash REAL NOT NULL,
final_value REAL NOT NULL,
profit_pct REAL NOT NULL,
trades_count INTEGER NOT NULL,
real_start TEXT,
real_end TEXT,
created_at TEXT DEFAULT (datetime('now'))
)
""")
# Additive migrations — safe to run multiple times
for col_sql in [
"ALTER TABLE leaderboard ADD COLUMN user_id INTEGER",
"ALTER TABLE leaderboard ADD COLUMN username TEXT",
]:
try:
conn.execute(col_sql)
except Exception:
pass # column already exists
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_lb_profit ON leaderboard(profit_pct DESC)"
)
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_users_username ON users(username)"
)
conn.commit()
init_db()
# ---------------------------------------------------------------------------
# Session helpers — session stores ONLY mutable state (~300 bytes)
# ---------------------------------------------------------------------------
def _get_sim():
return session.get("sim")
def _save_sim(sim: dict):
session["sim"] = sim
session.modified = True
def _no_cache(response):
"""Add no-cache headers to API responses."""
response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate"
response.headers["Pragma"] = "no-cache"
return response
@app.after_request
def add_security_headers(response):
"""Add security headers to every response."""
# Prevent MIME-type sniffing
response.headers["X-Content-Type-Options"] = "nosniff"
# Prevent clickjacking
response.headers["X-Frame-Options"] = "DENY"
# Don't send Referer header to external sites
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
# Basic XSS protection for older browsers
response.headers["X-XSS-Protection"] = "1; mode=block"
return response
# ---------------------------------------------------------------------------
# Auth gate — redirect to login if no session identity
# ---------------------------------------------------------------------------
# Endpoints exempt from auth check
_AUTH_EXEMPT = {"login", "play_as_guest", "static", "index"}
@app.before_request
def require_auth():
ep = request.endpoint or ""
if ep.startswith("static") or ep in _AUTH_EXEMPT:
return
if ep.startswith("api_"):
return # API endpoints are public (search, stock-info used on login page too)
if not session.get("user_id") and not session.get("guest"):
return redirect(url_for("login"))
# ---------------------------------------------------------------------------
# Auth routes
# ---------------------------------------------------------------------------
@app.route("/login", methods=["GET", "POST"])
@limiter.limit("10 per minute", methods=["POST"])
def login():
"""Handles login, registration, and redirects logged-in users."""
if session.get("user_id") or session.get("guest"):
return redirect(url_for("index"))
mode = request.args.get("mode", "login")
error = None
if request.method == "POST":
mode = request.form.get("mode", "login")
username = request.form.get("username", "").strip()
password = request.form.get("password", "")
if mode == "register":
if not _USERNAME_RE.match(username):
error = "Username must be 3–20 characters: letters, numbers, and _ only."
elif len(password) < 8:
error = "Password must be at least 8 characters."
else:
try:
pw_hash = _hash_password(password)
with get_db() as conn:
conn.execute(
"INSERT INTO users (username, password_hash) VALUES (?, ?)",
(username, pw_hash),
)
conn.commit()
user = conn.execute(
"SELECT id FROM users WHERE username = ?", (username,)
).fetchone()
session["user_id"] = user["id"]
session["username"] = username
return redirect(url_for("index"))
except sqlite3.IntegrityError:
error = "Username already taken."
except Exception as e:
log.error("Register error: %s", e)
error = "Registration failed — please try again."
else: # login
# Identical error for wrong username OR wrong password — no enumeration
with get_db() as conn:
user = conn.execute(
"SELECT id, password_hash FROM users WHERE username = ?",
(username,),
).fetchone()
if not user or not _check_password(password, user["password_hash"]):
error = "Invalid credentials."
else:
session["user_id"] = user["id"]
session["username"] = username
return redirect(url_for("index"))
return render_template("login.html", error=error, mode=mode)
@app.route("/play-as-guest")
def play_as_guest():
"""Sets guest flag and redirects to home."""
session["guest"] = True
return redirect(url_for("index"))
@app.route("/logout")
def logout():
session.clear()
return redirect(url_for("login"))
# ---------------------------------------------------------------------------
# Routes — pages
# ---------------------------------------------------------------------------
@app.route("/")
def index():
featured = []
for scenario in FEATURED_SCENARIOS:
featured.append({
"ticker": scenario["ticker"],
"label": scenario["label"],
"teaser": scenario["teaser"],
"tag": scenario.get("tag", ""),
"name": STOCK_META.get(scenario["ticker"], {}).get("name", scenario["ticker"]),
"logo": LOGO_MAP.get(scenario["ticker"], ""),
})
return render_template("index.html", featured=featured)
@app.route("/setup/<ticker>")
def setup(ticker):
ticker = ticker.upper()
if ticker not in STOCK_META:
return render_template("error.html", message=(
f"'{ticker}' is not in our supported ticker list. "
"Use the search bar on the home page to find a valid stock."
))
info = get_stock_info(ticker)
difficulties = [
{"key": "beginner", "label": "Beginner", "weeks": "12–20", "desc": "More time to recover from mistakes"},
{"key": "intermediate", "label": "Intermediate", "weeks": "8–14", "desc": "The sweet spot of challenge"},
{"key": "expert", "label": "Expert", "weeks": "6–10", "desc": "Fast, brutal, unforgiving"},
]
return render_template("setup.html", stock=info, difficulties=difficulties)
@app.route("/start", methods=["POST"])
def start_simulation():
ticker = request.form.get("ticker", "").upper()
difficulty = request.form.get("difficulty", "intermediate")
if not ticker:
return redirect(url_for("index"))
if ticker not in STOCK_META:
return render_template("error.html", message=(
f"'{ticker}' is not in our supported stock list. "
"Use the search bar to find a valid stock."
))
raw_data = get_ohlcv(ticker)
if not raw_data:
return render_template("error.html", message=(
f"Could not load historical data for {ticker}. "
"Yahoo Finance may be temporarily unavailable — please try again."
))
scenario = pick_scenario(ticker, difficulty)
if not scenario:
return render_template("error.html", message=(
f"Not enough history for {ticker} on {difficulty.title()} difficulty. "
"Try a lower difficulty or a different stock."
))
# Save static scenario data to disk
sid = uuid.uuid4().hex
save_scenario(sid, {
"ticker": ticker,
"difficulty": difficulty,
"dates": scenario["dates"],
"start_price": scenario["start_price"],
"end_price": scenario["end_price"],
"pct_change": scenario["pct_change"],
"briefing": scenario["briefing"],
"real_start_date": scenario["real_start_date"],
"real_end_date": scenario["real_end_date"],
"total_days": scenario["total_days"],
"seed": scenario["seed"],
"start_cash": 10000.0,
})
_save_trades(sid, [])
# Preserve auth identity across session.clear()
user_id = session.get("user_id")
username = session.get("username")
guest = session.get("guest")
session.clear()
if user_id:
session["user_id"] = user_id
session["username"] = username
elif guest:
session["guest"] = True
_save_sim({
"sid": sid,
"day": 0,
"cash": 10000.0,
"shares": 0,
"start_cash": 10000.0,
"avg_cost": 0.0,
})
return redirect(url_for("briefing"))
@app.route("/briefing")
def briefing():
sim = _get_sim()
if not sim:
return redirect(url_for("index"))
sc = load_scenario(sim["sid"])
if not sc:
return redirect(url_for("index"))
stock_info = get_stock_info(sc["ticker"])
return render_template("briefing.html", scenario=sc, sim=sim, stock=stock_info)
@app.route("/simulation")
def simulation():
sim = _get_sim()
if not sim:
return redirect(url_for("index"))
sc = load_scenario(sim["sid"])
if not sc:
return redirect(url_for("index"))
if sim["day"] >= sc["total_days"] - 1 and sim["day"] > 0:
return redirect(url_for("results"))
stock_info = {
"ticker": sc["ticker"],
"name": STOCK_META.get(sc["ticker"], {}).get("name", sc["ticker"]),
"logo": LOGO_MAP.get(sc["ticker"], ""),
}
resp = app.make_response(render_template("simulation.html",
scenario=sc, sim=sim, stock=stock_info))
resp.headers["Cache-Control"] = "no-store, no-cache, must-revalidate"
resp.headers["Pragma"] = "no-cache"
return resp
@app.route("/results")
def results():
sim = _get_sim()
if not sim:
return redirect(url_for("index"))
sc = load_scenario(sim["sid"])
if not sc:
return redirect(url_for("index"))
ticker = sc["ticker"]
data = get_ohlcv(ticker)
dates = sc["dates"]
last_date = dates[-1] if dates else None
last_price = (data[last_date]["close"]
if data and last_date and last_date in data
else sc["end_price"])
final_cash = sim["cash"] + sim["shares"] * last_price
profit = final_cash - sim["start_cash"]
profit_pct = (profit / sim["start_cash"]) * 100
rating = get_performance_rating(profit_pct)
trades = _load_trades(sim["sid"])
full_sc = {"ticker": ticker, "dates": dates,
"data": {d: data[d] for d in dates if d in data} if data else {}}
chart_data = build_chart_data(full_sc, trades)
stock_info = {
"ticker": ticker,
"name": STOCK_META.get(ticker, {}).get("name", ticker),
"logo": LOGO_MAP.get(ticker, ""),
"sector": STOCK_META.get(ticker, {}).get("sector", ""),
}
# Save score — username defaults to "Guest" for unauthenticated users
save_username = session.get("username") or "Guest"
save_user_id = session.get("user_id")
try:
with get_db() as conn:
conn.execute(
"""INSERT INTO leaderboard
(ticker, difficulty, start_cash, final_value, profit_pct,
trades_count, real_start, real_end, user_id, username)
VALUES (?,?,?,?,?,?,?,?,?,?)""",
(ticker, sc["difficulty"], sim["start_cash"],
round(final_cash, 2), round(profit_pct, 2),
len(trades), sc["real_start_date"], sc["real_end_date"],
save_user_id, save_username),
)
conn.commit()
except Exception:
pass
leaderboard = []
try:
with get_db() as conn:
rows = conn.execute(
"SELECT id, ticker, difficulty, start_cash, final_value, profit_pct, trades_count, real_start, real_end, created_at, username FROM leaderboard ORDER BY profit_pct DESC LIMIT 10"
).fetchall()
leaderboard = [dict(r) for r in rows]
except Exception:
pass
sim_ctx = dict(sim)
sim_ctx["trades"] = trades
return render_template(
"results.html",
scenario=sc,
sim=sim_ctx,
stock=stock_info,
final_cash=round(final_cash, 2),
profit=round(profit, 2),
profit_pct=round(profit_pct, 2),
rating=rating,
chart_data=json.dumps(chart_data),
leaderboard=leaderboard,
last_price=round(last_price, 2),
)
# ---------------------------------------------------------------------------
# Routes — API
# ---------------------------------------------------------------------------
@app.route("/api/search")
def api_search():
q = request.args.get("q", "").strip()
if not q:
return _no_cache(jsonify([]))
return _no_cache(jsonify(search_ticker(q)))
@app.route("/api/stock-info/<ticker>")
def api_stock_info(ticker):
ticker = ticker.upper()
# Restrict to curated universe — prevents outbound yfinance calls for arbitrary tickers
if ticker not in STOCK_META:
return _no_cache(jsonify({"error": "Ticker not found"})), 404
info = get_stock_info(ticker)
return _no_cache(jsonify(info))
@app.route("/api/scenario/state")
def api_scenario_state():
sim = _get_sim()
if not sim:
return _no_cache(jsonify({"error": "No active scenario"})), 400
# One-time migration: move trades from old session-cookie format to disk
if "trades" in sim:
existing = _load_trades(sim["sid"])
if not existing:
_save_trades(sim["sid"], sim["trades"])
sim.pop("trades")
_save_sim(sim)
sc = load_scenario(sim["sid"])
if not sc:
return _no_cache(jsonify({"error": "Scenario data missing"})), 400
data = get_ohlcv(sc["ticker"])
if not data:
return _no_cache(jsonify({"error": "Price data unavailable"})), 500
current_day = sim["day"]
total_days = sc["total_days"]
dates = sc["dates"]
visible_dates = dates[: current_day + 1]
candles = []
for d in visible_dates:
if d in data:
candles.append({
"date": d,
"open": data[d]["open"],
"high": data[d]["high"],
"low": data[d]["low"],
"close": data[d]["close"],
"volume": data[d]["volume"],
})
current_price = candles[-1]["close"] if candles else sc["start_price"]
prev_price = candles[-2]["close"] if len(candles) > 1 else current_price
day_change_pct = ((current_price - prev_price) / prev_price * 100) if prev_price else 0
portfolio_value = sim["cash"] + sim["shares"] * current_price
unrealized_pnl = sim["shares"] * (current_price - sim.get("avg_cost", 0))
total_pnl = portfolio_value - sim["start_cash"]
trades = _load_trades(sim["sid"])
return _no_cache(jsonify({
"current_day": current_day,
"total_days": total_days,
"week_num": current_day // 5 + 1,
"day_in_week": current_day % 5 + 1,
"current_price": round(current_price, 4),
"day_change_pct": round(day_change_pct, 2),
"cash": round(sim["cash"], 2),
"shares": sim["shares"],
"portfolio_value": round(portfolio_value, 2),
"unrealized_pnl": round(unrealized_pnl, 2),
"total_pnl": round(total_pnl, 2),
"candles": candles,
"trades": trades,
"finished": current_day >= total_days - 1 and current_day > 0,
}))
@app.route("/api/scenario/advance", methods=["POST"])
def api_advance():
sim = _get_sim()
if not sim:
return _no_cache(jsonify({"error": "No active scenario"})), 400
sc = load_scenario(sim["sid"])
if not sc:
return _no_cache(jsonify({"error": "Scenario missing"})), 400
n = 1
if request.is_json:
try:
n = max(1, int(request.json.get("days", 1)))
except (ValueError, TypeError):
return _no_cache(jsonify({"error": "days must be an integer"})), 400
old_day = sim["day"]
new_day = min(old_day + n, sc["total_days"] - 1)
if new_day != old_day:
sim["day"] = new_day
_save_sim(sim)
return _no_cache(jsonify({
"current_day": sim["day"],
"total_days": sc["total_days"],
}))
@app.route("/api/scenario/trade", methods=["POST"])
def api_trade():
sim = _get_sim()
if not sim:
return _no_cache(jsonify({"error": "No active scenario"})), 400
sc = load_scenario(sim["sid"])
if not sc:
return _no_cache(jsonify({"error": "Scenario missing"})), 400
body = request.get_json() or {}
action = body.get("action")
dollar_amount = body.get("dollar_amount")
try:
shares = int(body.get("shares", 0))
except (ValueError, TypeError):
return _no_cache(jsonify({"error": "shares must be an integer"})), 400
data = get_ohlcv(sc["ticker"])
if not data:
return _no_cache(jsonify({"error": "Price data unavailable"})), 500
current_day = sim["day"]
dates = sc["dates"]
if current_day >= len(dates):
return _no_cache(jsonify({"error": "Simulation ended"})), 400
current_price = data[dates[current_day]]["close"]
if dollar_amount:
try:
dollar_float = float(dollar_amount)
except (ValueError, TypeError):
return _no_cache(jsonify({"error": "dollar_amount must be a number"})), 400
if dollar_float > 0:
shares = int(dollar_float / current_price)
if shares <= 0:
return _no_cache(jsonify({"error": "Enter at least 1 share"})), 400
day_label = f"Week {current_day // 5 + 1}, Day {current_day % 5 + 1}"
if action == "buy":
cost = shares * current_price
if cost > sim["cash"] + 0.001:
max_shares = int(sim["cash"] / current_price)
return _no_cache(jsonify({
"error": f"Need ${cost:,.2f} — only ${sim['cash']:,.2f} available. Max: {max_shares} shares."
})), 400
sim["cash"] -= cost
sim["shares"] += shares
trade = {"action": "buy", "shares": shares,
"price": round(current_price, 4), "total": round(cost, 2),
"day_index": current_day, "day_label": day_label}
elif action == "sell":
if shares > sim["shares"]:
return _no_cache(jsonify({
"error": f"You only own {sim['shares']} shares."
})), 400
proceeds = shares * current_price
sim["cash"] += proceeds
sim["shares"] -= shares
trade = {"action": "sell", "shares": shares,
"price": round(current_price, 4), "total": round(proceeds, 2),
"day_index": current_day, "day_label": day_label}
else:
return _no_cache(jsonify({"error": "Invalid action"})), 400
trades = _load_trades(sim["sid"])
trades.append(trade)
_save_trades(sim["sid"], trades)
sim["avg_cost"] = _avg_cost(trades)
_save_sim(sim)
portfolio_value = sim["cash"] + sim["shares"] * current_price
return _no_cache(jsonify({
"success": True,
"trade": trade,
"cash": round(sim["cash"], 2),
"shares": sim["shares"],
"portfolio_value": round(portfolio_value, 2),
}))
@app.route("/api/leaderboard")
def api_leaderboard():
try:
with get_db() as conn:
rows = conn.execute(
"SELECT id, ticker, difficulty, start_cash, final_value, profit_pct, trades_count, real_start, real_end, created_at, username FROM leaderboard ORDER BY profit_pct DESC LIMIT 10"
).fetchall()
return _no_cache(jsonify([dict(r) for r in rows]))
except Exception:
return _no_cache(jsonify([]))
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _avg_cost(trades: list) -> float:
total_cost, total_shares = 0.0, 0
for t in trades:
if t["action"] == "buy":
total_cost += t["total"]
total_shares += t["shares"]
elif t["action"] == "sell" and total_shares > 0:
avg = total_cost / total_shares
total_cost -= avg * t["shares"]
total_shares -= t["shares"]
return (total_cost / total_shares) if total_shares > 0 else 0.0
if __name__ == "__main__":
# Debug mode exposes the Werkzeug interactive debugger — NEVER enable in production.
# Set FLASK_DEBUG=1 only in local development environments.
debug = os.environ.get("FLASK_DEBUG", "") == "1"
port = int(os.environ.get("PORT", 5000))
print(f"Starting StockReplay on http://localhost:{port} (debug={debug})")
app.run(debug=debug, port=port, host="0.0.0.0")