Skip to content

A rudimentary chatbot created for the Financial Technology and Analytics class at NUS.

Notifications You must be signed in to change notification settings

McKeev/digichat

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

DigiChat - AI-Powered Financial Trading Assistant

A Telegram-based chatbot for real-time stock information and simulated portfolio trading using natural language.

Features

  • πŸ€– 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

Prerequisites

  • Python 3.9 or higher
  • Poetry (for dependency management)
  • Telegram account
  • OpenAI API key
  • Internet connection

Installation

1. Clone the Project

cd /path/to/digichat

2. Install Poetry (if not already installed)

curl -sSL https://install.python-poetry.org | python3 -

3. Install Dependencies

poetry install --no-root

Setup

1. Create a Telegram Bot

  1. Open Telegram and search for @BotFather
  2. Start a chat and send /newbot
  3. Follow the instructions to create your bot
  4. Copy the bot token provided by BotFather

2. Get OpenAI API Key

  1. Visit OpenAI Platform
  2. Create an account or sign in
  3. Navigate to API Keys section
  4. Create a new API key and copy it

3. Configure Environment Variables

Create a .env file in the project root:

cp .env.example .env

Edit .env and add your credentials:

TELEGRAM_BOT_TOKEN=your_telegram_bot_token_here
OPENAI_API_KEY=your_openai_api_key_here
LOG_LEVEL=INFO

Running the Bot

poetry run python main.py

You should see:

πŸ€– DigiChat bot started successfully!
Bot is now running and ready to receive messages.

Usage Examples

Once the bot is running, open Telegram and find your bot. Try these commands:

Stock Information

  • Price of Tesla
  • Show me AAPL
  • How did Microsoft do today?
  • What's the latest on NVDA?

Trading (Simulated)

  • Buy 10 shares of Apple
  • Buy 5 TSLA
  • Purchase 3 shares of Microsoft
  • Sell 2 shares of Apple
  • Sell 5 TSLA

Portfolio Management

  • /portfolio - View all holdings with P&L
  • /transactions - View complete trading history
  • /help - Show available commands
  • /start - Welcome message

Project Structure

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)

How It Works

  1. User sends message β†’ Telegram receives it
  2. OpenAI parses query β†’ Extracts intent (BUY/SELL/INFO) and ticker symbol
  3. Fetch stock data β†’ Yahoo Finance provides real-time pricing
  4. Process transaction β†’ Record to CSV (for buy/sell) or format response (for info)
  5. Calculate P&L β†’ Portfolio tracks average cost and current value
  6. Send response β†’ Formatted message with emojis and Markdown

Technical Details

  • Telegram Bot: python-telegram-bot v22+ with async handlers
  • NLP: OpenAI GPT with structured outputs (Pydantic models)
  • Financial Data: yfinance for real-time market data
  • Portfolio Storage: CSV with schema [date, user, type, asset, qty, price]
  • Logging: Color-coded console output via colorlog

Portfolio Features

Buy Orders

  • Extracts quantity from natural language
  • Fetches current market price
  • Records transaction with timestamp
  • Shows total cost

Sell Orders

  • Validates sufficient holdings
  • Calculates profit/loss on the trade
  • Shows P&L with percentage
  • Updates portfolio automatically

Portfolio View

  • Real-time pricing for all holdings
  • Position-level P&L
  • Average cost basis tracking
  • Total portfolio value and P&L

Transaction History

  • Complete audit trail
  • Last 20 transactions displayed
  • Buy/Sell statistics
  • Date and price details

Development

Running Tests

poetry run python -c "from nlp.query import Query; from finance.data_fetcher import FinanceDataFetcher; print('All imports successful!')"

Project Dependencies

Key packages (managed by Poetry):

  • python-telegram-bot>=22.5 - Telegram bot framework (v22+, not v13)
  • openai>=2.5.0 - OpenAI API with structured outputs
  • yfinance>=0.2.66 - Yahoo Finance data
  • pydantic>=2.12.3 - Data validation for structured outputs
  • colorlog>=6.9.0 - Colored logging

Adding New Dependencies

poetry add package-name

Limitations (Current Phase)

  • 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.)

Troubleshooting

Bot doesn't respond

  • Check if main.py is running
  • Verify TELEGRAM_BOT_TOKEN in .env
  • Check internet connection
  • Review logs in terminal

"OpenAI API error"

  • Verify OPENAI_API_KEY in .env
  • Check API key is valid and has credits
  • Ensure model gpt-5-nano is accessible

Stock data not found

  • 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")

Portfolio calculations seem wrong

  • Check data/portfolio.csv for transaction history
  • Verify buy/sell quantities match expectations
  • P&L is calculated as: (current_price - avg_buy_price) Γ— quantity

Future Enhancements

  • 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

License

This is a proof-of-concept project for educational purposes.

Support

For issues or questions, check the logs in the console output or review the transaction history in data/portfolio.csv.

About

A rudimentary chatbot created for the Financial Technology and Analytics class at NUS.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages