xuan13hao
ai_qt_stock
Python

An AI-powered quantitative trading platform for US stocks using Alpaca Markets API and DeepSeek LLM for intelligent trading decisions.

Last updated Feb 5, 2026
10
Stars
0
Forks
0
Issues
0
Stars/day
Attention Score
20
Language breakdown
Python 100.0%
โ–ธ Files click to expand
README

Quantitative Trading Platform with Hard Risk Control

An AI-powered quantitative trading platform for US stocks using Alpaca Markets API and DeepSeek LLM for intelligent trading decisions.

๐Ÿ“น Project Demo

Watch the demo video to see the platform in action:

Watch the demo

๐Ÿš€ Features

Core Functionality

  • ๐Ÿ’ฐ Account Management - Real-time account information, portfolio value, buying power, and equity tracking
  • ๐Ÿ“Š Position Management - View all positions with real-time P&L, entry prices, and market values
  • โšก Order Management - Place buy/sell orders with multiple order types (market, limit, stop, stop-limit)
  • ๐Ÿค– AI Trading Decisions - DeepSeek LLM-powered analysis providing buy/sell/hold recommendations with confidence scores
  • ๐ŸŽฏ Strategy Management - Create, manage, and execute trading strategies with automated monitoring
  • ๐Ÿ”„ Auto Trading - Automated trading execution based on AI decisions and strategy rules
  • ๐Ÿ›ก๏ธ Risk Management - Stop loss and take profit monitoring with automatic alerts
  • ๐Ÿ“‹ Trade Records - Complete history of all trades and trading signals
  • โš™๏ธ Configuration - Easy web-based configuration for API keys and trading settings

Trading Modes

  • ๐ŸŽฎ Local Simulator (Default)
- No API required, works out of the box - Initial capital: $100,000 - Completely virtual, risk-free for testing - Perfect for learning and strategy development
  • ๐Ÿ“ Alpaca Paper Trading
- Uses Alpaca Paper Trading API - Virtual money, real market conditions - Test strategies with realistic market data - Requires Alpaca account (free)
  • ๐Ÿ’ต Live Trading
- Real money, real orders - Full Alpaca Markets integration - Use with caution - real financial risk

๐Ÿ“‹ Requirements

  • Python 3.8+ (recommended 3.12)
  • Stable internet connection
  • DeepSeek API Key (for AI features)
  • Alpaca API Key (optional, for paper/live trading)

๐Ÿ”ง Installation

1. Clone the Repository

git clone https://github.com/xuan13hao/aiqtstock.git
cd aiqtstock

Edit .env file and configure your API keys:

# DeepSeek API (Required for AI features)
DEEPSEEKAPIKEY=yourdeepseekapikeyhere
DEEPSEEKBASEURL=https://api.deepseek.com/v1

Alpaca API (Optional, for paper/live trading)

ALPACA_ENABLED=false ALPACAAPIKEY=youralpacaapikeyhere ALPACAAPISECRET=youralpacaapisecrethere ALPACA_PAPER=true # true for paper trading, false for live trading

2. Run the Application

# Using the run script
python run.py

Or directly with Streamlit

streamlit run app.py --server.port 8503

๐Ÿณ Docker Deployment

Using Docker Compose (Recommended)

docker-compose up -d

Using Dockerfile

# Build the image
docker build -t alpaca-trading-platform .

Run the container

docker run -d -p 8503:8501 \ -v $(pwd)/.env:/app/.env \ --name alpaca-trading \ alpaca-trading-platform

๐Ÿ“– Usage Guide

Getting Started

  • Configure API Keys
- Navigate to "โš™๏ธ Configuration" in the sidebar - Enter your API keys (see Getting API Keys section below) - Click "๐Ÿ’พ Save All Configuration"
  • View Account Information
- Click "๐Ÿ’ฐ Account" in the sidebar - View your portfolio value, buying power, cash, and equity - Check account status and trading mode
  • Place Orders
- Navigate to "โšก Trading" - Choose Buy or Sell tab - Enter stock symbol (e.g., AAPL, TSLA, MSFT) - Select order type (market, limit, stop, stop-limit) - Enter quantity and submit order

AI Trading Decisions

  • Get AI Recommendation
- Navigate to "๐Ÿค– AI Decision" or use the "๐Ÿค– AI Decision" tab in Trading - Enter a stock symbol - Click "๐Ÿค– Get AI Decision" - Review the AI analysis: - Action (BUY/SELL/HOLD) - Confidence level - Risk assessment - Reasoning and analysis - Trading parameters (position size, stop loss, take profit) - Key price levels (support, resistance)
  • Auto Execute Trade
- Enable "Auto Execute Trade" checkbox - Review the decision details - Click "Execute AI Decision" to place the order automatically

Strategy Management

  • Add Strategy Task
- Navigate to "๐ŸŽฏ Strategies" - Click "โž• Add New Strategy Task" - Select strategy type (aidecision, lowprice_bull, custom) - Enter stock symbol - Configure check interval and auto trading - Click "Add Strategy Task"
  • Auto Trading
- Enable "AI Auto Trading" in the Strategies page - Start auto trading service - System will automatically check and execute trades based on strategies - Configure check interval (default: 300 seconds)
  • Stop Loss / Take Profit
- Navigate to "๐Ÿ›ก๏ธ Stop Loss/Take Profit" tab - Click "๐Ÿ” Check Stop Loss/Take Profit" - System will check all positions and alert if triggers are hit - Manually execute sell orders from the alert list

Order Types

  • Market Order - Execute immediately at current market price
  • Limit Order - Execute only at specified price or better
  • Stop Order - Trigger when price reaches stop price
  • Stop-Limit Order - Combination of stop and limit orders

Time in Force Options

  • Day - Order expires at end of trading day
  • GTC - Good till canceled (remains active until filled or canceled)
  • IOC - Immediate or cancel (fill immediately or cancel)
  • FOK - Fill or kill (fill completely or cancel)

๐Ÿ”‘ Getting API Keys

DeepSeek API Key

  • Visit https://platform.deepseek.com
  • Register/Login to your account
  • Navigate to API key management
  • Create a new API key
  • Copy the key and paste it into the configuration

Alpaca API Keys

  • Visit https://alpaca.markets
  • Sign up for a free account
  • Go to Dashboard โ†’ API Keys
  • Create new API key (for paper trading)
  • Copy Key ID and Secret Key
  • Paste into configuration
Important: Start with paper trading to test strategies before using live trading!

๐Ÿ“ Project Structure

aiagents-stock/
โ”œโ”€โ”€ app.py                      # Main Streamlit application
โ”œโ”€โ”€ usstocktrading.py         # Alpaca trading interface
โ”œโ”€โ”€ alpacaaidecision.py       # AI decision engine (DeepSeek)
โ”œโ”€โ”€ alpacastrategymanager.py  # Strategy management
โ”œโ”€โ”€ alpacaautotrader.py       # Auto trading service
โ”œโ”€โ”€ config_manager.py           # Configuration management
โ”œโ”€โ”€ run.py                      # Application launcher
โ”œโ”€โ”€ requirements.txt            # Python dependencies
โ”œโ”€โ”€ env_example.txt             # Environment configuration template
โ”œโ”€โ”€ Dockerfile                  # Docker image definition
โ”œโ”€โ”€ docker-compose.yml          # Docker Compose configuration
โ””โ”€โ”€ README.md                   # This file

๐Ÿ› ๏ธ Technology Stack

  • Frontend: Streamlit
  • Trading API: Alpaca Markets API
  • AI/LLM: DeepSeek API
  • Data Source: Yahoo Finance (yfinance)
  • Technical Analysis: TA-Lib (ta library)
  • Database: SQLite
  • Language: Python 3.8+

โš ๏ธ Important Notes

Risk Warning

  • Stock trading involves real financial risk
  • AI recommendations are for reference only, not investment advice
  • Always test strategies with paper trading first
  • Never invest more than you can afford to lose
  • Use stop loss orders to manage risk
  • Past performance does not guarantee future results

Best Practices

  • Start with Simulator - Use the local simulator to learn the platform
  • Test with Paper Trading - Use Alpaca paper trading to test strategies
  • Start Small - Begin with small position sizes
  • Monitor Positions - Regularly check your positions and account
  • Understand Orders - Learn different order types before trading
  • Keep Records - Review trade history to improve strategies

๐Ÿ“œ Trading Policy

Risk Management Rules

  • Maximum Position Size
- Single position should not exceed 20% of total account equity - Recommended position size: 5-10% of account equity per trade - For new traders, limit to 2-5% per position
  • Portfolio Diversification
- Maintain at least 5-10 different positions when possible - Avoid over-concentration in a single sector or stock - Maximum 30% of portfolio in any single sector
  • Maximum Daily Loss Limit
- Set a daily loss limit (recommended: 2-5% of account equity) - Stop trading for the day if daily loss limit is reached - Review and adjust strategy before resuming trading
  • Maximum Drawdown Limit
- Set an account drawdown limit (recommended: 10-20% from peak equity) - Reduce position sizes or pause trading if drawdown limit is reached - Reassess trading strategy and risk parameters

Stop Loss Requirements

  • Mandatory Stop Loss
- All positions must have a stop loss order set - Stop loss should be set immediately after entering a position - Use the platform's Stop Loss/Take Profit monitoring feature
  • Stop Loss Placement
- Stop loss should be based on technical analysis (support levels, ATR, etc.) - Typical stop loss: 2-5% below entry price for long positions - Adjust stop loss based on volatility and time frame
  • Trailing Stop Loss
- Consider using trailing stop loss for profitable positions - Lock in profits while allowing for continued upside - Adjust trailing stop as position becomes more profitable

Position Management

  • Entry Rules
- Verify sufficient buying power before placing orders - Confirm order details (symbol, quantity, order type) before submission
  • Exit Rules
- Exit positions that hit stop loss immediately - Take profits at predetermined levels (take profit orders) - Review and exit positions that no longer meet entry criteria
  • Position Monitoring
- Check all positions at least once per trading day - Monitor positions for news or events that may affect price - Use the platform's position management features regularly

AI Decision Usage Policy

  • AI Recommendations
- AI recommendations are tools for analysis, not guaranteed outcomes - Always review AI analysis before executing trades - Consider AI confidence levels when making decisions - Combine AI recommendations with your own research
  • Auto Execution
- Use auto-execution feature with caution - Review all AI decision details before enabling auto-execution - Start with manual execution to understand AI behavior - Monitor auto-executed trades closely
  • AI Limitations
- AI cannot predict market movements with certainty - AI analysis is based on historical data and patterns - Market conditions can change rapidly, making AI recommendations outdated - Always use stop loss orders even with AI recommendations

Auto Trading Policy

  • Auto Trading Activation
- Only enable auto trading after thorough testing in simulator mode - Test strategies with paper trading for at least 2-4 weeks - Start with small position sizes when first enabling auto trading - Monitor auto trading activity daily
  • Strategy Requirements
- All auto trading strategies must include stop loss rules - Set maximum position size limits for each strategy - Define clear entry and exit criteria - Review and update strategies regularly
  • Auto Trading Monitoring
- Check auto trading logs and trade history regularly - Review strategy performance weekly - Disable auto trading if performance degrades significantly - Adjust strategy parameters based on market conditions

Trading Hours Policy

  • Regular Market Hours (Recommended)
- Primary trading should occur during regular market hours: 9:30 AM - 4:00 PM ET - Better liquidity and tighter spreads during regular hours - Most reliable execution during regular market hours
  • Extended Hours Trading
- Pre-market (4:00 AM - 9:30 AM ET) and after-hours (4:00 PM - 8:00 PM ET) have: - Lower liquidity - Wider bid-ask spreads - Higher volatility - Use extended hours trading with caution and smaller position sizes - Consider using limit orders instead of market orders during extended hours
  • Market Closures
- Do not place orders when markets are closed - Be aware of market holidays and early closures - GTC (Good Till Canceled) orders will execute when markets reopen

Account Protection

  • API Key Security
- Never share API keys or credentials - Use environment variables or secure configuration files - Regularly rotate API keys for security
  • Account Monitoring
- Monitor account status and buying power daily - Check for any account restrictions or warnings - Verify all trades executed as intended - Review account statements regularly
  • Capital Preservation
- Maintain a cash reserve (recommended: 20-30% of account) - Avoid using margin unless you understand the risks - Set account-level risk limits

Compliance and Regulatory

  • Regulatory Compliance
- Ensure compliance with all applicable securities regulations - Understand pattern day trader (PDT) rules if applicable - Comply with tax reporting requirements - Keep accurate records of all trades
  • Record Keeping
- Maintain records of all trades and decisions - Document strategy changes and rationale - Keep logs of AI recommendations and executions - Review trade history regularly for learning
  • Disclosure Requirements
- This platform is for educational and research purposes - Not registered as an investment advisor - Users are responsible for their own trading decisions

Prohibited Practices

  • Do Not:
- Ignore stop loss orders or risk management rules - Over-leverage your account - Trade based solely on AI recommendations without research - Disable risk management features - Trade during high volatility without understanding risks - Share API keys or account credentials
  • Restrictions:
- No trading of securities you don't understand - No trading based on insider information - No manipulation of market prices - No violation of securities regulations

Policy Updates

  • Trading policies may be updated periodically
  • Users are responsible for reviewing and understanding current policies
  • Policy violations may result in account restrictions
  • Contact maintainers for questions about trading policies
Remember: These policies are guidelines to help manage risk. Adapt them to your risk tolerance and trading experience. When in doubt, err on the side of caution.

๐Ÿ› Troubleshooting

Common Issues

  • API Key Errors
- Verify API keys are correct in configuration - Check API key has sufficient balance/permissions - Ensure .env file exists and is properly formatted
  • Connection Issues
- Check internet connection - Verify Alpaca API is accessible - Check firewall settings
  • Order Execution Failures
- Verify trading hours (see Trading Policy section) - Check account has sufficient buying power - Verify stock symbol is correct - Check account status is ACTIVE
  • AI Decision Failures
- Verify DeepSeek API key is valid - Check API account has sufficient balance - Ensure network connection is stable
  • Docker Issues
- Check Docker is running: docker ps - View logs: docker-compose logs -f - Verify .env file is mounted correctly - Check port 8503 is not in use

๐Ÿ“ License

MIT License

Commercial Use

โš ๏ธ Important: Commercial use of this project requires explicit permission from the author. If you intend to use this software for commercial purposes, please contact the author for authorization before proceeding.

For commercial licensing inquiries, please open an issue on GitHub or contact the maintainers.

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit issues or pull requests.

๐Ÿ“ง Support

For questions or issues, please open an issue on GitHub or contact the maintainers.


Disclaimer: This platform is for educational and research purposes only. Stock trading involves substantial risk of loss. AI recommendations should not be considered as investment advice. Always conduct your own research and consult with financial advisors before making investment decisions.

๐Ÿ”— More in this category

ยฉ 2026 GitRepoTrend ยท xuan13hao/ai_qt_stock ยท Updated daily from GitHub