A Telegram-based chatbot for real-time stock information and simulated portfolio trading using natural language.
- π€ Natural Language Processing - Powered by OpenAI for intelligent query understanding
- π Real-time Stock Data - Live prices via Yahoo Finance
- π° Simulated Trading - Buy and sell stocks with natural language commands
- π Portfolio Management - Track holdings with real-time P&L calculations
- π Transaction History - Complete audit trail of all trades
- π― Smart Ticker Resolution - Works with company names (Apple) or symbols (AAPL)
- πΎ CSV Database - Lightweight sheet-based portfolio storage
- Python 3.9 or higher
- Poetry (for dependency management)
- Telegram account
- OpenAI API key
- Internet connection
cd /path/to/digichatcurl -sSL https://install.python-poetry.org | python3 -poetry install --no-root- Open Telegram and search for
@BotFather - Start a chat and send
/newbot - Follow the instructions to create your bot
- Copy the bot token provided by BotFather
- Visit OpenAI Platform
- Create an account or sign in
- Navigate to API Keys section
- Create a new API key and copy it
Create a .env file in the project root:
cp .env.example .envEdit .env and add your credentials:
TELEGRAM_BOT_TOKEN=your_telegram_bot_token_here
OPENAI_API_KEY=your_openai_api_key_here
LOG_LEVEL=INFO
poetry run python main.pyYou should see:
π€ DigiChat bot started successfully!
Bot is now running and ready to receive messages.
Once the bot is running, open Telegram and find your bot. Try these commands:
Price of TeslaShow me AAPLHow did Microsoft do today?What's the latest on NVDA?
Buy 10 shares of AppleBuy 5 TSLAPurchase 3 shares of MicrosoftSell 2 shares of AppleSell 5 TSLA
/portfolio- View all holdings with P&L/transactions- View complete trading history/help- Show available commands/start- Welcome message
digichat/
βββ main.py # Entry point
βββ pyproject.toml # Poetry dependencies
βββ .env # Environment variables (not in git)
β
βββ bot/ # Telegram bot interface
β βββ telegram_bot.py # Bot setup and configuration
β βββ handlers.py # Message and command handlers
β
βββ nlp/ # Natural language processing
β βββ query.py # OpenAI-powered query parser
β
βββ finance/ # Financial data and portfolio
β βββ data_fetcher.py # Yahoo Finance integration
β βββ portfolio_db.py # CSV-based portfolio database
β
βββ utils/ # Utilities
β βββ logger.py # Colored logging setup
β
βββ data/ # Portfolio data storage
βββ portfolio.csv # User transactions (auto-created)
- User sends message β Telegram receives it
- OpenAI parses query β Extracts intent (BUY/SELL/INFO) and ticker symbol
- Fetch stock data β Yahoo Finance provides real-time pricing
- Process transaction β Record to CSV (for buy/sell) or format response (for info)
- Calculate P&L β Portfolio tracks average cost and current value
- Send response β Formatted message with emojis and Markdown
- Telegram Bot:
python-telegram-botv22+ with async handlers - NLP: OpenAI GPT with structured outputs (Pydantic models)
- Financial Data:
yfinancefor real-time market data - Portfolio Storage: CSV with schema
[date, user, type, asset, qty, price] - Logging: Color-coded console output via
colorlog
- Extracts quantity from natural language
- Fetches current market price
- Records transaction with timestamp
- Shows total cost
- Validates sufficient holdings
- Calculates profit/loss on the trade
- Shows P&L with percentage
- Updates portfolio automatically
- Real-time pricing for all holdings
- Position-level P&L
- Average cost basis tracking
- Total portfolio value and P&L
- Complete audit trail
- Last 20 transactions displayed
- Buy/Sell statistics
- Date and price details
poetry run python -c "from nlp.query import Query; from finance.data_fetcher import FinanceDataFetcher; print('All imports successful!')"Key packages (managed by Poetry):
python-telegram-bot>=22.5- Telegram bot framework (v22+, not v13)openai>=2.5.0- OpenAI API with structured outputsyfinance>=0.2.66- Yahoo Finance datapydantic>=2.12.3- Data validation for structured outputscolorlog>=6.9.0- Colored logging
poetry add package-name- Simulated trading only (no real brokerage integration)
- No user authentication beyond Telegram ID
- Single-user portfolio per Telegram account
- Limited to stocks available on Yahoo Finance
- No advanced order types (limit orders, stop loss, etc.)
- Check if
main.pyis running - Verify
TELEGRAM_BOT_TOKENin.env - Check internet connection
- Review logs in terminal
- Verify
OPENAI_API_KEYin.env - Check API key is valid and has credits
- Ensure model
gpt-5-nanois accessible
- Verify ticker symbol is correct
- Some stocks may not be available on Yahoo Finance
- Try using the exact ticker symbol (e.g., "AAPL" instead of "Apple")
- Check
data/portfolio.csvfor transaction history - Verify buy/sell quantities match expectations
- P&L is calculated as: (current_price - avg_buy_price) Γ quantity
- Real brokerage integration
- Advanced order types (limit, stop-loss, trailing stop)
- Technical analysis indicators
- News sentiment analysis
- Price alerts and notifications
- Multi-ticker portfolio analytics
- Export portfolio reports
This is a proof-of-concept project for educational purposes.
For issues or questions, check the logs in the console output or review the transaction history in data/portfolio.csv.