JuanFuriaz's picture
Upload folder using huggingface_hub
bb208f2 verified
|
Raw
History Blame Contribute Delete
8.21 kB

A newer version of the Gradio SDK is available: 6.26.0

Upgrade
metadata
title: StrategyGenerator
app_file: app.py
sdk: gradio
sdk_version: 5.47.2

Financial Strategy Generator

A Gradio web application that generates Python trading strategies from natural language descriptions using Large Language Models (LLMs). The generated strategies can be instantly backtested using the Backtrader library with real market data from Yahoo Finance.

Overview

This application allows you to:

  • Describe trading strategies in plain English (e.g., "Buy when 10-day SMA crosses above 100-day SMA")
  • Generate Python code automatically using state-of-the-art LLMs
  • Backtest strategies immediately in the GUI with configurable parameters
  • Visualize results with interactive charts and detailed transaction logs
  • Export data for further analysis

Key Features

  • πŸ€– Multi-LLM Support: Choose from GPT, Claude, Deepseek, Gemini, or Grok4
  • πŸ“Š Financial Indicators: Supports SMA, MACD, RSI, ATR, and more via Backtrader
  • πŸ“ˆ Interactive Backtesting: Real-time strategy testing with Yahoo Finance data
  • πŸ’Ύ Data Caching: Automatic caching to avoid redundant downloads
  • πŸ“‰ Visual Analytics: Charts, transaction tables, and trade performance metrics
  • βš™οΈ Configurable Parameters: Customize capital, commission, slippage, and more
  • 🎯 Multiple Timeframes: Support for 1m, 5m, 15m, 1h, 1d intervals
  • πŸ“₯ Export Capabilities: Download generated code and CSV reports

Requirements

  • Python 3.12
  • Dependencies listed in requirements.txt.

Installation & Setup

1. Clone the Repository

git clone <repository-url>
cd LLM-fintech

2. Install Dependencies

pip install -r requirements.txt

3. Environment Variables

Create a .env file in the project root with your LLM API keys:

OPENAI_API_KEY=your_openai_key_here
ANTHROPIC_API_KEY=your_anthropic_key_here
DEEPSEEK_API_KEY=your_deepseek_key_here
GOOGLE_API_KEY=your_google_key_here
XAI_API_KEY=your_grok_key_here

# Optional: FMP key for extracting date
FMP_API_KEY=your_fmp_key_here
# Optional: For HuggingFace local mode
HF_TOKEN=your_huggingface_token_here

# Optional: Override default models (see config/var_dev.yaml for defaults)
OPENAI_MODEL=gpt-4
CLAUDE_MODEL=claude-sonnet-4-20250514
DEEPSEEK_MODEL=deepseek-reasoner
GEMINI_MODEL=gemini-2.5-flash
GROK4_MODEL=grok-4-fast-reasoning

4. Configuration

The application uses config/var_dev.yaml for default settings:

  • Market/ticker mappings (e.g., "S&P 500 ETF" β†’ "SPY")
  • Default LLM model names
  • Backtesting parameters (initial capital, commission, slippage)
  • Data intervals and periods

You can modify this file to customize defaults without changing code.

Running Locally

Start the Application

python app.py

The Gradio interface will automatically open in your default browser. The app runs on http://127.0.0.1:7860 by default.

Using the Interface

  1. Generate Strategy:

    • Select your preferred LLM model from the dropdown
    • Enter a natural language description of your trading strategy
    • Click "Generate Strategy" to create Python code
  2. Configure Backtesting:

    • Choose a stock/ETF or enter a custom ticker symbol
    • Set initial capital, commission, and slippage
    • Select date range and data interval
    • Optionally enable adjusted prices (for dividends/splits)
  3. Run Backtest:

    • Click "Run Python Code" to execute the strategy
    • View results in the Python result panel
    • Check the "Charts" tab for visualizations
    • Review "Transactions" and "Trades" tabs for detailed logs
  4. Export Results:

    • Download generated strategy code as a .py file
    • Export transaction and trade data as CSV files

Gradio Deployment

To deploy this application to Gradio's hosting service:

1. Install uv

# On macOS/Linux
curl -LsSf https://astral.sh/uv/install.sh | sh

# On Windows
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

# Or via pip
pip install uv

2. Deploy

uv gradio deploy

This command will:

  • Package your application
  • Upload it to Gradio's servers
  • Provide a public URL for your deployed app

Note: Make sure your .env file is configured properly, or set environment variables in your deployment environment for API keys.

For more deployment options and configurations, refer to Gradio Deployment Documentation.

Project Structure

LLM-fintech/
β”œβ”€β”€ app.py                 # Main Gradio application interface
β”œβ”€β”€ strategy_generator.py  # LLM integration and strategy code generation
β”œβ”€β”€ bt_utils.py           # Backtesting engine, data fetching, and plotting
β”œβ”€β”€ bt_strategies.py      # Example strategy classes (reference implementations)
β”œβ”€β”€ bt_testing.py         # Standalone backtesting script (for testing)
β”œβ”€β”€ utils.py              # Helper functions (validation, file operations)
β”œβ”€β”€ config/
β”‚   └── var_dev.yaml      # Configuration file (markets, models, defaults)
β”œβ”€β”€ data_cache/           # Cached Yahoo Finance data (auto-generated)
β”œβ”€β”€ requirements.txt      # Python dependencies
└── README.md            # This file

Configuration Details

Market/Ticker Mappings

The config/var_dev.yaml file contains mappings between friendly names and ticker symbols. You can:

  • Use predefined markets from the dropdown (e.g., "S&P 500 ETF")
  • Enter any valid Yahoo Finance ticker symbol directly
  • Add custom mappings by editing the YAML file

Supported Data Intervals

  • Intraday: 1m, 2m, 5m, 15m, 30m, 1h
  • Daily: 1d

Note: Intraday data has limitations on historical range (Yahoo Finance restrictions).

Backtesting Parameters

  • Initial Capital: Starting portfolio value (default: $10,000)
  • Commission: Per-share trading commission (default: $0.005)
  • Slippage: Percentage of price applied as slippage (default: 0.01%)
  • Adjusted Prices: Use dividend/split-adjusted prices (recommended: enabled)

Supported Financial Indicators

The generated strategies can use any Backtrader indicator, including:

  • Moving Averages: SMA, EMA, WMA
  • Momentum: RSI, Stochastic, MACD
  • Volatility: ATR, Bollinger Bands
  • Volume: Volume indicators
  • Custom Indicators: Any Backtrader-compatible indicator

Example strategy descriptions:

  • "Go long when RSI crosses above 30 and 10-day SMA is above 50-day SMA"
  • "Buy when MACD line crosses above signal line, exit when it crosses below"
  • "Use ATR for position sizing, enter on golden cross with RSI confirmation"

Data Caching

The application automatically caches downloaded market data in the data_cache/ directory. This:

  • Speeds up subsequent backtests
  • Reduces API calls to Yahoo Finance
  • Caches are keyed by ticker, interval, date range, and adjustment settings

Cache files are automatically managed and will be re-downloaded if parameters change.

Troubleshooting

Common Issues

  1. API Key Errors: Ensure all required API keys are set in your .env file
  2. No Data Available: Check that your ticker symbol is valid and date range is appropriate
  3. Code Generation Fails: Try a different LLM model or refine your strategy description
  4. Chart Not Displaying: Ensure matplotlib backend is set correctly (handled automatically)

Browser Compatibility

The Gradio interface works best on modern browsers (Chrome, Firefox, Safari, Edge). If charts don't display, try:

  • Clearing browser cache
  • Using a different browser
  • Checking browser console for errors

Notes

  • Generated code follows Backtrader's strategy pattern and best practices
  • Strategies must inherit from bt.Strategy and implement __init__ and next() methods
  • The app automatically wraps generated code with backtesting execution logic
  • Data is fetched from Yahoo Finance with automatic handling of market hours and holidays

Version

0.0.2: added FMP extraction, replay mode and database reading for intraday

0.0.1: First working version

License

Needs to be done

Contributing

Next Steps