Skip to content

About

Hackathon !

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

PSX Signal Lab

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.

Architecture

  • frontend/ — Next.js 14 + React + TypeScript + Tailwind. Builds to a static export (frontend/out) via output: '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.py reads the SQLite DB (data/psx_signal_lab.db) when present; fixture_repo.py falls back to fixtures/*.json per 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 only openapi.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 seed works fully offline and seeds the same DB tables from the verified CSV + fixture signal snapshot (clearly labeled fixture_backfill in metrics_json). On any machine where sklearn imports, python -m scripts.seed_demo replaces it with a genuine trained run automatically.

Setup (3 commands)

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:8090

Open http://localhost:8090 — the UI and API are the same origin; the browser never calls a second port.

Development (hot reload)

npm run dev       # FastAPI on :8090 + Next.js dev server on :3000

In dev, Next.js rewrites proxy /api/* → http://localhost:8090, so the browser still only talks to :3000 (no CORS issues).

Other commands

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

Real model training (requires working sklearn)

python -m scripts.seed_demo   # ingest CSV + walk-forward train + persist run

Needs scikit-learn, pandas, joblib importable (blocked by Windows Application Control on some machines) and optionally yfinance + --source live for fresh Yahoo Finance PSX data.

Environment variables

See .env.example (names only). All are optional — defaults work out of the box:

  • PORT — production listen port (default 8090)
  • API_PORT — dev API port / Next.js rewrite target (default 8090)
  • API_ALLOWED_ORIGIN — CORS origin for dev (http://localhost:3000)
  • NEXT_PUBLIC_API_BASE_URL — optional API override; leave empty to use relative /api paths
  • DEFAULT_WATCHLIST_SYMBOLS — comma-separated PSX symbols

Demo

  1. npm run setup && npm run build && npm start
  2. Open http://localhost:8090 — pick a symbol (e.g. OGDC) from the watchlist.
  3. The chart loads delayed daily candles; the signal panel shows direction + calibrated probability.
  4. npm run smoke verifies health, the model endpoint, and the UI in one shot.

Deploy (one unit)

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 command npm start (or node scripts/start.js). Set PORT — 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.

Data Source & Delay Policy

  • Primary source: yfinance_psx_delayed_daily (.KA tickers 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).

Modeling Rules & Methodology

  • Target & Zero-Return Tie Rule: Binary directional target y_t = 1 if close[t+h] / close[t] - 1 > 0 else 0 (default h = 1). Exact zero-return ties (close[t+h] == close[t]) map to class 0 (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.55 likely_up, <= 0.45 likely_down, else no_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_rate is returned as null alongside past_signal_count and history_note ("not enough history").
  • Persisted Artifacts: Fitted estimators, StandardScaler instances, and temporal Platt calibrators are serialized to data/processed/fitted_models.joblib, with SHA-256 checksums, split bounds, and metrics saved to data/processed/ml_artifacts.json and SQLite.

Demo FAQ & Honest Limitations

  • 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.

About

Hackathon !

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages