Skip to main content

CI Status Coverage PyPI Downloads Python License: GPL v3

LumiBot AI Trading

Turn trading ideas into working strategies.

LumiBot is a free, open-source Python framework for building trading bots. Write your own trading rules, let AI agents make decisions, or combine both. Backtest on historical data, inspect trades and results, and use the same strategy class with a supported broker for paper or live trading.

Full docs: lumibot.lumiwealth.com · Managed cloud: BotSpot.trade · MCP: BotSpot for AI coding agents

Read this in 中文 · Español · Français · Deutsch · 日本語 · 한국어 · Português · Русский

Why LumiBot?

  • Backtest before trading: test on historical data and inspect charts, trades and results.
  • Same strategy for backtesting and trading: keep your strategy class; select a historical data source or a broker runner.
  • Multiple asset classes: stocks, options, futures, forex, crypto and prediction markets through supported brokers.
  • The decision reaches a broker. Inspect the orders, fills and decision records. How execution works.

Three ways to build a strategy

  • Python strategies: write rules, indicators, position sizing and orders in Python.
  • AI-native strategies: write prompts for agents that research, reason and place trades inside your strategy.
  • Hybrid strategies: combine Python rules and AI decisions. For example, Python finds a signal, an AI agent reviews risk, and Python sizes the order.

Python quickstart · AI example · More examples

Run your first AI backtest

The trading rules go in the prompt. Edit system_prompt below to change what the agent does. initialize() creates it once; on_trading_iteration() calls it on every iteration. This example has one agent that makes the trading decisions and places orders.

Use Python 3.10+. This example uses Yahoo daily prices and an OpenAI model; model calls incur charges.

pip install lumibot
export OPENAI_API_KEY="your-openai-api-key"

Save as my_ai_strategy.py:

from datetime import datetime
from lumibot.backtesting import YahooDataBacktesting
from lumibot.strategies import Strategy


class MyAIStrategy(Strategy):
    def initialize(self):
        self.sleeptime = "1D"
        self.agents.create(
            name="trader",
            default_model="openai/gpt-6-luna",
            reasoning_effort="medium",
            allow_trading=True,
            system_prompt=(
                "Trade SPY using its last 20 completed daily bars. "
                "Buy when the latest completed close is above their average; "
                "sell an existing position when it is below. Otherwise hold. "
                "Keep the position at or below 10% of portfolio value. "
                "Check cash, positions and open orders before acting. "
                "No shorting or leverage. Do not duplicate pending orders. "
                "Use only information available as of the strategy time."
            ),
        )

    def on_trading_iteration(self):
        self.agents["trader"].run(
            task_prompt="Review SPY, apply your rules and verify any orders.",
            context={"as_of": self.get_datetime().isoformat()},
        )


if __name__ == "__main__":
    MyAIStrategy.backtest(
        YahooDataBacktesting,
        datetime(2026, 4, 6),
        datetime(2026, 4, 11),
        budget=100_000,
        benchmark_asset="SPY",
    )
python my_ai_strategy.py

Review the decisions, orders and backtest charts. This demonstrates the API; it is not a claim that this trading rule is profitable.

For a complete two-agent team, read the researcher-and-trader example and follow its walkthrough:

python -m lumibot.example_strategies.ai_researcher_trader

Recorded run (made with Gemini): the existing two-agent example has source, decisions and trade records. These are historical results, separate from the single-agent example above.

Backtest a strategy

This is a traditional rules-based strategy: buy 10 AAPL shares on the first iteration and hold. It uses Yahoo historical prices, requires internet access, and makes no AI calls. Use Python 3.10 or later.

pip install lumibot

Save this as my_strategy.py:

from datetime import datetime
from lumibot.strategies import Strategy
from lumibot.backtesting import YahooDataBacktesting

class MyStrategy(Strategy):
    def on_trading_iteration(self):
        if self.first_iteration:
            aapl = self.create_order("AAPL", 10, "buy")
            self.submit_order(aapl)

MyStrategy.backtest(
    YahooDataBacktesting,
    datetime(2023, 1, 1),
    datetime(2024, 1, 1),
)
python my_strategy.py

Run the same strategy with a paper broker

After the backtest works, keep the MyStrategy class and replace the final MyStrategy.backtest(...) call with a broker runner. This example uses Alpaca paper trading:

export ALPACA_API_KEY='your-alpaca-key'
export ALPACA_API_SECRET='your-alpaca-secret'
export ALPACA_IS_PAPER=true
python my_strategy.py
import os
from lumibot.brokers import Alpaca
from lumibot.traders import Trader

ALPACA_CONFIG = {
    "API_KEY": os.environ["ALPACA_API_KEY"],
    "API_SECRET": os.environ["ALPACA_API_SECRET"],
    "PAPER": os.environ.get("ALPACA_IS_PAPER", "true").lower() != "false",
}

broker = Alpaca(ALPACA_CONFIG)
strategy = MyStrategy(broker=broker)

trader = Trader()
trader.add_strategy(strategy)
trader.run_all()

Start with paper trading. When you are ready for live trading, use the same strategy class and switch your broker account/configuration intentionally.

For full setup guides, broker tutorials, AI-agent docs, examples, and deployment notes, use the Lumibot documentation.

Build a hybrid strategy

Use Python for the rules you want to control directly and an agent for the research or decision you want it to handle. A moving-average entry can trigger a read-only risk review; Python checks the structured answer, sizes the position and submits the order. Set that reviewer's allow_trading=False. See the hybrid flow and structured-answer examples.

Connect your AI assistant

Claude, ChatGPT, Codex, Cursor, VS Code or another MCP-compatible assistant can help you write and test any of these strategies. Your coding assistant helps build the code; the agents inside an AI-native strategy run its trading logic.

Connect the free BotSpot MCP for strategy-building skills, free research data and hosted backtests with charts. BotSpot also offers scheduled hosting, a community, a strategy marketplace and broker linking. Hosted usage depends on your plan.

Connect your AI assistant

For local coding help, install the free LumiBot trading skills. For research tools inside a running strategy's agents, see LumiBot strategy agents and lumibot connect botspot.

Explore LumiBot

LumiBot: Python rules or AI agents, historical backtests and broker connections

Want help building your first AI trading bot?

Join the free challenge with Rob Grzesik, creator of LumiBot. Follow the training and learn how to turn an idea into an AI trading strategy.

Build your first AI trading bot with Rob Grzesik. Join the FREE challenge.

Looking for deeper training? Explore the AI Trading Bootcamp. Prefer a hosted workspace? Explore BotSpot.

🌐 Community

Reddit Reddit Community     Discord Discord Community

Project Growth

Live LumiBot Star History Chart

AI Bootcamp

Learn to build, backtest, and deploy trading strategies using AI. Join 2,400+ traders.

Rob Grzesik, creator of LumiBot. Explore the AI Trading Bootcamp

Contributing

We welcome contributions! Here's a video to help you get started: Watch The Video

Steps:

  1. Clone the repository
  2. Create a new branch: git switch -c my-feature
  3. Install dev dependencies: pip install -r requirements_dev.txt && pip install -e .
  4. Make your changes
  5. Run tests: pytest
  6. Create a pull request

Running Tests

pytest                          # Run all tests
pytest tests/test_asset.py      # Run a specific test file
coverage run; coverage report   # Show code coverage

Remote Cache Configuration

Lumibot can mirror its local parquet caches to AWS S3. See docs/remote_cache.md for configuration.

Architecture Documentation

Disclaimer

This software is provided for educational and informational purposes only. It is not financial advice and does not constitute a recommendation to buy or sell any security. Lumibot and BotSpot are not registered broker-dealers or financial advisors. Algorithmic trading involves substantial risk of loss, including the possibility of losses greater than your initial investment. Software bugs and errors can lead to rapid financial losses. Past backtest performance does not guarantee future results. Use this software at your own risk. You are solely responsible for compliance with all applicable laws and regulations regarding the assets you choose to trade.

Affiliate disclosure: some provider links or promo codes, including ThetaData, may support continued Lumibot development.

License

GNU General Public License v3.0 - View License

Contribute

See CONTRIBUTING.md for reproducible bugs, examples, tests, and focused pull requests. If LumiBot is useful to your work, star the repository and share an example with another developer.

Metadata

Release files for lumibot 4.6.31

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Built distribution (wheel)

Table of built distributions (wheels) for lumibot 4.6.31
File Interpreter ABI Platform Actions
lumibot-4.6.31-py3-none-any.whl Python 3 none any Details for lumibot-4.6.31-py3-none-any.whl

Release files / lumibot-4.6.31-py3-none-any.whl

Download URL lumibot-4.6.31-py3-none-any.whl
Size 38.1 MB
Tags Python 3
SHA-256 checksum
How to use checksums
4326f349db85f1868dcc2f85537ff4437994bf59e8cfa353e5a0fee186140b67
BLAKE2b-256 checksum
How to use checksums
163e8108349c0d1cc5a6091853a63b5574cfda2d8da1741215dc0ee823f789ab
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for lumibot 4.6.31

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

4.6.31 This release

1 release file No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page