Educational directional signal estimator and walk-forward backtesting lab for 15 liquid Pakistan Stock Exchange (PSX / KSE-100) equities — shipped as one web app: a single command installs it, a single command runs it, and everything (UI + API + signals) is served from one URL on one port.
Disclaimer: PSX Signal Lab provides delayed daily statistical estimates for educational and research purposes only. Signals indicate directional likelihood (
likely_up,likely_down,no_clear_direction) and never promise profit or constitute investment advice.
frontend/— Next.js 14 + React + TypeScript + Tailwind. Builds to a static export (frontend/out) viaoutput: 'export'.backend/— Python FastAPI (app.main:app). Serves/api/v1/*and the static frontend on the same port.backend/app/repositories/— data layer:live_repo.pyreads the SQLite DB (data/psx_signal_lab.db) when present;fixture_repo.pyfalls back tofixtures/*.jsonper domain (market data vs signals). No pandas/sklearn needed at request time.backend/{data,models,db,features,backtest}+scripts/— offline ingest/training pipeline (backend.*imports; run from repo root).contracts/— contains onlyopenapi.json; no smart contracts in this repo.psx-signal-lab/— legacy nested clone of this project; ignore it.ECC/— unrelated third-party tooling; ignore it.
There are no external LLM/AI API calls — "model" inference is the local sklearn walk-forward pipeline; no API keys are needed and MOCK_LLM does not apply.
Note on this machine: Windows Application Control blocks scipy/sklearn native DLLs, so
scripts.seed_demo(real training) cannot run here.npm run seedworks fully offline and seeds the same DB tables from the verified CSV + fixture signal snapshot (clearly labeledfixture_backfillinmetrics_json). On any machine where sklearn imports,python -m scripts.seed_demoreplaces it with a genuine trained run automatically.
npm run setup # python venv + pip install + npm install (frontend)
npm run seed # offline: ingest CSV -> SQLite + backfill signal snapshot (no sklearn needed)
npm run build # static-export the frontend into frontend/out
npm start # one process, one port → http://localhost:8090Open http://localhost:8090 — the UI and API are the same origin; the browser never calls a second port.
npm run dev # FastAPI on :8090 + Next.js dev server on :3000In dev, Next.js rewrites proxy /api/* → http://localhost:8090, so the browser still only talks to :3000 (no CORS issues).
| Command | What it does |
|---|---|
npm run build |
next build → static export to frontend/out |
npm start |
Production server (PORT env, default 8090) |
npm run smoke |
Checks UI, /api/v1/health, and the signal endpoint |
npm run seed |
Offline DB seed (ingest + fixture signal backfill) |
npm test |
Backend pytest (26 tests) + frontend vitest (42 tests) |
npm run dev:reload |
Dev with uvicorn --reload |
python -m scripts.seed_demo # ingest CSV + walk-forward train + persist runNeeds scikit-learn, pandas, joblib importable (blocked by Windows Application Control on some machines) and optionally yfinance + --source live for fresh Yahoo Finance PSX data.
See .env.example (names only). All are optional — defaults work out of the box:
PORT— production listen port (default8090)API_PORT— dev API port / Next.js rewrite target (default8090)API_ALLOWED_ORIGIN— CORS origin for dev (http://localhost:3000)NEXT_PUBLIC_API_BASE_URL— optional API override; leave empty to use relative/apipathsDEFAULT_WATCHLIST_SYMBOLS— comma-separated PSX symbols
npm run setup && npm run build && npm start- Open http://localhost:8090 — pick a symbol (e.g. OGDC) from the watchlist.
- The chart loads delayed daily candles; the signal panel shows direction + calibrated probability.
npm run smokeverifies health, the model endpoint, and the UI in one shot.
The production artifact is a single Python process serving static files + API — deployable on any Python host:
- Railway / Render: build command
npm run setup && npm run build, start commandnpm start(ornode scripts/start.js). SetPORT— the platform injects it automatically. No external services, DB, or secrets required. - Vercel/Netlify are not a fit — the API is Python, not serverless JS.
- Render alternative: use
backend/requirements.txt+ a build step for the frontend, or the root scripts above which handle both.
- Primary source:
yfinance_psx_delayed_daily(.KAtickers on Yahoo Finance) with automatic split-discontinuity repair and zero-volume holiday/halt filtering. - Offline fallback:
data/fixtures/psx_fallback.csv(verified delayed daily OHLCV snapshot for all 15 watchlist symbols). - Current verified snapshot (
data_as_of):2026-11-26(missing dates represent PSX non-trading days and are never forward-filled).
- Target & Zero-Return Tie Rule: Binary directional target
y_t = 1ifclose[t+h] / close[t] - 1 > 0else0(defaulth = 1). Exact zero-return ties (close[t+h] == close[t]) map to class0(not up / DOWN) consistently across training, calibration, and resolution. - Symbol Modeling Scope: Each of the 15 PSX symbols is trained as an independent per-symbol model with 35 strictly causal features (27 technical/volume/calendar + 8 equal-weight PSX universe relative strength/beta/breadth features), so symbol one-hot encoding is not required.
- Chronological Splits & Calibration: Purged expanding walk-forward CV with strict ordering
max(train_date) < min(cal_date) <= max(cal_date) < min(test_date), temporal Platt sigmoid calibration, and fixed direction thresholds (>= 0.55likely_up,<= 0.45likely_down, elseno_clear_direction). - Minimum History Rule (< 30 Resolved Signals): In
/api/v1/signals, if a symbol has fewer than 30 resolved out-of-sample directional signals,past_hit_rateis returned asnullalongsidepast_signal_countandhistory_note("not enough history"). - Persisted Artifacts: Fitted estimators,
StandardScalerinstances, and temporal Platt calibrators are serialized todata/processed/fitted_models.joblib, with SHA-256 checksums, split bounds, and metrics saved todata/processed/ml_artifacts.jsonand SQLite.
- Q: Is this profitable / should I trade on these signals? A: No. PSX Signal Lab is an educational statistical modeling tool, not a profitable trading strategy or investment advisor. Daily equity returns have a low signal-to-noise ratio (typical out-of-sample ROC-AUC ~0.49–0.55), and historical backtests exclude real-world slippage, market impact, liquidity limits, and sudden macro/corporate events.