A sophisticated portfolio risk management and analysis system for active traders, featuring Value at Risk (VaR) calculations, real-time monitoring via Telegram, and automated pairs trading strategies.
- Value at Risk (VaR) Calculation: Parametric VaR calculation at 95% confidence level using historical data
- Portfolio Risk Monitoring: Real-time alerts for sector concentration, position sizing, and exposure limits
- Pairs Trading: Automated entry/exit for pairs trading strategies with ratio-based stop-loss
- Risk Assessment: Quality ratings (GOOD/MID/BAD) based on VaR percentiles
- Correlation Analysis: Portfolio diversification visualization through correlation matrices
- Professional Visualizations: Publication-ready charts and dashboards for presentations and social media
- Sector concentration limits (default: 20% max per sector)
- Individual position size limits (default: 5% max per position)
- Maximum portfolio size (default: 20 positions)
- Portfolio exposure limits (default: 130% of net liquidity)
- Quality-based position filtering
- Interactive Brokers: Live trading via TWS/Gateway
- Telegram Bot: Real-time portfolio alerts and monitoring
- Yahoo Finance: Historical price data and sector information
- Python 3.8+
- Data Analysis: pandas, numpy, scipy
- Visualization: matplotlib, seaborn
- Trading: ib-insync (Interactive Brokers API)
- Messaging: pyTelegramBotAPI
- Financial Data: yfinance, pandas-datareader
- Python 3.8 or higher
- Interactive Brokers TWS or Gateway (for live trading)
- Telegram account (for alerts)
- Clone the repository:
git clone <repository-url>
cd VarProject- Install dependencies:
pip install -r requirements.txt- Configure environment variables:
cp .env.example .env- Edit
.envwith your credentials:
# Required
TELEGRAM_BOT_TOKEN=your_telegram_bot_token_here
# Optional (defaults provided)
NET_LIQUIDITY=294000
INITIAL_INVESTMENT=1000000See .env.example for all available configuration options.
Transform and analyze your portfolio from broker CSV export:
python main.pyThis will:
- Transform raw portfolio CSV to standardized format
- Fetch sector information for each position
- Calculate VaR for all holdings
- Add color-coded quality ratings
- Generate Excel output with risk metrics
- Create publication-ready visualizations in the
outputs/directory:var_analysis.png- VaR bar chart with quality color-codingportfolio_dashboard.png- Comprehensive 6-panel dashboardrisk_summary.png- Visual summary card with key metrics
Perfect for LinkedIn posts, presentations, and portfolio showcases!
Start the Telegram bot for real-time alerts:
python TelegramBot.pyAvailable commands:
/Run- Execute comprehensive portfolio risk checks
The bot will alert you if any of the following conditions are met:
- Sector concentration exceeds 20%
- Individual position exceeds 5%
- Total positions exceed 20
- Portfolio exposure exceeds 130%
- Too many low-quality (high VaR) positions
Execute automated pairs trading strategy:
python online_stoploss.pyRequirements:
- Create
stock_symbols.csvwith columnsStockXandStockY - Interactive Brokers TWS/Gateway must be running
- Sufficient margin for short positions
The script will:
- Enter long/short pair at market prices
- Monitor price ratio continuously
- Exit when ratio converges by 8% (configurable)
- Log all actions and price updates
Run standalone risk checks and generate correlation matrix:
python extremities.pyCalculate VaR for all tickers in your master list:
python Var.pyThe system automatically generates professional, publication-ready visualizations when you run main.py. All charts are saved to the outputs/ directory at 300 DPI for high-quality printing and presentations.
A horizontal bar chart displaying Value at Risk for each position in your portfolio:
- Color-coded by quality rating (Green = GOOD, Yellow = MID, Red = BAD)
- Sorted by VaR magnitude
- Clear legend and currency formatting
- Perfect for identifying highest-risk positions at a glance
A comprehensive 6-panel dashboard showing:
- Sector Allocation: Pie chart showing portfolio diversification across sectors
- Top 10 Position Sizes: Bar chart with 5% limit threshold
- Long vs Short Exposure: Visual breakdown of directional exposure
- Quality Distribution: Count of GOOD/MID/BAD rated positions
- VaR Distribution: Histogram showing risk distribution across portfolio
- Timestamp and professional formatting
A visual summary card perfect for quick overviews:
- Total positions count
- Portfolio exposure percentage
- Average VaR
- Quality breakdown with visual indicators
- Highest risk position highlight
- Clean, presentation-ready design
These visualizations are specifically designed for social media and professional presentations:
Suggested LinkedIn Post Template:
π Portfolio Risk Analysis Update
Just completed a comprehensive risk assessment of my trading portfolio using
quantitative VaR analysis. Key insights:
β’ Managing [X] positions across [Y] sectors
β’ Portfolio exposure: [Z]%
β’ Average VaR: $[amount]
β’ Risk distribution: [X]% GOOD, [Y]% MID, [Z]% BAD
The dashboard shows [your key insight here].
#QuantitativeFinance #RiskManagement #PortfolioAnalysis #Trading #Python
Attach portfolio_dashboard.png or risk_summary.png to your post.
VarProject/
βββ config.py # Configuration management
βββ main.py # Main portfolio processing workflow
βββ Var.py # VaR calculation engine
βββ visualization.py # Professional chart generation
βββ TelegramBot.py # Telegram bot for alerts
βββ online_stoploss.py # Live pairs trading with IB
βββ extremities.py # Risk checks and correlation analysis
βββ stopLossFunctions.py # Various stop-loss strategies
βββ stopLossPairs.py # Pairs trading backtesting
βββ verify_setup.py # Setup verification script
βββ data/ # Portfolio data (not tracked in git)
β βββ actualportfolio.csv # Raw broker export
β βββ actualportfolio.xlsx # Transformed portfolio
β βββ alltickers.xlsx # Master ticker list with VaR
β βββ finished.xlsx # Final analysis output
βββ outputs/ # Generated visualizations (not tracked in git)
β βββ var_analysis.png # VaR bar chart
β βββ portfolio_dashboard.png # Comprehensive dashboard
β βββ risk_summary.png # Risk summary card
βββ TradingView_lists/ # Watchlists and sector lists
βββ requirements.txt # Python dependencies
βββ .env.example # Environment variables template
βββ README.md # This file
All configuration is managed through environment variables in .env:
INITIAL_INVESTMENT: Portfolio value for VaR calculation (default: 1,000,000)NET_LIQUIDITY: Net liquidation value (default: 294,000)
SECTOR_PERCENTAGE_LIMIT: Max sector concentration (default: 0.2)MAX_POSITION_PERCENTAGE: Max individual position size (default: 0.05)MAX_PORTFOLIO_SIZE: Max number of positions (default: 20)MAX_PORTFOLIO_EXPOSURE: Max total exposure (default: 1.3)
POSITION_SIZE: Pairs trading position size (default: 100 shares)TARGET_RATIO_MULTIPLIER: Exit ratio threshold (default: 0.92 = 8% convergence)SLEEP_TIME: Monitoring interval in seconds (default: 10)
IB_IP: IB Gateway IP (default: 127.0.0.1)IB_PORT: IB Gateway port (default: 7497 for paper, 7496 for live)IB_CLIENT_ID: Client ID for IB connection (default: 1)
The system expects the following data structure:
-
actualportfolio.csv: Export from your broker with columns:
- Financial Instrument, Position, Avg Price, Market Value, etc.
-
alltickers.xlsx: Master list of tickers with pre-calculated VaR
- Columns: Symbol, Var, Qual
-
stock_symbols.csv (for pairs trading):
- Columns: StockX, StockY
Data files are excluded from git by default to protect privacy.
- Never commit
.envfile or any files containing credentials .gitignoreis configured to exclude sensitive data files- All credentials should be managed through environment variables
- Consider using paper trading account for testing
All modules use Python's logging module for comprehensive logging:
- INFO: Normal operations and status updates
- WARNING: Risk violations and failed data fetches
- ERROR: Critical failures and exceptions
Logs include timestamps and detailed error traces for debugging.
When contributing:
- Never commit sensitive data or credentials
- Follow existing code style and error handling patterns
- Add logging for new operations
- Update configuration in config.py for new settings
- Test with paper trading account first
This software is for educational and research purposes only. Trading involves substantial risk of loss. The authors are not responsible for any financial losses incurred through the use of this software. Always test thoroughly with paper trading before using real capital.
[Add your chosen license here]
For issues, questions, or contributions, please open an issue on GitHub.