PythonPython
HTMLHTML
CSSCSS
JavaScriptJavaScript
No Screenshots Uploaded Yet
COMPLETED

Vantage Psx

![Python Version](https://www.python.org/) ![FastAPI](https://fastapi.tiangolo.com/) ![TradingView](https://tradingview.github.io/lightweight-charts/) ![Agnific](https://www.agnific.com) Vantage PSX

About the Project

Python Version FastAPI TradingView Agnific

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 localStorage persistence.

🔬 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 (venv or conda)

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 install or 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 quotes
  • GET /api/quotes/{symbol} — Fetch real-time telemetry for a single ticker
  • GET /api/history/{symbol} — Fetch daily OHLCV candlestick historical series
  • GET /api/signals/{symbol} — Fetch Intraday, Swing, and Long-term signal results
  • GET /api/news — Fetch aggregated news and corporate calendar disclosures
  • GET /api/system/health — Terminal health and memory telemetry
  • WS /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

Aug 2026 - Aug 2026

Technologies

PythonHTMLCSSJavaScript

External Links

Related Projects

Projects built with similar technologies.

Online Html Editor And Viewer
COMPLETED
JavaScriptHTMLCSS+1 more

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.

Rasikh Ali
Qrgen
COMPLETED
Jupyter NotebookHTMLPython

Qrgen

A premium, feature-rich QR Code Generator engineered with Python (Flask) and a pristine Glassmorphism frontend.

Rasikh Ali
Examina Ai
COMPLETED
TypeScriptPythonCSS+2 more

Examina Ai

Using AI, It transforms raw study materials into structured, verified examination sets with support for institutional export formats like Moodle XML.

Rasikh Ali