Skip to content

bhanuprasanna2001/CapiPortV2

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

56 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

title emoji sdk sdk_version app_file pinned license python_version
CapiPort
πŸ“ˆ
streamlit
1.32.0
main.py
false
mit
3.10

πŸ“ˆ CapiPort V2

Quantitative Portfolio Optimisation for Indian Equity Markets

Build Status License: MIT Python Streamlit HuggingFace

πŸš€ Live Demo β€” πŸ€— HuggingFace Spaces


πŸ“Œ Table of Contents

  1. Overview
  2. Why CapiPort?
  3. Quantitative Methodology
  4. Key Features
  5. Tech Stack
  6. Architecture
  7. Getting Started
  8. Usage
  9. Output & Analytics
  10. Deployment
  11. Contributing
  12. License

πŸ”­ Overview

CapiPort V2 is an end-to-end, web-based quantitative portfolio optimisation platform focused on the National Stock Exchange (NSE) of India. Given a user-defined basket of NSE-listed equities, a historical look-back window, and an investment amount, CapiPort computes the mathematically optimal capital allocation across assets β€” maximising risk-adjusted returns while rigorously controlling for portfolio volatility.

The application is built on battle-tested financial theory (Modern Portfolio Theory & Graph-based Risk Parity) and delivers institutional-grade analytics through a clean, interactive Streamlit UI β€” accessible to anyone with a browser.


πŸ’‘ Why CapiPort?

Challenge CapiPort's Solution
Indian retail investors lack access to quant tools Browser-based app β€” no coding required
Manual stock selection is noisy and biased Data-driven allocation via mathematical optimisation
Ignoring correlations leads to concentrated risk Covariance-aware EF & HRP methods account for cross-asset correlation
No visibility into historical performance Full annual & monthly return breakdown with interactive charts
Opaque black-box tools Open-source, fully auditable Python codebase

πŸ“ Quantitative Methodology

CapiPort V2 implements two complementary optimisation frameworks, giving users control over the risk-return trade-off:

1. πŸ”· Efficient Frontier (Modern Portfolio Theory)

Based on Harry Markowitz's seminal 1952 framework, the Efficient Frontier identifies the set of portfolios that maximise expected return for a given level of risk (variance).

$$\min_{\mathbf{w}} ; \mathbf{w}^T \Sigma \mathbf{w} \quad \text{subject to} \quad \mathbf{w}^T \boldsymbol{\mu} \geq \mu^*, ; \mathbf{w}^T \mathbf{1} = 1, ; w_i \geq 0$$

Four parametric objectives are supported:

Parameter Description Best For
Maximum Sharpe Ratio Maximises the reward-to-risk ratio: $\frac{\mu_p - r_f}{\sigma_p}$ Growth-oriented investors
Minimum Volatility Minimises portfolio variance regardless of return Conservative / risk-averse investors
Efficient Risk Maximises return subject to a target volatility constraint Investors with a defined risk budget
Efficient Return Minimises risk subject to a target return constraint Investors with a return target

Inputs to EF: Mean historical returns vector ΞΌ and sample covariance matrix Ξ£, both estimated from adjusted closing prices sourced via Yahoo Finance.


2. πŸ”Ά Hierarchical Risk Parity (HRP)

HRP, introduced by Marcos LΓ³pez de Prado (2016), overcomes a key weakness of the classical EF β€” sensitivity to estimation error in the covariance matrix β€” by using graph theory and hierarchical clustering instead of matrix inversion.

The algorithm proceeds in three steps:

1. Tree Clustering   β†’ Build a dendrogram of assets via correlation-based linkage
2. Quasi-Diagonalisation β†’ Reorder the covariance matrix so correlated assets sit together
3. Recursive Bisection  β†’ Allocate capital top-down through the tree proportional to cluster-level inverse-variance

HRP produces more stable, diversified portfolios that are robust to covariance estimation noise, making it particularly suitable for volatile or illiquid segments of the NSE.


✨ Key Features

  • 🏦 1,000+ NSE-listed equities β€” comprehensive universe covering large-, mid-, and small-cap stocks
  • βš™οΈ Dual optimisation engines β€” Efficient Frontier (4 objectives) and Hierarchical Risk Parity
  • πŸ“Š Interactive visualisations β€” asset allocation pie chart, annual bar chart, cumulative return time-series (all powered by Plotly)
  • πŸ“… Flexible look-back window β€” set any historical start date from 1947-08-15 onward
  • πŸ’° Investment simulation β€” enter an initial capital amount and track portfolio value evolution over time
  • πŸ“‹ Granular analytics tables β€” annual returns, monthly returns, and per-stock weighted contribution breakdowns
  • ⚑ Zero-install access β€” fully deployed on Streamlit Cloud and HuggingFace Spaces
  • πŸ”“ Open-source β€” MIT licensed; inspectable and extendable

πŸ› οΈ Tech Stack

Layer Technology
Frontend / UI Streamlit
Data Ingestion yfinance (Yahoo Finance API)
Optimisation PyPortfolioOpt
Visualisation Plotly
Data Wrangling pandas, NumPy
Database MongoDB via PyMongo
CI/CD GitHub Actions β†’ HuggingFace Spaces sync
Language Python 3.10+

πŸ—οΈ Architecture

CapiPortV2/
β”œβ”€β”€ main.py                        # App entry point β€” wires together UI & logic
β”œβ”€β”€ requirements.txt               # Pinned Python dependencies
β”‚
└── utilities/
    β”œβ”€β”€ data/
    β”‚   └── Company List.csv       # NSE universe: company names & ticker symbols
    β”œβ”€β”€ style/
    β”‚   └── style.css              # Custom Streamlit CSS styling
    β”œβ”€β”€ Notebooks/
    β”‚   └── Experiment.ipynb       # Research & prototyping notebook
    └── py/
        β”œβ”€β”€ composer.py            # High-level app orchestration (MVC controller)
        β”œβ”€β”€ ui_elements.py         # Streamlit widget definitions (view layer)
        β”œβ”€β”€ data_management.py     # Stock data fetching & portfolio optimisation (model)
        β”œβ”€β”€ plots.py               # Plotly chart builders
        β”œβ”€β”€ summary_tables.py      # Return aggregation & table formatting
        β”œβ”€β”€ styling.py             # Page-level Streamlit styling helpers
        └── mongodb.py             # MongoDB integration utilities

Data flow:

User selects stocks + params
        ↓
yfinance fetches adjusted close prices (Yahoo Finance)
        ↓
PyPortfolioOpt computes ΞΌ (mean returns) & Ξ£ (covariance matrix)
        ↓
EF / HRP solver β†’ optimal weight vector w*
        ↓
Portfolio returns & metrics computed β†’ rendered via Plotly + Streamlit

πŸš€ Getting Started

Prerequisites

  • Python 3.10 or higher
  • pip package manager

Installation

# 1. Clone the repository
git clone https://github.com/bhanuprasanna527/CapiPortV2.git
cd CapiPortV2

# 2. (Recommended) Create a virtual environment
python -m venv venv
source venv/bin/activate        # macOS / Linux
# venv\Scripts\activate         # Windows

# 3. Install dependencies
pip install -r requirements.txt

Run locally

streamlit run main.py

The app will open at http://localhost:8501 in your default browser.


πŸ“– Usage

  1. Select companies β€” pick two or more NSE-listed stocks from the multi-select dropdown (1,000+ available)
  2. Choose an optimisation method β€” Efficient Frontier or Hierarchical Risk Parity
  3. Set an EF parameter (Efficient Frontier only) β€” Maximum Sharpe Ratio, Minimum Volatility, Efficient Risk, or Efficient Return
  4. Pick a start date β€” defines the historical window used to estimate returns and covariance
  5. Enter initial investment (β‚Ή) β€” used to simulate the absolute portfolio value trajectory
  6. Click Run β€” CapiPort fetches live data, optimises, and renders all results

πŸ“Š Output & Analytics

After optimisation, CapiPort presents a rich set of outputs:

Output Description
Stock Price Table Adjusted closing prices for the selected basket over the chosen period
Asset Allocation Table Optimal weight (%) assigned to each stock
Portfolio Performance Expected annual return (%), annual volatility (%), Sharpe ratio
Allocation Pie Chart Interactive donut chart of capital distribution
Annual Returns Bar Chart Year-by-year portfolio return visualisation
Cumulative Returns Chart Portfolio value growth over time (β‚Ή) with range slider
Annual Returns Table Year-level return, cumulative balance, and per-stock weighted contribution
Monthly Returns Table Month-level return, cumulative balance, and per-stock weighted contribution

🌐 Deployment

Platform URL
Streamlit Cloud https://capiport2.streamlit.app/
HuggingFace Spaces (V2) https://huggingface.co/spaces/bhanuprasanna527/CapiPort
Version 1 β€” GitHub https://github.com/bhanuprasanna527/CapiPort
Version 1 β€” HuggingFace Spaces https://huggingface.co/spaces/sankhyikii/CapiPort

Continuous deployment is handled via a GitHub Actions workflow (.github/workflows/HF_sync_space.yml) that automatically syncs the main branch to HuggingFace Spaces on every push.


🀝 Contributing

Contributions are warmly welcome! Here's how to get involved:

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/your-feature-name
  3. Commit your changes: git commit -m "feat: add your feature"
  4. Push to your fork: git push origin feature/your-feature-name
  5. Open a Pull Request β€” describe your changes and the problem they solve

Ideas for contribution:

  • Add Monte Carlo simulation for forward-looking risk analysis
  • Integrate Black-Litterman model for view-adjusted returns
  • Add factor exposure analysis (Fama-French)
  • Support BSE (Bombay Stock Exchange) tickers

πŸ“„ License

This project is licensed under the MIT License β€” see the LICENSE file for details.


*Built with ❀️ and rigorous quantitative finance

⭐ Star this repo if you find it useful! ⭐

About

Your Portfolio Optimisation Tool

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors