Files
YoteInvest/tests/test_demo.py
T
2026-11-17 20:07:31 +01:00

144 lines
6.4 KiB
Python

"""Demo mode: real-data path with Yahoo responses replayed offline, plus the simulator."""
import random
import pytest
from app import demo, main, marketdata, sentiment
from app.sentiment import Verdict
from tests.test_bot import reset # noqa: F401 (shared fixture: clean account, mocked news)
def yahoo_json(candles, currency="USD"):
"""Build a response in Yahoo's chart format, including a null gap like the real API."""
ts = [c[0] for c in candles]
q = {k: [c[i] for c in candles] for i, k in enumerate(["_", "open", "high", "low", "close", "volume"]) if k != "_"}
q["close"][3] = None
return {"chart": {"result": [{"meta": {"currency": currency}, "timestamp": ts,
"indicators": {"quote": [q]}}], "error": None}}
def trending_candles(n, start_ts=1_700_000_000, seed=1):
rng, p, out = random.Random(seed), 100.0, []
for i in range(n):
drift = 0.004 if (i // 60) % 2 else -0.003 # alternating down/up phases
o, p = p, p * (1 + drift + rng.gauss(0, 0.004))
v = 1000 * (3 if rng.random() < 0.3 else 1)
out.append((start_ts + i * 3600, o, max(o, p) * 1.002, min(o, p) * 0.998, p, v))
return out
def test_parse_chart_skips_gaps_and_open_candle():
c = trending_candles(10)
candles, cur = marketdata.parse_chart(yahoo_json(c, "EUR"), "1h", now=c[-1][0] + 1800)
assert cur == "EUR"
assert len(candles) == 8 # one null close dropped, last candle not closed yet
assert candles[0].close == pytest.approx(c[0][4])
def test_parse_chart_error():
with pytest.raises(ValueError):
marketdata.parse_chart({"chart": {"result": None, "error": {"code": "Not Found"}}}, "1h")
def test_real_mode_trades_on_new_candles_only():
full = trending_candles(400)
shown = {"n": 120}
def fetch(sym):
data = yahoo_json(full[: shown["n"]], "EUR" if sym.endswith(".AS") else "USD")
return marketdata.parse_chart(data, "1h", now=10**12)
sim = demo.Simulator(main.process, main.paper.mark, mode="real", fetch=fetch, fx=lambda: {"USD": 1.08, "GBP": 0.86})
before = len(main.store.events(10000))
sim.run_once(main.paper.equity, main._held)
assert len(main.store.events(10000)) == before # first load only warms up indicators
assert sim.series["ASML"].currency == "EUR" and sim.series["NVDA"].currency == "USD"
for n in range(121, 400, 5): # candles arrive over time
shown["n"] = n
sim.run_once(main.paper.equity, main._held)
ev = main.store.events(10000)[: len(main.store.events(10000)) - before]
assert any(e["decision"] == "executed" and e["action"] == "buy" for e in ev)
# US-dollar prices are converted to euros before reaching the fake account
nvda = [e for e in ev if e["symbol"] == "NVDA"]
if nvda:
assert nvda[0]["price"] < max(c[4] for c in full)
def test_real_mode_survives_feed_errors():
def broken(sym):
raise ConnectionError("rate limited")
sim = demo.Simulator(main.process, main.paper.mark, mode="real", fetch=broken, fx=lambda: {})
sim.run_once(main.paper.equity, main._held)
assert "rate limited" in sim.series["BTCUSD"].error
assert sim.rates["USD"] == pytest.approx(1.10) # falls back to the configured rate
assert all("error" in p for p in sim.prices())
def test_simulated_mode_runs_and_trades():
sim = demo.Simulator(main.process, main.paper.mark, mode="simulated", seed=7)
for _ in range(400):
sim.run_once(main.paper.equity, main._held)
assert len(main.store.events(1000)) > 5
assert len(sim.equity_history) == 400
def test_keyword_sentiment():
up = ["x | ASML shares surge after record profit, analysts upgrade",
"x | ASML beats estimates, raises growth outlook"]
assert sentiment.keyword_verdict(up).sentiment == "bullish"
down = ["x | Adyen plunges on weak volume, downgrade follows",
"x | Adyen shares fall as analysts cut targets amid probe"]
v = sentiment.keyword_verdict(down)
assert v.sentiment == "bearish" and v.confidence <= 0.75
assert sentiment.keyword_verdict(["x | Bitcoin trades sideways"]).sentiment == "neutral"
def test_health_panel_data():
from tests.helpers import wave
from app import demo, main
import time as _t
recent = _t.time() - 700 * 3600
def fetch(sym):
if sym == "SPY":
raise ConnectionError("rate limited")
return wave(700, start=int(recent), step=3600), "USD"
sim = demo.Simulator(main.process, main.paper.mark, mode="real", fetch=fetch, fx=lambda: {"USD": 1.1, "GBP": 0.87})
sim.run_once()
h = sim.health()
rows = {r["symbol"]: r for r in h["markets"]}
from app.config import INSTRUMENTS
assert h["total"] == len(INSTRUMENTS) and h["feed_ok"] == len(INSTRUMENTS) - 1 and h["updates"] == 1
assert rows["SPY"]["feed"] == "error" and "rate limited" in rows["SPY"]["note"]
assert rows["ASML"]["feed"] == "ok" and len(rows["ASML"]["checks"]) == 5
assert h["next_check"] > h["last_check"]
assert all(c["symbol"] != "SPY" for c in h["closest"])
fresh = demo.Simulator(main.process, main.paper.mark, mode="real", fetch=fetch, fx=lambda: {})
assert fresh.health()["markets"][0]["feed"] == "waiting" and fresh.health()["last_check"] is None
def test_health_flags_a_feed_that_stopped_while_the_exchange_is_open():
from tests.helpers import wave
from app import demo, main
sim = demo.Simulator(main.process, main.paper.mark, mode="real",
fetch=lambda sym: (wave(700), "USD"), fx=lambda: {}) # candles from 2017
sim.run_once()
rows = {r["symbol"]: r for r in sim.health()["markets"]}
assert rows["BTCUSD"]["feed"] == "stale" # crypto is always open, so old candles are a problem
def test_parse_chart_waits_for_volume_that_yahoo_has_not_filled_in_yet():
c = trending_candles(10)
c[-2] = c[-2][:5] + (0,) # last two closed candles: volume 0 for now
c[-3] = c[-3][:5] + (None,)
done = c[:-1] + [c[-1][:5] + (0,)]
candles, _ = marketdata.parse_chart(yahoo_json(done), "1h", now=c[-1][0] + 7200)
assert candles[-1].ts == c[-4][0] and all(x.volume > 0 for x in candles[-2:])
# a market that never reports volume keeps its candles
none = [x[:5] + (0,) for x in trending_candles(10)]
kept, _ = marketdata.parse_chart(yahoo_json(none), "1h", now=none[-1][0] + 7200)
assert len(kept) == 9