Skip to content

Repository files navigation

Factor Exposure API (FastAPI Backend)

Quantitative Analytics & Risk Factor Engine for Indian Equities (Nifty 500)

The high-performance, asynchronous Python backend for the Factor Exposure Analyzer terminal. It utilizes advanced multivariate regression algorithms to calculate stock sensitivities ($\beta$ coefficients) against five critical risk factors and attributes variance-decomposition risk contributions.


📈 Quantitative Factor Model

The engine downloads equity datasets dynamically via Yahoo Finance (yfinance) and estimates rolling Ordinary Least Squares (OLS) regressions against liquid proxies representing five market risk premiums:

$$R_i(t) - R_f = \alpha_i + \beta_{i,MKT}(R_{MKT}(t) - R_f) + \beta_{i,VAL}R_{VAL}(t) + \beta_{i,MOM}R_{MOM}(t) + \beta_{i,SZ}R_{SZ}(t) + \beta_{i,VOL}R_{VOL}(t) + \epsilon_i(t)$$

Factor Proxy Underlying Metric Yahoo Ticker
Nifty 50 Market Benchmark ^NSEI
Nifty Value 20 Value / Fundamental Cheapness NV20BEES.NS
Nifty Momentum 50 Trend / Relative Strength MOMOMENTUM.NS
Nifty Midcap 150 Size / Cap-weighted Premium MID150BEES.NS
India VIX Market Fear / Systemic Volatility ^INDIAVIX

⚙️ Setup & Installation

Prerequisites

  • Python: 3.10 or higher
  • Dependencies: Listed in requirements.txt (statsmodels, scikit-learn, yfinance, pandas, supabase)

Local Setup

  1. Navigate into the directory:

    cd factor-exposure-api
  2. Initialize and activate virtual environment:

    # Windows
    python -m venv .venv
    .venv\Scripts\activate
    
    # macOS/Linux
    python3 -m venv .venv
    source .venv/bin/activate
  3. Install requirements:

    pip install -r requirements.txt
  4. Configure Environment Variables: Copy the example template to .env:

    cp .env.example .env

    Populate your custom rate limits, persistent Supabase keys, and server bindings.

  5. Run server:

    python -m uvicorn main:app --host 127.0.0.1 --port 8000 --reload

    The OpenAPI/Swagger docs will be live at http://127.0.0.1:8000/docs.


🚀 Deploying to Render (Best Practice)

This backend is ready for immediate deployment on Render (Free or Starter tier):

  1. Create Render Web Service: Connect your GitHub repository to Render.
  2. Configuration:
    • Environment: Python
    • Build Command: pip install -r requirements.txt
    • Start Command: uvicorn main:app --host 0.0.0.0 --port $PORT
  3. Environment Variables:
    • PORT: 8000 (Render will override or map this automatically)
    • CORS_ORIGINS: Add your deployed Next.js URL(s), comma-separated (e.g., https://factor-analyzer.vercel.app,http://localhost:3000)
    • LOG_LEVEL: INFO
    • SUPABASE_URL / SUPABASE_KEY (highly recommended to prevent API rate limiting from Yahoo Finance by utilizing shared cache storage).

🔄 Heatmap Pre-Computation Pipeline

The system exposes a dedicated heatmap computation endpoint for portfolio-wide factor exposure analysis across the Nifty 500 universe:

Endpoint Method Description
/heatmap GET Returns computed factor betas for all tickers with sector aggregations
/heatmap/status GET Returns computation progress for a specific window (126D/252D/504D)
/heatmap/status/all GET Returns completion status for all windows in a single call

Pre-computation Workflow:

# Activate virtual environment
.venv\Scripts\activate

# Run the heatmap compute script (computes all 500 tickers)
python scripts/compute_heatmap.py

The script iterates through the Nifty 500 constituent list, performs rolling OLS regressions for each ticker against the five factor proxies, and stores results in Supabase. On a local machine, full computation takes approximately 45-60 minutes.


💾 Supabase Caching Architecture

The API implements a TTL-based caching layer backed by Supabase to minimize repeated Yahoo Finance API calls:

Cache Table Key TTL Purpose
factor_betas_cache ticker + window_size 24 hours (configurable) Individual stock factor regressions
heatmap_cache ticker + window Permanent Pre-computed heatmap data

Graceful Degradation: If Supabase is unavailable (missing credentials or connectivity issues), the API falls back to on-demand computation. The service remains fully functional—albeit slower on cache misses.

Environment Variables:

SUPABASE_URL=https://your-project.supabase.co
SUPABASE_KEY=your-anon-key
CACHE_TTL_HOURS=24

⚡ Rate Limiting & Performance

The API implements request throttling via slowapi:

  • Default Limit: 10 requests/minute per IP
  • Exempt Endpoints: /health, /heatmap/status, /heatmap/status/all
  • Customization: Set via RATE_LIMIT environment variable (e.g., "50/minute")

For production deployments, we recommend:

  1. Enabling Supabase caching to reduce Yahoo Finance API calls
  2. Running weekly heatmap pre-computation via GitHub Actions
  3. Using GitHub Actions cron job to ping /health every 10 minutes (see .github/workflows/keep_alive.yml)

👥 Credits

Quantitative engine design, micro-service orchestration, and data fetching handlers by Sourabh.

About

Quantitative factor exposure analyzer for Nifty 500 stocks, rolling OLS regression, sector heatmap, FastAPI backend

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages