Spaces:
Runtime error
Runtime error
File size: 8,207 Bytes
ff1f271 63bad2b ff1f271 63bad2b bb208f2 63bad2b ff1f271 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 | ---
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
```bash
git clone <repository-url>
cd LLM-fintech
```
### 2. Install Dependencies
```bash
pip install -r requirements.txt
```
### 3. Environment Variables
Create a `.env` file in the project root with your LLM API keys:
```env
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
```bash
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`
```bash
# 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
```bash
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](https://www.gradio.app/guides/deploying-your-app).
## 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
|