The Free Portfolio Risk Scanner Indian Retail Investors Never Had
Open-source VaR, Sharpe ratio, Monte Carlo simulation, and sector exposure analysis from a single CSV upload. No subscriptions, no API keys, no catch.
I know a guy who trades actively. Checks his Zerodha Console every morning, tracks P&L religiously, rebalances once a quarter. Solid process.
Last week I asked him: what’s your portfolio’s Value at Risk?
Blank stare.
Not his fault. Every free tool for the Indian market shows you P&L. None of them tell you whether your portfolio is actually risky. Zerodha Console gives green and red numbers. Tickertape charges ₹399/month for proper analytics. Bloomberg terminals cost lakhs.
There’s a gap in the middle where most retail investors sit. And the options are either too basic or too expensive.
I got tired of waiting for someone to fill it. So I built an open-source portfolio risk scanner that does exactly one thing: take your broker CSV and spit out institutional grade risk metrics. VaR 95/99, Sharpe and Sortino ratios, Monte Carlo simulation, HMM regime detection, sector concentration, stress testing. All from numpy and scipy. Zero paid APIs.
I call it the NSE Portfolio Risk Scanner.
Here’s what it does and why I think it matters.
The Problem With Portfolio Risk
Portfolio risk analysis is not complicated math. VaR is a percentile. Sharpe is a ratio. Drawdown is a running minimum. A first year quant finance student can code these in an afternoon.
But packaged into a usable tool? That’s where it breaks down.
The existing options look like this:
Notice the gap. There’s a free option that shows you what you own, and a paid option that shows you risk. Nothing in between that is both free and analytical.
That gap is where most Indian investors live.
What the Tool Does
You export your portfolio CSV from your broker. Upload it. And you get:
Core risk metrics. Annualized volatility, VaR at 95% and 99% confidence, Conditional VaR, Sharpe and Sortino ratios, beta against Nifty 50, maximum drawdown with peak-to-trough timestamps. All computed from your actual holdings, not an approximation.
Monte Carlo simulation. 10,000 geometric Brownian motion paths project your portfolio forward. You get probability of profit, confidence intervals, and horizon VaR. It’s the same technique institutional risk teams run, just without the Bloomberg terminal.
HMM regime detection. A Gaussian Hidden Markov Model classifies market states into Bull, Neutral, or Bear. You see transition probabilities between regimes, per regime return and volatility stats, and which regime you’re likely in right now. Falls back to a quantile heuristic if hmmlearn isn’t installed.
Sector analysis. 160+ NSE stocks mapped across 18 sectors. Herfindahl-Hirschman Index for concentration risk. A diversification score from 0 to 100. Automatic flagging when any sector breaches 20% of your portfolio.
Factor decomposition. Market beta, size, momentum, volatility, liquidity, and concentration factor exposures. Macro sensitivity estimates for crude oil, interest rates, INR/USD, and global risk sentiment.
Stress testing. Five basic scenarios (mild crash through bull run) plus seven macro scenarios with sector specific multipliers. Each scenario includes probability estimates and causal reasoning.
Institutional risk scoring. A P×I×C (Probability × Impact × Confidence) framework that produces five composite scores: Overall Risk, Conviction, Stress, Hidden Correlation, and Tail Risk. It’s the closest thing to what a sell-side risk desk would produce.
Plain-English narratives. Here’s the part I’m most proud of. Every metric is accompanied by a rule-generated explanation that tells you what it means. “VaR 95%: -1.8%” becomes “you have a 5% chance of losing this much in a day.” No LLM involved, no API call, no privacy leak. Just if/elif chains tuned for Indian market context.
PDF export. A four page report with cover page, risk analysis, and holdings breakdown. Ready to email or print.
Get Ashay Kushwaha’s stories in your inbox
Join Medium for free to get updates from this writer.
Shareable links. Your entire portfolio is base64-encoded into a ?p= query parameter. Share the URL. Zero server storage.
All of this from a single CSV upload. It handles 10+ broker formats — Zerodha, Groww, Upstox, Angel One, ICICI Direct, Kotak, HDFC Sec. Indian number formats with commas. Auto-detects columns. If you don’t have a CSV, there’s a one-click sample portfolio button that loads a diversified 7 holding portfolio to explore the tool in zero clicks.
Why the Architecture Matters
The biggest design decision was keeping the risk engine completely separate from the UI.
engine/ → Pure Python. Zero Streamlit. Zero IO. Every function is a dataclass in, dataclass out.
ui/ → Streamlit only. Zero business logic. Renders what the engine returns.
data/ → Price fetching with three-tier caching. nselib → yfinance → diskcache.
storage/ → SQLite persistence for portfolios and analysis history.This means the engine is independently testable. Every risk function takes inputs and returns outputs with no side effects. You can import engine.risk in a Jupyter notebook, a FastAPI server, or a cron job and get the same results.
The test suite reflects this. 355 tests across 26 files, 90% coverage. Every module in engine/ has dedicated unit tests. The integration tests verify the full pipeline from CSV input to rendered metrics.
The caching hierarchy deserves its own note. Price fetching is the bottleneck (yfinance is free but rate-limited). So there are three layers:
- L1: In-memory LRU dict (128 entries, per session)
- L2: SQLite via diskcache (cross-session, survives restarts)
- L3: yfinance (source of truth)
The first load fetches from yfinance. Every subsequent load in the same session hits L1 (instant). Reloads across sessions hit L2 (milliseconds). You only touch yfinance again when the cache expires or you force a refresh.
The result: after the first run, the tool loads in about a second. No waiting for Yahoo Finance every time you open it.
What I’d Change
The rule-based narrative engine was harder to tune than I expected. Translating quant metrics into plain English sounds simple, but edge cases multiply fast. What do you say when VaR is 0% because the portfolio is mostly cash? What about a Sharpe ratio that’s negative because the risk-free rate is higher than returns? The thresholds that work for a 10 stock equity portfolio break for a 3 holding concentrated position.
There are about 40 edge case guards across the narrative module. I still find new ones every time I test with a different portfolio.
I’d also like to add mutual fund support. Right now the tool only handles direct equity holdings and ETFs. The data pipeline for mutual fund NAVs is different, and I haven’t cracked it in a way that meets the zero paid API constraint.
How It Compares
The honest trade-off: Tickertape has better data coverage (mutual funds, IPOs, broader screening) and a polished UI. If you need those, ₹399/month is reasonable. But if what you need is portfolio risk analytics — VaR, Sharpe, drawdown, concentration — this tool gives you the same math for free, with the ability to inspect every line of code.
Getting Started
The live app is at nse-portfolio-risk-scanner.streamlit.app. No sign up, no account, no API key. Upload your CSV or click “Try Sample Portfolio” and you’re running.
To run it locally:
git clone https://github.com/AshayK003/nse-portfolio-risk-scanner
cd nse-portfolio-risk-scanner
pip install -e .
streamlit run app.pyThat’s it. Three commands, zero configuration, no environment variables.
The repo is at github.com/AshayK003/nse-portfolio-risk-scanner under AGPLv3 license. Contributions, issues, and feature requests are genuinely welcome. The financial lexicon could use more Indian market terms in the narrative engine, the broker CSV format list could always grow, and I keep finding edge cases in the scenario stress tests that need better handling.
If you trade NSE stocks, upload your portfolio and see what the numbers say. They might surprise you.
They surprised me.
Built by Ashay Kushwaha.
Repo: github.com/AshayK003/nse-portfolio-risk-scanner.
App: nse-portfolio-risk-scanner.streamlit.app.









