Vantage Psx
    Vantage PSX
About the Project
Vantage PSX (engineered with precision by Agnific) is an enterprise-grade real-time market intelligence, technical telemetry, and algorithmic signal platform designed for the Pakistan Stock Exchange (PSX).
Tracking all 736 listed equities, Vantage PSX combines low-latency WebSocket price feeds, multi-horizon technical indicators, corporate event calendar tracking, algorithmic trade callouts, walk-forward backtest expectancy telemetry, and news sentiment scoring into an ultra-fast Dark Bento UI terminal.
ð Core Features
- Live Market Telemetry & Ticker Tape: Real-time tracking of PSX benchmarks (KSE-100, KSE-30, KMI-30), session turnover, advancing/declining market breadth, top gainers/losers/active volume leaders, and market status.
- Multi-Horizon Algorithmic Signals: Automated, mathematical evaluation classifying equities as Bullish, Bearish, or Neutral across Intraday, Swing, and Long-term timeframes.
- Algorithmic Trade Alerts Feed (
/alerts): Real-time actionable callouts triggered on genuine score threshold crossings ($\pm 30.0$) with ATR-based reference entries, stop losses ($1.5 \times \text{ATR}$), targets ($3.0 \times \text{ATR}$), and 1:2 R:R ratios. - Walk-Forward Backtesting & Expectancy Telemetry: Strictly causal, zero look-ahead backtest engine measuring universe win rates, average R-multiples, profit factors, and statistical expectancy.
- Interactive Candlestick Charts: Self-hosted TradingView Lightweight Charts with dynamic period zoom (
1M,3M,6M,1Y), volume histograms, and responsive crosshairs. - Advanced Stock Screener (
/screener): Dual-dropdown horizon-specific signal filtering (Intraday / Swing / Long-term + Bullish / Neutral / Bearish), live text search, and click-to-sort headers. - Corporate Calendar & News Hub (
/news): Multi-source financial RSS feed (Dawn Business, Business Recorder, Mettis Global) with automated ticker NLP sentiment scoring, weekly navigation, upcoming event pinning, and direct DPS filing links. - Portfolio Watchlist (
/watchlist): Client-persisted watchlist with categorical signal strength and numeric metrics sorting. - Quick Command Palette (
Ctrl + K//): Instant modal search across all 736 PSX stocks and terminal pages. - Adaptive Dark & Light Theme System: Obsidian telemetry dark mode and clean Apple/Linear FinTech light mode with instant, zero-flicker
localStoragepersistence.
ð¬ Algorithmic Signal Evaluation Engine
Vantage PSX features an explainable, multi-factor quantitative engine (app/services/signal_engine.py) that evaluates each stock across five core analytical categories: Trend, Momentum, Volatility, Volume, and Sentiment.
1. Multi-Horizon Timeframes
The engine computes independent composite scores for three distinct investment horizons:
| Horizon | Primary Focus | Holding Period | |---|---|---| | Intraday | Order flow velocity, volume spikes, oscillator momentum | Minutes to 5 Trading Days | | Swing | Moving average crossovers, channel breakouts, recent news | 2 Weeks to 1 Month (20 Days) | | Long-Term | 200 EMA structural trend, dividend yield, corporate filings | 1 to 3 Months (60 Days) |
2. Category Weight Matrix
Each horizon weights the 5 indicator categories based on timeframe sensitivity:
$$\text{Composite Score} = \sum_{c \in \text{Categories}} w_{c} \times S_{c}$$
âââââââââââââââââââ¬ââââââââââââ¬ââââââââââââ¬ââââââââââââââ
â Category â Intraday â Swing â Long-term â
âââââââââââââââââââ¼ââââââââââââ¼ââââââââââââ¼ââââââââââââââ¤
â Trend â 35% â 30% â 40% â
â Momentum â 40% â 25% â 15% â
â Volatility â 20% â 15% â 10% â
â Volume â 25% â 15% â 10% â
â News Sentiment â 10% â 15% â 25% â
âââââââââââââââââââ´ââââââââââââ´ââââââââââââ´ââââââââââââââ
3. Indicator Formulas & Scoring Logic
A. Trend Scoring (Weight: 30% â 40%)
- EMA 9 / EMA 21 Crossover:
- $\text{EMA}9 > \text{EMA}{21} \rightarrow \min\left(\frac{\text{EMA}9 - \text{EMA}{21}}{\text{EMA}_{21}} \times 1000, 80\right)$ [Bullish short-term trend].
- $\text{EMA}9 < \text{EMA}{21} \rightarrow \max\left(\frac{\text{EMA}9 - \text{EMA}{21}}{\text{EMA}_{21}} \times 1000, -80\right)$ [Bearish short-term trend].
- EMA 50 / EMA 200 Golden & Death Cross:
- $\text{EMA}{50} > \text{EMA}{200} \rightarrow +70$ (Golden Cross structural regime).
- $\text{EMA}{50} < \text{EMA}{200} \rightarrow -70$ (Death Cross structural regime).
- Price vs. 200 EMA Distance:
- Price $> +5%$ above 200 EMA $\rightarrow \min(\text{Dist} \times 3, 60)$ [Bullish].
- Price $< -5%$ below 200 EMA $\rightarrow \max(\text{Dist} \times 3, -60)$ [Bearish].
B. Momentum Scoring (Weight: 15% â 40%)
- Relative Strength Index (RSI 14):
- $\text{RSI} > 70$: Overbought expansion $\rightarrow \min(40 + (\text{RSI} - 70) \times 2, 80)$.
- $\text{RSI} < 30$: Oversold contraction $\rightarrow -\min(40 + (30 - \text{RSI}) \times 2, 80)$.
- $30 \le \text{RSI} \le 70$: Equilibrium momentum $\rightarrow (\text{RSI} - 50) \times 1.5$.
- Moving Average Convergence Divergence (MACD 12, 26, 9):
- Base score from MACD line sign ($\pm 25$), Signal line crossover ($\pm 25$), and Histogram expansion ($\pm 30$).
C. Volatility Scoring (Weight: 10% â 20%)
- Bollinger Bands (20, 2.0 $\sigma$) Position %B:
- $%B > 0.90$ with $\Delta P \ge 0 \rightarrow +40$ to $+70$ (Volatility breakout).
- $%B < 0.10$ with $\Delta P \le 0 \rightarrow -40$ to $-70$ (Downside volatility expansion).
- Average True Range (ATR 14 Percentile):
- Measures volatility expansion vs 14-session historical percentile rank.
D. Volume Scoring (Weight: 10% â 25%)
- Relative Volume (RVOL = $\frac{\text{Current Volume}}{\text{20-Day SMA Volume}}$):
- $\text{RVOL} > 1.0\times$ with $\Delta P > 0 \rightarrow \min(\text{RVOL} \times 20, 60)$ (Institutional accumulation).
- $\text{RVOL} > 1.0\times$ with $\Delta P < 0 \rightarrow -\min(\text{RVOL} \times 20, 60)$ (Institutional distribution).
E. News & Corporate Sentiment Isolation (Weight: 10% â 25%)
- Ticker-Isolated Sentiment: The engine queries news articles mentioning the target ticker or its sector. If no company-specific disclosures exist, sentiment is neutral ($0.0$), preventing unrelated market news from distorting technical scores.
- Recency Decay Weighting: Newer announcements carry exponential weighting ($w_i = \frac{1}{i + 1}$).
4. Classification Thresholds & Signal Direction
The composite score $S \in [-100.0, +100.0]$ maps to:
| Composite Score ($S$) | Signal Direction | Strategy & Interpretation | |---|---|---| | $S \ge +30.0$ | BULLISH | Technical structure, momentum expansion, and sentiment align upward. | | $S \le -30.0$ | BEARISH | Distribution, momentum breakdown, and negative news indicate downside risk. | | $-30.0 < S < +30.0$ | NEUTRAL | Balanced equilibrium or range-bound consolidation. |
ð Algorithmic Trade Alerts & Backtest Engine
Vantage PSX includes a production-grade algorithmic trade alert and walk-forward backtesting system (app/services/backtest_engine.py):
1. Zero Look-Ahead Bias Guarantee
At every historical session $t$, technical scores are computed strictly from data available up to $t$ (history[:t+1]). Spiking or modifying future prices $t+1 \dots N$ causes zero change in historical signal scores at step $t$.
2. Standardized ATR Reference Ruleset (1:2 R:R)
- Reference Entry: Close price $P$ at trigger session $t$.
- Stop Loss: $P - 1.5 \times \text{ATR}(14)$ ($1.0\text{R}$ risk).
- Target Price: $P + 3.0 \times \text{ATR}(14)$ ($+2.0\text{R}$ reward).
- Outcomes:
WIN: Target price reached first ($+2.0\text{R}$).LOSS: Stop loss breached first ($-1.0\text{R}$).EXPIRED: Max holding window elapses before either target or stop loss is reached (exited at bar close; tracked separately).
3. Empirical Results on PSX Historical Data (1,409 Setups across 42 Scrips)
| Horizon | Max Holding | Total Setups | Wins ($+2.0\text{R}$) | Losses ($-1.0\text{R}$) | Expired | Win Rate (Resolved) | Expectancy ($E$) | Profit Factor | | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | | Intraday | 5 bars | 620 | 126 | 161 | 333 | 43.9% | $+0.20\text{R}$ | 1.55x | | Swing | 20 bars | 444 | 172 | 227 | 45 | 43.1% | $+0.27\text{R}$ | 1.52x | | Long-Term | 60 bars | 345 | 135 | 202 | 8 | 40.1% | $+0.20\text{R}$ | 1.34x |
[!NOTE] Because the ATR setup targets a 1 : 2.0 Risk-to-Reward ratio, the mathematical breakeven threshold is only 33.3%. Achieving 40.1%â43.9% win rate yields consistent positive statistical expectancy ($+0.20\text{R}$ to $+0.27\text{R}$ per setup).
ðï¸ System Architecture
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â VANTAGE PSX TERMINAL â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¤
â Frontend Layer: â
â ⢠Jinja2 Server-Rendered HTML Templates (Zero-build pipeline) â
â ⢠HTMX 2.0 (Dynamic partial updates, sorting, and live polling) â
â ⢠Alpine.js 3.x (Reactive UI state, command palette, sort comparators)â
â ⢠TradingView Lightweight Charts (Standalone, self-hosted canvas) â
â ⢠Tailwind CSS Design System (Dark & Light tokens) â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¤
â Backend Services: â
â ⢠FastAPI (High-performance async Python web framework) â
â ⢠Signal Engine (Multi-horizon mathematical scoring) â
â ⢠Backtest Engine (Vectorized walk-forward simulation & telemetry) â
â ⢠Alert Service (Score boundary transition detection & reference LVLs)â
â ⢠News & Calendar Service (RSS parser & NLP polarity scorer) â
â ⢠In-Process APScheduler (Quotes 15s, Signals 2m, News 5m, Backtest) â
â ⢠WebSocket Server (`/ws/quotes` real-time price broadcast) â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¤
â Data Layer: â
â ⢠PSXData Adapter (Live direct PSX exchange scraper for 736 stocks) â
â ⢠SQLite / PostgreSQL Database (Price history, signals, alerts, news)â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
ð Quick Start
1. Prerequisites
- Python 3.10+
- Virtual environment tool (
venvorconda)
2. Installation & Setup
# Clone repository git clone https://github.com/agnific/vantage-psx.git cd vantage-psx # Create and activate virtual environment python -m venv venv # On Windows: .\venv\Scripts\activate # On Linux/macOS: source venv/bin/activate # Install dependencies pip install -r requirements.txt
3. Launch Terminal
uvicorn app.main:app --reload --port 8000
Open your browser at http://localhost:8000.
[!TIP] No
npm installor separate frontend build step required! All static dependencies (TradingView charts, Lucide SVG icons, Tailwind, Alpine, HTMX) run instantly out of the box.
ðºï¸ Route Sitemap & API Reference
Page Views (HTML)
/â Market Overview Dashboard (Indices, Breadth, Gainers/Losers/Active, Sector Breakdown, News)/screenerâ Stock Screener (Filter by Horizon + Signal, type-safe click-to-sort across all columns)/alertsâ Algorithmic Trade Alerts (Edge Telemetry Card, ATR reference levels, Scrip Backtest badges)/newsâ News Hub & Corporate Calendar (Weekly timeline, daily pagination, upcoming events, DPS links)/stock/{symbol}â Stock Detail (TradingView Candlestick Chart, multi-horizon indicator breakdown, filings)/watchlistâ Portfolio Watchlist (Multi-horizon signal sorting, LTP/Change/Volume metrics)/settingsâ Terminal Settings & System Telemetry
REST API & WebSocket
GET /api/quotesâ Fetch JSON snapshot of all 736 active PSX quotesGET /api/quotes/{symbol}â Fetch real-time telemetry for a single tickerGET /api/history/{symbol}â Fetch daily OHLCV candlestick historical seriesGET /api/signals/{symbol}â Fetch Intraday, Swing, and Long-term signal resultsGET /api/newsâ Fetch aggregated news and corporate calendar disclosuresGET /api/system/healthâ Terminal health and memory telemetryWS /ws/quotesâ Live real-time WebSocket price stream
âï¸ Configuration (.env)
# Environment APP_NAME=Vantage PSX APP_ENV=production DEBUG=false # Data Provider (psxdata | mock | eodhd | capitalstake) DATA_PROVIDER=psxdata # Database DATABASE_URL=sqlite:///./psx_vantage.db # SQL Debug Logging (false = quiet, clean console; true = verbose query echo) SQL_DEBUG=false # Feature Flags TRADE_ALERTS_ENABLED=true # Polling Intervals (seconds) QUOTE_POLL_INTERVAL=15 NEWS_POLL_INTERVAL=300 SIGNAL_RECOMPUTE_INTERVAL=120
ð¡ï¸ Regulatory Notice & Disclaimer
This software provides market intelligence, algorithmic technical signals, backtested performance simulations, and corporate disclosures for informational and quantitative research purposes only. It does not constitute financial advice, investment advisory services, brokerage recommendations, or a solicitation to buy or sell securities. Trading in equities involves risk of capital loss.
ð¢ Engineered by Agnific
Vantage PSX is engineered with precision by Agnific.
Enterprise market intelligence, quantitative software engineering, and high-performance financial systems.
Project Timeline
Technologies
External Links
Related Projects
Projects built with similar technologies.
Online Html Editor And Viewer
The Online HTML Editor and Viewer is a simple web application built with Flask that allows users to write and preview HTML code in real-time.
Qrgen
A premium, feature-rich QR Code Generator engineered with Python (Flask) and a pristine Glassmorphism frontend.
Examina Ai
Using AI, It transforms raw study materials into structured, verified examination sets with support for institutional export formats like Moodle XML.