Lumibot: Backtestable AI Trading Teams in Python¶
Build deterministic strategies, AI trading teams, and hybrid Python trading systems that backtest, paper trade, and run live.
Lumibot is a Python framework for building deterministic strategies, AI trading teams, and hybrid trading systems that backtest, paper trade, and run live through real brokers.
Use normal Python for rules, indicators, schedules, position sizing, and risk controls. Add AI agents when you want a strategy to research market data, SEC filings, macro data, news, technical indicators, and account state before making a decision.
The same strategy lifecycle works from historical backtests to paper trading and live trading, so you can inspect behavior before connecting a real account.
Lumibot also supports AI trading agents inside the strategy lifecycle, including DuckDB-powered time-series analysis, external MCP tools, replayable agent runs, and trading permissions that keep research agents read-only.
Features
Works with Crypto, Options, Futures, Stocks, and FOREX!
We're one of the few libraries that supports Algorithmic Options trading and backtesting, as well as many other asset classes.
Built in Live Trading
It's very easy to switch between live trading and backtesting, just a few lines of code to go from backtesting to live trading.
Support For Top Brokers
We support many top broker paths, including Alpaca, Interactive Brokers, Tradier, Schwab, Tradovate, TopstepX futures through ProjectX, Bitunix, and selected CCXT crypto paths such as Coinbase, Kraken, KuCoin, Binance, BitMEX, WEEX, Bybit, and OKX. CCXT support is exchange-specific, not a blanket claim that every CCXT exchange works out of the box.
Easy to Use and Get Started
Install Lumibot, write a normal Python strategy, and run a backtest with free Yahoo data. Add broker credentials only when you are ready for paper or live trading.
Advanced Analytics Out of the Box
We've built a suite of advanced analytics tools that can be used to analyze and optimize your trading strategies, including interactive charts and more.
Event Based Backtesting
Our backtesting engine is event-based so that you can see your strategies run as if they were live trading. You don't have to deal with complicated and confusing vector math to see your strategies run.
AI Trading Teams Built In
Create research, bull, bear, risk, and portfolio-manager agents inside your strategy. Let them query time-series data with DuckDB, attach MCP tools, and replay the exact same agent runs during backtests.Getting Started
AI Trading Agents – Backtest AI Agents with Real External Tools¶
LumiBot is built for AI agents that reason, call external tools, and make trading decisions on every bar during a backtest – then run the exact same code live. This is real agentic backtesting: the LLM is inside the simulation loop, not bolted onto the side.
Backtest AI trading agents with real external data from 20,000+ MCP servers
LLM in the loop on every bar – the agent reasons over point-in-time market state, calls tools, and submits orders
Replay caching makes warm backtest reruns deterministic and fast (zero LLM calls on rerun)
Any LLM provider per agent – use a cheaper model for evidence gathering and a stronger model for debate/trading
Built-in SEC fundamentals and filings – agents can inspect income statements, balance sheets, cash flow, company facts, and annual reports
Built-in FRED macro data – agents can inspect rates, inflation, labor, growth, liquidity, credit spreads, and market-risk series
Trading permissions – research agents can use read-only tools while portfolio-manager agents place orders
Same code for backtest and live – write once, backtest it, deploy it
External MCP servers are just a URL – no local scripts, no npm installs
Key AI agent docs:
AI Trading Agents and Agentic Backtesting – main guide: agentic backtesting framework, MCP trading tools, and competitive positioning
Design Your AI Trading Team – design single-agent, multi-agent, debate, team, and hybrid flows
AI Trading Team Example – one concrete AI trading team example
SEC Fundamentals – SEC fundamentals and filing research tools
FRED Macro Data – FRED macro data tools and point-in-time behavior
Agent Built-In Tools – built-in tools, indicators, and trading permissions
AI Agents Quick Start – quick start with code examples for AI agent backtesting
Canonical AI Agent Demos – three reference demos: news sentiment, macro risk, and M2 liquidity
AI Agent Observability – traces, replay cache, warnings, and debugging workflow
Start with AI Trading Agents and Agentic Backtesting to learn how LumiBot puts AI agents inside the backtest loop with external MCP tools.
Cash Accounting¶
Lumibot supports explicit cash accounting for both backtests and live broker telemetry. Use the strategy cash methods for deposits, withdrawals, direct cash adjustments, and financing setup, then review the resulting cash-adjusted returns in the standard backtest artifacts.
Backtests keep external cashflows out of strategy performance
Live cloud payloads can include normalized broker
cash_eventsListener storage keeps raw normalized events in a dedicated event table
Start with Cash Accounting for the end-to-end guide.
Getting Started¶
After you have installed Lumibot on your computer, you can create a strategy and backtest it using free data available from Yahoo Finance, or use your own data. Here’s how to get started:
Step 1: Install Lumibot¶
Note
Ensure you have installed the latest version of Lumibot. Upgrade using the following command:
pip install lumibot --upgrade
Install the package on your computer:
pip install lumibot
Step 2: Create a Strategy for Backtesting¶
Here’s some code to get you started:
from datetime import datetime
from lumibot.backtesting import YahooDataBacktesting
from lumibot.strategies import Strategy
# A simple strategy that buys AAPL on the first day and holds it
class MyStrategy(Strategy):
def on_trading_iteration(self):
if self.first_iteration:
aapl_price = self.get_last_price("AAPL")
quantity = self.portfolio_value // aapl_price
order = self.create_order("AAPL", quantity, "buy")
self.submit_order(order)
# Pick the dates that you want to start and end your backtest
backtesting_start = datetime(2020, 11, 1)
backtesting_end = datetime(2020, 12, 31)
# Run the backtest
MyStrategy.backtest(
YahooDataBacktesting,
backtesting_start,
backtesting_end,
)
Step 3: Take Your Bot Live¶
Once you have backtested your strategy and understand how it behaves on historical data, you can take your bot to paper trading or live trading. Notice how the strategy code is exactly the same. Here’s an example using Alpaca (you can create a free Paper Trading account here in minutes: https://alpaca.markets/).
from lumibot.brokers import Alpaca
from lumibot.strategies.strategy import Strategy
from lumibot.traders import Trader
ALPACA_CONFIG = {
"API_KEY": "YOUR_ALPACA_API_KEY",
"API_SECRET": "YOUR_ALPACA_SECRET",
"PAPER": True # Set to True for paper trading, False for live trading
}
# A simple strategy that buys AAPL on the first day and holds it
class MyStrategy(Strategy):
def on_trading_iteration(self):
if self.first_iteration:
aapl_price = self.get_last_price("AAPL")
quantity = self.portfolio_value // aapl_price
order = self.create_order("AAPL", quantity, "buy")
self.submit_order(order)
trader = Trader()
broker = Alpaca(ALPACA_CONFIG)
strategy = MyStrategy(broker=broker)
# Run the strategy live
trader.add_strategy(strategy)
trader.run_all()
Important
Remember to start with a paper trading account to ensure everything works as expected before moving to live trading.
All Together¶
Here’s the complete code:
from datetime import datetime
from lumibot.backtesting import YahooDataBacktesting
from lumibot.brokers import Alpaca
from lumibot.strategies import Strategy
from lumibot.traders import Trader
ALPACA_CONFIG = {
"API_KEY": "YOUR_ALPACA_API_KEY",
"API_SECRET": "YOUR_ALPACA_SECRET",
"PAPER": True
}
class MyStrategy(Strategy):
def on_trading_iteration(self):
if self.first_iteration:
aapl_price = self.get_last_price("AAPL")
quantity = self.portfolio_value // aapl_price
order = self.create_order("AAPL", quantity, "buy")
self.submit_order(order)
trader = Trader()
broker = Alpaca(ALPACA_CONFIG)
strategy = MyStrategy(broker=broker)
# Run the strategy live
trader.add_strategy(strategy)
trader.run_all()
Or you can download the file here: https://github.com/Lumiwealth/lumibot/blob/dev/lumibot/example_strategies/simple_start_single_file.py
Additional Resources¶
If you would like to learn how to modify your strategies, we suggest that you first learn about Lifecycle Methods, then Strategy Methods, and Strategy Properties. You can find the documentation for these in the menu, with the main pages describing what they are, then the sub-pages describing each method and property individually.
We also have some more sample code that you can check out here: https://github.com/Lumiwealth/lumibot/tree/dev/lumibot/example_strategies
Next, explore the AI agent docs if you want a strategy that researches evidence, debates bull and bear cases, checks risk, and trades from the same Python lifecycle.
Need Extra Help?¶
BotSpot is the hosted cloud built around Lumibot. Use it when you want Lumibot-tuned AI strategy generation, hosted data, parallel backtests, broker connections, monitoring, alerts, audit history, and cheaper scheduled deployment without maintaining your own trading server.
You can start from a strategy idea, a sample Lumibot strategy, or an existing bot, then inspect the backtest artifacts before moving to paper or live trading.
Why Run Lumibot on BotSpot?
BotSpot removes the infrastructure work around the strategy:
- Hosted backtesting data and artifacts
- Parallel backtests for strategy variants
- Broker connections and scheduled runs
- Charts, logs, alerts, account checks, and kill switches
- BotSpot MCP tools for Codex, Claude Code, Cursor, and other coding agents
Important
Build Trading Bots with AI
Lumibot is easier to run on BotSpot because the strategy code, hosted data, backtests, broker connections, deployment, monitoring, and AI workflow are already connected.
Backtesting data included: run supported backtests without sourcing every vendor and local data file yourself.
Cheaper deployment at scale: schedule periodic bots on managed Lumibot infrastructure instead of paying for always-on servers per strategy.
Lumibot-tuned AI: use prompts and workflows built for Lumibot code, backtests, artifacts, brokers, and deployment.
MCP for coding agents: let Codex, Claude Code, Cursor, and other agents launch backtests, inspect artifacts, and prepare deployment.
Marketplace and strategy library: browse, clone, adapt, run, or publish strategies when the author allows it.
Observability and control: inspect charts, trades, logs, audit history, alerts, account checks, and kill switches.
Work from anywhere: use the web app, your phone, Telegram, Discord, Claude, ChatGPT, or BotSpot MCP.
Try a sample Lumibot strategy on BotSpot: https://botspot.trade
Table of Contents¶
- Home
- Build Bots with AI
- BotSpot MCP Integration
- GitHub
- Getting Started
- Imports and Startup
- AI Trading Agents and Agentic Backtesting
- AI Agents Quick Start
- Design Your AI Trading Team
- Agent Built-In Tools
- AI Trading Team Example
- Canonical AI Agent Demos
- AI Agent Observability
- Agent Memory
- Agent Notifications
- Why This Is Different
- Quick Start
- How
@agent_toolWorks - External Data Patterns
- Built-in Tools
- System Prompts
- Agent Handoffs
- DuckDB and Time-Series Data
- Replay Cache
- Observability
- Canonical Demos
- Frequently Asked Questions
- Error Handling and Reliability
- Cash Accounting
- Lifecycle Methods
- Summary
- def initialize
- def on_trading_iteration
- def before_market_opens
- def before_starting_trading
- def before_market_closes
- def after_market_closes
- def on_abrupt_closing
- def on_bot_crash
- def trace_stats
- def tearsheet_custom_metrics
- def on_new_order
- def on_partially_filled_order
- def on_filled_order
- def on_canceled_order
- def on_parameters_updated
- Strategy Methods
- Strategy Properties
- Entities
- Indicators
- SEC Fundamentals
- FRED Macro Data
- Backtesting
- Brokers
- Reference
- Code Examples
- Deployment Guide
- Option A — Deploy on BotSpot (Recommended)
- Option B — Self-hosted Deployment (Render or Replit)
- Example Strategy for Deployment
- Choosing Your Self-hosted Platform
- Deploying to Render
- Deploying to Replit
- Secrets Configuration
- Broker Configuration
- Tradier Configuration
- Tradovate Configuration
- Alpaca Configuration
- Coinbase Configuration
- Kraken Configuration
- Additional CCXT Exchange Examples
- Interactive Brokers Configuration
- Interactive Brokers-Legacy Configuration
- Schwab Configuration
- Bitunix Configuration
- DataBento Configuration
- ProjectX Configuration
- General Environment Variables
- Final Steps
- Conclusion
- Common Mistakes and How to Avoid Them
- Frequently Asked Questions (FAQ)
- Get Pre-Built Strategies