A powerful Telegram bot that optimizes cryptocurrency portfolios using Modern Portfolio Theory (MPT) with intelligent multi-model ensemble strategies and stability scoring.
- 🎯 Multi-Model Ensemble Strategy - Combines Mean-Variance Optimization, Risk Parity, and Equal Weight models
- 💼 Complete Wallet Analysis - Analyze any wallet address across multiple blockchains
- 📊 Efficient Frontier - Visualize risk-return tradeoffs with interactive charts
⚠️ Risk Alerts - Automatic concentration warnings and market state detection- 🔍 Auto Token Detection - Support for 10,000+ cryptocurrencies via CoinGecko API
- 🌐 Multi-Chain Support - Ethereum, BSC, Polygon, Arbitrum, Optimism, Avalanche, and more
- 📈 Interactive Visualizations - Allocation pie charts, correlation heatmaps, frontier curves
- 🔄 Extended Recommendations - Suggests complementary tokens based on correlation analysis
68+ Pre-defined tokens: BTC, ETH, BNB, SOL, XRP, ADA, DOGE, MATIC, DOT, AVAX, LINK, UNI, LTC, ATOM, ETC, XLM, ALGO, VET, FIL, ICP, USDT, USDC, DAI, SHIB, TRX, TON, ARB, OP, NEAR, APT, STX, INJ, HBAR, IMX, MKR, AAVE, GRT, SNX, RUNE, FTM, SAND, MANA, CRV, COMP, YFI, 1INCH, BAL, LDO, PEPE, FLOKI, WIF, BONK, and more.
Auto-detection: Any token listed on CoinGecko can be automatically detected via smart search API.
- Python 3.8 or higher
- Telegram account
- Clone the repository
git clone <repository-url>
cd crypto_portfolio_bot- Install dependencies
pip install -r requirements.txt- Configure environment
cp .env.example .env- Get Telegram Bot Token
- Open Telegram and search for
@BotFather - Send
/newbotcommand - Follow instructions to create your bot
- Copy the token and add to
.env:
- Open Telegram and search for
TELEGRAM_BOT_TOKEN=your_bot_token_here- (Optional) Configure Wallet APIs
For complete wallet analysis, configure one or more APIs:
DeBank API (Free, no config needed):
- Works out of the box
- Supports major chains
Covalent API (Recommended):
- Most complete holdings data
- Sign up: https://www.covalenthq.com/
- Add to
.env:
COVALENT_API_KEY=your_api_key_hereEtherscan API (Backup):
- Accurate ERC-20 data
- Sign up: https://etherscan.io/apis
- Add to
.env:
ETHERSCAN_API_KEY=your_api_key_herepython main.py| Command | Description | Example |
|---|---|---|
/start |
Welcome message | /start |
/help |
Show help | /help |
/lang |
Change language | /lang zh |
/coins |
List supported coins | /coins |
/prices |
Get current prices | /prices BTC ETH |
/optimize |
Optimize portfolio | /optimize BTC ETH SOL |
/wallet |
Analyze wallet | /wallet 0xYourAddress ethereum |
Analyze any wallet address to get personalized optimization recommendations:
/wallet <wallet_address> <blockchain>
Examples:
/wallet 0x396343362be2A4dA1cE0C1C210945346fb82Aa49 ethereum
/wallet 0xYourAddress bsc
/wallet 0xYourAddress polygon
What you get:
- 📊 Current holdings breakdown
- 💰 Total portfolio value
- 🎯 Optimized allocation recommendations
⚠️ Concentration risk warnings- 📈 Interactive charts (efficient frontier, allocation, correlations)
- 💡 Extended token recommendations
| Model | Principle | Best For |
|---|---|---|
| Mean-Variance | Maximize Sharpe ratio | Bull markets, trending |
| Risk Parity | Equal risk contribution | Bear markets, stability |
| Equal Weight | Simple diversification | Neutral markets |
The system dynamically adjusts model weights based on market state:
Market State → Model Confidence Weights
Bull → Mean-Variance: 80%, Risk Parity: 60%, Equal Weight: 50%
Bear → Mean-Variance: 40%, Risk Parity: 80%, Equal Weight: 60%
Neutral → Mean-Variance: 60%, Risk Parity: 70%, Equal Weight: 60%
- Maximum single asset: 40%
- Minimum stablecoin allocation: 15%
When analyzing wallets, the bot also recommends complementary tokens based on:
- Low correlation with current holdings
- Market momentum
- Asset quality (blue-chip vs growth)
crypto_portfolio_bot/
├── main.py # Entry point
├── requirements.txt # Python dependencies
├── .env.example # Environment variables template
├── README.md # This file
├── src/
│ ├── __init__.py
│ ├── bot.py # Telegram bot handlers (refactored to ~550 lines)
│ ├── config/
│ │ ├── constants.py # Configuration constants
│ │ └── settings.py # Environment settings
│ ├── handlers/ # Modular handlers (menu, wallet, portfolio, market)
│ │ ├── callbacks.py
│ │ ├── market.py
│ │ ├── menu.py
│ │ ├── portfolio.py
│ │ ├── session.py
│ │ └── wallet.py
│ ├── services/ # Core business logic
│ │ ├── alert_scheduler.py
│ │ ├── data_fetcher.py # CoinGecko API integration
│ │ ├── ensemble_strategy.py # Multi-model strategy
│ │ ├── market_state.py # Market condition detection
│ │ ├── optimizer.py # Portfolio optimization
│ │ ├── rebalancing_alert.py
│ │ ├── visualizer.py # Chart generation
│ │ └── wallet_fetcher.py # Wallet data fetching
│ ├── i18n/
│ │ └── translations.py # Multi-language support
│ └── utils/
│ ├── async_http.py # Async HTTP utilities
│ ├── db_store.py # Database utilities
│ ├── fun_progress.py # Simple progress tracking
│ ├── language_store.py # Language preferences
│ ├── log_filters.py # Log sanitization
│ ├── progress_tracker.py # Advanced progress tracking
│ └── validators.py # Input validation
├── tests/ # Unit tests
└── docs/ # Documentation
├── ARCHITECTURE.md # System architecture
├── DB_SETUP.md # Database setup
├── MULTI_WINDOW_COMPARISON.md # Time window comparison
├── PORTFOLIO_INTERPRETATION.md # Results interpretation
├── QUICKSTART.md # Quick start guide
├── STABILITY_OPTIMIZATION.md # Stability scoring system
└── WALLET_ANALYSIS_GUIDE.md # Complete wallet guide
bot.pyreduced from 2000+ lines to ~550 lines- Split into focused handler modules
- Clear separation of concerns
- Async thread pools prevent blocking
- Progress bars for long-running operations
- Automatic cleanup of progress messages
- Stability scoring system avoids overfitting
- Multi-window testing (1d, 7d, 30d, 90d, 180d, 365d)
- Concentration warnings for single-asset risk
Make sure you've created a .env file with your bot token.
CoinGecko's free API has rate limits. The system includes automatic retry with exponential backoff.
- Try configuring Covalent API for more complete data
- Ensure the wallet address and blockchain match
- Check if the blockchain is supported
This indicates the entire sample period showed losses (bear market). The optimization found the "least bad" option.
- Never commit your
.envfile to version control - Keep your bot token secret
- Consider implementing user authentication for production use
MIT License
This bot is for educational and informational purposes only. It does not constitute financial advice. Cryptocurrency investments are highly risky. Always do your own research before making investment decisions.