Skip to content

Skeiro666/crypto_portfolio_bot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Crypto Portfolio Optimizer Telegram Bot

A powerful Telegram bot that optimizes cryptocurrency portfolios using Modern Portfolio Theory (MPT) with intelligent multi-model ensemble strategies and stability scoring.

✨ Key Features

  • 🎯 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

🚀 Supported Cryptocurrencies

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.

📦 Installation

Prerequisites

  • Python 3.8 or higher
  • Telegram account

Quick Start

  1. Clone the repository
git clone <repository-url>
cd crypto_portfolio_bot
  1. Install dependencies
pip install -r requirements.txt
  1. Configure environment
cp .env.example .env
  1. Get Telegram Bot Token
    • Open Telegram and search for @BotFather
    • Send /newbot command
    • Follow instructions to create your bot
    • Copy the token and add to .env:
TELEGRAM_BOT_TOKEN=your_bot_token_here
  1. (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):

COVALENT_API_KEY=your_api_key_here

Etherscan API (Backup):

ETHERSCAN_API_KEY=your_api_key_here

💬 Usage

Start the Bot

python main.py

Basic Commands

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

🆕 Wallet Analysis

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

🧠 Multi-Model Ensemble Strategy

Three Models Combined

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

Smart Weight Allocation

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%

Risk Constraints

  • Maximum single asset: 40%
  • Minimum stablecoin allocation: 15%

Extended Recommendations

When analyzing wallets, the bot also recommends complementary tokens based on:

  • Low correlation with current holdings
  • Market momentum
  • Asset quality (blue-chip vs growth)

📁 Project Structure

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

🚀 Key Improvements

Modular Architecture

  • bot.py reduced from 2000+ lines to ~550 lines
  • Split into focused handler modules
  • Clear separation of concerns

Performance

  • Async thread pools prevent blocking
  • Progress bars for long-running operations
  • Automatic cleanup of progress messages

Risk Management

  • Stability scoring system avoids overfitting
  • Multi-window testing (1d, 7d, 30d, 90d, 180d, 365d)
  • Concentration warnings for single-asset risk

🔧 Troubleshooting

"TELEGRAM_BOT_TOKEN not found"

Make sure you've created a .env file with your bot token.

Rate Limit Errors (429)

CoinGecko's free API has rate limits. The system includes automatic retry with exponential backoff.

Wallet Analysis Returns Incomplete Data

  1. Try configuring Covalent API for more complete data
  2. Ensure the wallet address and blockchain match
  3. Check if the blockchain is supported

Negative Sharpe Ratios

This indicates the entire sample period showed losses (bear market). The optimization found the "least bad" option.

Security Notes

  • Never commit your .env file to version control
  • Keep your bot token secret
  • Consider implementing user authentication for production use

License

MIT License

Disclaimer

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.

About

加密货币投资组合优化机器人

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors