An automated momentum-based portfolio management system for NSE stocks using Python.
- Automated Stock Screening: Filters stocks based on momentum criteria
- Sharpe Ratio Calculation: Multi-period Sharpe ratio analysis (3/6/9/12 months)
- Technical Filters: 200-day moving average and 52-week high proximity checks
- Portfolio Construction: Automatically builds portfolios with up to 30 stocks
- Daily Monitoring: Tracks portfolio stocks for 200 DMA breaks
- Monthly Rebalancing: Automated monthly portfolio rebalancing
- JSON Configuration: Easily configurable parameters
- Python 3.7 or higher
- Internet connection for fetching stock data
-
Download all the files to a folder:
momentum_portfolio.py(main script)setup_and_run.py(setup helper)requirements.txt(dependencies)- Batch files for automation
-
Install dependencies:
pip install -r requirements.txt
-
Or use the setup script:
python setup_and_run.py
The system uses a portfolio_config.json file for configuration:
{
"max_stocks": 30,
"exit_rank": 60,
"dma_period": 200,
"lookback_periods": [3, 6, 9, 12],
"high_percentage_threshold": 30,
"use_all_time_high": false,
"portfolio_file": "current_portfolio.json",
"data_cache_file": "stock_data_cache.json"
}Configuration Parameters:
max_stocks: Maximum number of stocks in portfolio (default: 30)exit_rank: Exit rank threshold (default: 60)dma_period: Moving average period (default: 200)lookback_periods: Sharpe ratio calculation periods in monthshigh_percentage_threshold: Maximum distance from 52-week high (%)use_all_time_high: Use all-time high instead of 52-week highportfolio_file: File to store current portfoliodata_cache_file: File to cache stock data
# Monthly rebalancing
python momentum_portfolio.py rebalance
# Daily monitoring
python momentum_portfolio.py monitor
# Show configuration
python momentum_portfolio.py configpython setup_and_run.py- Double-click
run_rebalance.batfor monthly rebalancing - Double-click
run_monitor.batfor daily monitoring
# Make executable
chmod +x run_rebalance.sh run_monitor.sh
# Run scripts
./run_rebalance.sh # Monthly rebalancing
./run_monitor.sh # Daily monitoring- Technical Filter: Stock price > 200-day moving average
- Momentum Filter: Stock within 30% of 52-week high (configurable)
- Sharpe Ratio: Ranked by 12-month Sharpe ratio
- Universe: NSE stocks (expandable to NSE 750)
- Maximum 30 stocks in portfolio
- Monthly rebalancing on predetermined dates
- Daily exit monitoring for 200 DMA breaks
- Immediate exit when stock breaks below 200 DMA
- New additions only on rebalance days
- Fetch daily price data for specified lookback period
- Calculate daily returns
- Compute annualized return and volatility
- Sharpe Ratio = Annualized Return / Annualized Volatility
momentum_portfolio/
βββ momentum_portfolio.py # Main portfolio manager
βββ setup_and_run.py # Setup and interactive runner
βββ requirements.txt # Python dependencies
βββ portfolio_config.json # Configuration file
βββ current_portfolio.json # Current portfolio data
βββ run_rebalance.bat # Windows rebalance script
βββ run_monitor.bat # Windows monitoring script
βββ run_rebalance.sh # Linux/Mac rebalance script
βββ run_monitor.sh # Linux/Mac monitoring script
βββ rebalance_results_*.json # Rebalancing results
βββ monitoring_results_*.json # Daily monitoring results
- Open Task Scheduler
- Create Basic Task
- Set trigger for monthly rebalancing
- Set action to run
run_rebalance.bat - Repeat for daily monitoring with
run_monitor.bat
# Edit crontab
crontab -e
# Add these lines:
# Daily monitoring at 9:30 AM
30 9 * * 1-5 /path/to/your/script/run_monitor.sh
# Monthly rebalancing on 1st of each month at 10:00 AM
0 10 1 * * /path/to/your/script/run_rebalance.sh==============================================================
MOMENTUM PORTFOLIO REBALANCING
==============================================================
Fetching data for 50 stocks...
β RELIANCE.NS (1/50)
β TCS.NS (2/50)
...
Screening stocks...
π REBALANCING RESULTS
π New Portfolio Size: 30 stocks
β Added Stocks: 5
β Removed Stocks: 3
π ADDED STOCKS:
β’ TITAN.NS
β’ MARUTI.NS
β’ SUNPHARMA.NS
ποΈ REMOVED STOCKS:
β’ ONGC.NS
β’ COALINDIA.NS
π FINAL PORTFOLIO:
1. RELIANCE.NS
2. TCS.NS
3. HDFCBANK.NS
...
==============================================================
DAILY PORTFOLIO MONITORING
==============================================================
Checking DMA breaks...
π’ RELIANCE.NS - Above 200 DMA (Price: 2450.00, DMA: 2380.50)
π’ TCS.NS - Above 200 DMA (Price: 3890.00, DMA: 3750.25)
π΄ ONGC.NS - Below 200 DMA (Price: 185.50, DMA: 195.75)
π MONITORING RESULTS
π Portfolio Size: 30 stocks
π΄ Stocks Below 200 DMA: 1
π’ Healthy Stocks: 29
β οΈ STOCKS TO EXIT (Below 200 DMA):
β’ ONGC.NS
To expand beyond the sample tickers, modify the get_nse_tickers() method in momentum_portfolio.py:
def get_nse_tickers(self) -> List[str]:
# Add your NSE 750 tickers here
your_tickers = [
'RELIANCE', 'TCS', 'HDFCBANK',
# ... add all 750 tickers
]
return [ticker + '.NS' for ticker in your_tickers]Modify portfolio_config.json:
- Change
max_stocksfor different portfolio sizes - Adjust
high_percentage_thresholdfor different momentum criteria - Modify
lookback_periodsfor different Sharpe calculation windows - Set
use_all_time_high: trueto use all-time highs instead of 52-week highs
Extend the screen_stocks() method to add custom filters:
# Example: Add volume filter
avg_volume = data['Volume'].tail(20).mean()
if avg_volume < 100000: # Minimum volume threshold
continue- Uses Yahoo Finance data (free but may have delays)
- Sample includes ~50 stocks (expand to NSE 750 for production)
- Historical data availability may vary by stock
- Backtesting: Always backtest before live trading
- Market Conditions: Strategy performance varies with market conditions
- Slippage: Consider transaction costs and slippage
- Position Sizing: Implement proper position sizing rules
- System handles missing data gracefully
- Logs errors for individual stock processing
- Continues processing even if some stocks fail
-
Import Errors
pip install --upgrade yfinance pandas numpy requests
-
Data Fetch Failures
- Check internet connection
- Verify ticker symbols are correct
- Some stocks may be delisted or suspended
-
Configuration Errors
- Ensure
portfolio_config.jsonis valid JSON - Check file permissions for writing results
- Ensure
-
Empty Portfolio
- Relax screening criteria
- Check if stocks meet all filters
- Verify data availability for selected time periods
Add debugging by modifying the script:
import logging
logging.basicConfig(level=logging.DEBUG)- Fork the code
- Add new methods to the
MomentumPortfolioManagerclass - Update configuration schema if needed
- Test thoroughly before production use
Consider using Git for tracking changes:
git init
git add .
git commit -m "Initial momentum portfolio setup"- NSE Website - Official NSE data
- Yahoo Finance API - Data source documentation
- Pandas Documentation - Data manipulation
- NumPy Documentation - Numerical computing
This software is for educational and research purposes only. It is not investment advice. Always:
- Consult with financial advisors
- Understand the risks involved
- Test thoroughly before real trading
- Consider your risk tolerance
- Past performance doesn't guarantee future results
Happy Trading! ππ