### Basic Backtest Setup with Polygon.io Source: https://github.com/lumiwealth/lumibot/blob/dev/llms-full.txt This example demonstrates the initial setup for a backtest using Polygon.io as the data source. Ensure you replace 'YOUR_POLYGON_API_KEY' with your actual API key. ```python from datetime import datetime from lumibot.backtesting import PolygonDataBacktesting from lumibot.strategies import Strategy class MyStrategy(Strategy): parameters = { "symbol": "AAPL", } def initialize(self): ``` -------------------------------- ### Run a Simple Buy-and-Hold Backtest Source: https://github.com/lumiwealth/lumibot/blob/dev/README.md Execute a basic buy-and-hold strategy using Lumibot's example strategies. This is a straightforward way to start a backtest. ```bash python -m lumibot.example_strategies.stock_buy_and_hold ``` -------------------------------- ### Implement Initialize and on_trading_iteration Methods Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/lifecycle_methods.summary.rst This example demonstrates implementing both the 'initialize' and 'on_trading_iteration' methods. The 'initialize' method is called once at the beginning of the strategy's lifecycle, before any trading iterations, and is used for setup. 'on_trading_iteration' contains the core trading logic. ```python from lumibot.strategies import Strategy class MyStrategy(Strategy): def initialize(self): # Initialize your strategy here pass def on_trading_iteration(self): # Implement your trading logic here pass ``` -------------------------------- ### Basic DataBento Backtesting Setup Source: https://github.com/lumiwealth/lumibot/blob/dev/llms-full.txt Demonstrates how to set up and use DataBento for backtesting within Lumibot. This includes installing dependencies, configuring the API key, and defining a strategy that fetches historical data. ```python import os os.environ['DATABENTO_API_KEY'] = 'your_api_key_here' ``` ```python from lumibot.strategies import Strategy from lumibot.entities import Asset from lumibot.backtesting import DataBentoDataBacktesting class MyStrategy(Strategy): def initialize(self): # Use continuous futures for clean backtesting self.asset = Asset("MES", asset_type=Asset.AssetType.CONT_FUTURE) def on_trading_iteration(self): # Get historical data bars = self.get_historical_prices(self.asset, 20, "minute") if bars and not bars.df.empty: # Your strategy logic here pass # Run backtest with DataBento if __name__ == "__main__": results = MyStrategy.backtest( DataBentoDataBacktesting, benchmark_asset=Asset("SPY", Asset.AssetType.STOCK) ) ``` -------------------------------- ### Explore All Lumibot Example Strategies Source: https://github.com/lumiwealth/lumibot/blob/dev/README.md List all available example strategy files within the Lumibot library. This command helps in discovering the range of examples provided. ```bash ls lumibot/example_strategies/ ``` -------------------------------- ### LumiBot CCXT Strategy Example Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/brokers.ccxt.rst A basic LumiBot strategy demonstrating how to initialize, set market, get prices, create limit orders, and submit them using CCXT. This example assumes CCXT auto-detection or an explicit config. ```python from lumibot.strategies import Strategy from lumibot.entities import Asset class MyStrategy(Strategy): def initialize(self): self.sleeptime = "1D" # Set the market to 24/7 since crypto markets are always open self.set_market("24/7") def on_trading_iteration(self): # Trade Bitcoin btc = Asset("BTC", asset_type=Asset.AssetType.CRYPTO) # Get current price last_price = self.get_last_price(btc) # Place a limit order if last_price: order = self.create_order( asset=btc, quantity=0.1, side="buy", order_type="limit", limit_price=last_price * 0.999 ) self.submit_order(order) # Run the strategy (CCXT auto-detects supported environment variables, # or use an explicit Ccxt config for manual exchange paths) strategy = MyStrategy() strategy.run_live() ``` -------------------------------- ### Example .env file for broker credentials Source: https://github.com/lumiwealth/lumibot/blob/dev/llms-full.txt This example shows how to configure API keys and secrets for Kraken and Binance in a .env file. LumiBot automatically loads these credentials. ```dotenv # For Kraken KRAKEN_API_KEY=your_kraken_api_key_here KRAKEN_API_SECRET=your_kraken_secret_here # For Binance BINANCE_API_KEY=your_binance_api_key_here BINANCE_SECRET=your_binance_secret_here ``` -------------------------------- ### Install Sphinx and Furo Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/README.md Install the necessary Python packages for documentation generation. Ensure you have pip installed. ```bash pip install sphinx pip install furo ``` -------------------------------- ### Verify Current Branch and Setup Version Source: https://github.com/lumiwealth/lumibot/blob/dev/CLAUDE.md At the start of each session, verify that the current Git branch is a 'version/X.Y.Z' branch and that the version in 'setup.py' matches. This is a mandatory check. ```bash git branch --show-current # MUST be version/X.Y.Z grep ‘version=’ setup.py # MUST match the branch name ``` -------------------------------- ### Install yappi for Profiling Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/getting_started.rst Install the yappi library using pip. This is the first step to profiling your code. ```bash pip install yappi ``` -------------------------------- ### Full Example Strategy with pandas_ta Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/brokers.ccxt.rst A complete LumiBot strategy example that includes importing pandas_ta for technical analysis. Ensure pandas_ta is installed via 'pip install pandas_ta'. ```python import datetime import pandas_ta # If this gives an error, run `pip install pandas_ta` in your terminal from lumibot.brokers import Ccxt ``` -------------------------------- ### Example .env File for CCXT Brokers Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/brokers.ccxt.rst Set your broker's API credentials in a .env file for automatic loading by LumiBot. This example shows credentials for Kraken and WEEX. ```bash # For Kraken KRAKEN_API_KEY=your_kraken_api_key_here KRAKEN_API_SECRET=your_kraken_secret_here # For WEEX WEEX_API_KEY=your_weex_api_key_here WEEX_API_SECRET=your_weex_secret_here WEEX_API_PASSPHRASE=your_weex_passphrase_here ``` -------------------------------- ### Full Example Strategy with Tradier Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/brokers.tradier.rst A complete example demonstrating how to set up a Lumibot strategy using the Tradier broker. Includes configuration, strategy definition, and execution. ```python from lumibot.brokers import Tradier from lumibot.trader import Trader from lumibot.strategies import Strategy TRADIER_CONFIG = { "ACCESS_TOKEN": "your_access_token", "ACCOUNT_NUMBER": "your_account_number", "PAPER": True, } class MyStrategy(Strategy): def on_trading_iteration(self): # Buy 1 share of AAPL if the price is less than $100 price = self.get_last_price("AAPL") self.log_message(f"AAPL price: {price}") broker = Tradier(config=TRADIER_CONFIG) strategy = MyStrategy(broker=broker) trader = Trader() trader.add_strategy(strategy) strategy_executors = trader.run_all() ``` -------------------------------- ### Backtesting Strategy Using Environment Variables Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/backtesting.thetadata.rst This example demonstrates running a backtest where the start and end dates are configured via environment variables (BACKTESTING_START, BACKTESTING_END) instead of being hardcoded. The IS_BACKTESTING variable should also be set to 'True'. ```python from lumibot.backtesting import BacktestingBroker, ThetaDataBacktesting from lumibot.strategies import Strategy from lumibot.traders import Trader class MyStrategy(Strategy): parameters = { "symbol": "AAPL", } def initialize(self): self.sleeptime = "1D" def on_trading_iteration(self): if self.first_iteration: symbol = self.parameters["symbol"] price = self.get_last_price(symbol) qty = self.portfolio_value / price order = self.create_order(symbol, quantity=qty, side="buy") self.submit_order(order) if __name__ == "__main__": # No start/end in code. We rely on environment variables for backtesting dates. result = MyStrategy.run_backtest( ThetaDataBacktesting, benchmark_asset="SPY" ) ``` -------------------------------- ### Example Strategy: OpenAI LLM Agent Source: https://github.com/lumiwealth/lumibot/blob/dev/CHANGELOG.md This example strategy demonstrates how to use an OpenAI LLM provider with an AI agent. Ensure the OPENAI_API_KEY environment variable is set. ```python from lumibot.brokers import BacktestingBroker from lumibot.strategies.agent import Agent from lumibot.traders import Trader class AgentM2LiquidityOpenAI(Agent): def __init__(self, manager): super().__init__(manager) self.default_model = "openai/gpt-5.4-mini" if __name__ == "__main__": # Example of how to run this strategy broker = BacktestingBroker() trader = Trader(broker, AgentM2LiquidityOpenAI) trader.run_for_time("2023-01-01 00:00:00", "2023-01-01 23:59:00") ``` -------------------------------- ### Example Strategy: Grok LLM Agent Source: https://github.com/lumiwealth/lumibot/blob/dev/CHANGELOG.md This example strategy demonstrates how to use the Grok LLM provider with an AI agent. Ensure the XAI_API_KEY or GROK_API_KEY environment variable is set. ```python from lumibot.brokers import BacktestingBroker from lumibot.strategies.agent import Agent from lumibot.traders import Trader class AgentM2LiquidityGrok(Agent): def __init__(self, manager): super().__init__(manager) self.default_model = "xai/grok-4.20-0309-reasoning" if __name__ == "__main__": # Example of how to run this strategy broker = BacktestingBroker() trader = Trader(broker, AgentM2LiquidityGrok) trader.run_for_time("2023-01-01 00:00:00", "2023-01-01 23:59:00") ``` -------------------------------- ### Install LumiBot Source: https://github.com/lumiwealth/lumibot/blob/dev/llms-full.txt Install LumiBot using pip. To upgrade to the latest version, use the --upgrade flag. ```bash pip install lumibot ``` ```bash pip install lumibot --upgrade ``` -------------------------------- ### Install Lumibot Source: https://github.com/lumiwealth/lumibot/blob/dev/docs/MIGRATING_FROM_BACKTRADER.md Command to install the Lumibot library using pip. This is the first step to begin using Lumibot for trading strategy development and execution. ```bash pip install lumibot ``` -------------------------------- ### One-Time Setup on First Iteration in LumiBot Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/faq.rst Use self.first_iteration, which is True only on the first call to on_trading_iteration(), to execute one-time setup logic like initial position entry. ```python def on_trading_iteration(self): if self.first_iteration: # Only runs once order = self.create_order("SPY", 100, "buy") self.submit_order(order) ``` -------------------------------- ### Live Trading Setup for AI Trading Team Strategy Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/index.rst Configure and run the AITradingTeamBullBearLeveragedETFStrategy with a live broker connection. Replace the backtesting block with this setup for paper or live trading. ```python from lumibot.brokers import Alpaca from lumibot.traders import Trader ALPACA_CONFIG = { "API_KEY": "YOUR_ALPACA_API_KEY", "API_SECRET": "YOUR_ALPACA_SECRET", "PAPER": True, } broker = Alpaca(ALPACA_CONFIG) strategy = AITradingTeamBullBearLeveragedETFStrategy(broker=broker) trader = Trader() trader.add_strategy(strategy) trader.run_all() ``` -------------------------------- ### Example Strategy: Anthropic LLM Agent Source: https://github.com/lumiwealth/lumibot/blob/dev/CHANGELOG.md This example strategy demonstrates how to use the Anthropic LLM provider with an AI agent. Ensure the ANTHROPIC_API_KEY environment variable is set. ```python from lumibot.brokers import BacktestingBroker from lumibot.strategies.agent import Agent from lumibot.traders import Trader class AgentM2LiquidityAnthropic(Agent): def __init__(self, manager): super().__init__(manager) self.default_model = "anthropic/claude-sonnet-4-6" if __name__ == "__main__": # Example of how to run this strategy broker = BacktestingBroker() trader = Trader(broker, AgentM2LiquidityAnthropic) trader.run_for_time("2023-01-01 00:00:00", "2023-01-01 23:59:00") ``` -------------------------------- ### Example Strategy with Trace Stats Source: https://github.com/lumiwealth/lumibot/blob/dev/llms-full.txt This example demonstrates how to implement the `trace_stats` method within a Lumibot strategy to log custom statistics. It shows how to access context from `on_trading_iteration` and return a dictionary of stats. ```python import random from lumibot.strategies import Strategy class MyStrategy(Strategy): def on_trading_iteration(self): google_symbol = "GOOG" def trace_stats(self, context, snapshot_before): print(context) # printing # { "google_symbol":"GOOG"} random_number = random.randint(0, 100) row = {"my_custom_stat": random_number} return row ``` -------------------------------- ### Initialize Strategy with Parameters Source: https://github.com/lumiwealth/lumibot/blob/dev/llms-full.txt Demonstrates initializing a strategy with custom parameters and budget. This is useful for setting up different trading strategies with specific configurations. ```python strategy_1 = MyStrategy( name="strategy_1", budget=budget, broker=broker, my_custom_parameter=False, my_other_parameter=50 ) strategy_2 = MyStrategy( name="strategy_2", budget=budget, broker=broker, my_custom_parameter=True, my_last_parameter="SPY" ) ``` -------------------------------- ### Set and Get Minutes Before Opening Source: https://github.com/lumiwealth/lumibot/blob/dev/llms-full.txt Manages the number of minutes before market open that the strategy starts executing. The default is 60 minutes. ```python >>> # Set the number of minutes before the market opens >>> self.minutes_before_opening = 10 >>> # Set the number of minutes before the market opens to 0 in the initialize method >>> def initialize(self): >>> self.minutes_before_opening = 0 ``` -------------------------------- ### Python Strategy: Resetting Blacklist Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/lifecycle_methods.before_starting_trading.rst Example of resetting a blacklist variable at the start of trading. This method is called once per day before trading begins. ```python class MyStrategy(Strategy): def before_starting_trading(self): self.blacklist = [] ``` -------------------------------- ### Get Version from setup.py Source: https://github.com/lumiwealth/lumibot/blob/dev/AGENTS.md Retrieves the current version number defined in the setup.py file. ```python version="X.Y.Z", # e.g., "4.4.25", "4.5.0", etc. ``` -------------------------------- ### Verify New Branch and Setup Version Source: https://github.com/lumiwealth/lumibot/blob/dev/CLAUDE.md After switching to a new version branch, verify that the current branch name and the version in 'setup.py' both match the new version. This confirms the switch was successful. ```bash git branch --show-current must print version/X.Y.(Z+1); grep 'version=' setup.py must match. ``` -------------------------------- ### Get Bars for Ethereum (ETH) in Bitcoin (BTC) Source: https://github.com/lumiwealth/lumibot/blob/dev/llms-full.txt Retrieves bars for Ethereum (ETH) and logs its closing price. This example demonstrates fetching crypto data. ```python asset = Asset(symbol="ETH", asset_type="crypto") quote = Asset(symbol="BTC", asset_type="crypto") bars = bars.get_bars(asset) df = bars.df self.log_message(df["close"][-1]) ``` -------------------------------- ### Risk Managed Futures Strategy Example Source: https://github.com/lumiwealth/lumibot/blob/dev/llms-full.txt Demonstrates a futures trading strategy with built-in stop-loss risk management. Ensure you have the necessary asset and trading environment setup. ```python class RiskManagedFuturesStrategy(Strategy): def initialize(self): self.asset = Asset("MES", asset_type=Asset.AssetType.CONT_FUTURE) self.max_position_size = 5 self.stop_loss_pct = 0.02 # 2% stop loss def on_trading_iteration(self): current_price = self.get_last_price(self.asset) position = self.get_position(self.asset) # Risk management: check for stop loss if position and position.quantity != 0: unrealized_pnl_pct = position.quantity * (current_price - position.avg_fill_price) / position.avg_fill_price if abs(unrealized_pnl_pct) > self.stop_loss_pct: # Exit position if stop loss hit if position.quantity > 0: order = self.create_order(self.asset, position.quantity, "sell") else: order = self.create_order(self.asset, abs(position.quantity), "buy") self.submit_order(order) return # Your trading logic here... ``` -------------------------------- ### Get Historical Prices and Perform Technical Analysis Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/brokers.ccxt.rst Retrieves historical price data and calculates technical indicators like RSI, MACD, and EMA using pandas_ta. Requires the pandas_ta library to be installed. ```python bars = self.get_historical_prices(base, 100, "minute", quote=quote) if bars is not None: df = bars.df max_price = df["close"].max() self.log_message(f"Max price for {base} was {max_price}") ############################ # TECHNICAL ANALYSIS ############################ # Use pandas_ta to calculate the 20 period RSI rsi = df.ta.rsi(length=20) current_rsi = rsi.iloc[-1] self.log_message(f"RSI for {base} was {current_rsi}") # Use pandas_ta to calculate the MACD macd = df.ta.macd() current_macd = macd.iloc[-1] self.log_message(f"MACD for {base} was {current_macd}") # Use pandas_ta to calculate the 55 EMA ema = df.ta.ema(length=55) current_ema = ema.iloc[-1] self.log_message(f"EMA for {base} was {current_ema}") ``` -------------------------------- ### Complete Lumibot Example Script Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/getting_started.rst A consolidated script demonstrating all steps from configuration to running a strategy, including imports. ```python from datetime import datetime from lumibot.backtesting import YahooDataBacktesting 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", # Set this to False to use a live account "PAPER": True } class MyStrategy(Strategy): parameters = { "symbol": "SPY", "quantity": 1, "side": "buy" } def initialize(self, symbol=""): self.sleeptime = "180M" def on_trading_iteration(self): symbol = self.parameters["symbol"] quantity = self.parameters["quantity"] side = self.parameters["side"] order = self.create_order(symbol, quantity, side) self.submit_order(order) trader = Trader() broker = Alpaca(ALPACA_CONFIG) strategy = MyStrategy(broker=broker, parameters={"symbol": "SPY"}) backtesting_start = datetime(2020, 1, 1) backtesting_end = datetime(2020, 12, 31) strategy.run_backtest( YahooDataBacktesting, backtesting_start, backtesting_end, parameters={"symbol": "SPY"} ) trader.add_strategy(strategy) trader.run_all() ``` -------------------------------- ### Instantiate Strategy with Different Custom Parameters Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/lifecycle_methods.initialize.rst Demonstrates setting different custom parameters during strategy instantiation. ```python strategy_2 = MyStrategy( name="strategy_2", budget=budget, broker=broker, my_custom_parameter=True, my_last_parameter="SPY" ) ``` -------------------------------- ### Full Backtesting Strategy with ThetaData Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/backtesting.thetadata.rst A complete example of a trading strategy using ThetaData for backtesting. Ensure THETADATA_USERNAME and THETADATA_PASSWORD are set. This code defines a simple strategy that buys a specified symbol at the start of the backtest. ```python from datetime import datetime from lumibot.backtesting import BacktestingBroker, ThetaDataBacktesting from lumibot.strategies import Strategy from lumibot.traders import Trader class MyStrategy(Strategy): parameters = { "symbol": "AAPL", } def initialize(self): self.sleeptime = "1D" def on_trading_iteration(self): if self.first_iteration: symbol = self.parameters["symbol"] price = self.get_last_price(symbol) qty = self.portfolio_value / price order = self.create_order(symbol, quantity=qty, side="buy") self.submit_order(order) if __name__ == "__main__": backtesting_start = datetime(2025, 1, 1) backtesting_end = datetime(2025, 1, 31) result = MyStrategy.run_backtest( ThetaDataBacktesting, backtesting_start, backtesting_end, benchmark_asset="SPY" ) ``` -------------------------------- ### Initialize Strategy with Basic Properties Source: https://github.com/lumiwealth/lumibot/blob/dev/llms-full.txt A basic example of initializing a strategy by setting properties like sleeptime, ticker, and closing time parameters. ```python def initialize(self): self.sleeptime = 5 self.ticker = "AAPL" self.minutes_before_closing = 5 self.max_bars = 100 ``` -------------------------------- ### Futures Backtesting Setup Source: https://github.com/lumiwealth/lumibot/blob/dev/llms-full.txt Illustrates how to set up a backtesting environment for futures strategies using `DataBentoDataBacktesting`. It specifies flat trading fees, which are typical for futures contracts. ```python from lumibot.backtesting import DataBentoDataBacktesting from lumibot.entities import TradingFee class FuturesStrategy(Strategy): def initialize(self): self.asset = Asset("ES", asset_type=Asset.AssetType.CONT_FUTURE) def on_trading_iteration(self): # Your futures trading logic here pass if __name__ == "__main__": if IS_BACKTESTING: # Use flat fees for futures (typical: $0.50 per contract) trading_fee = TradingFee(flat_fee=0.50) results = FuturesStrategy.backtest( DataBentoDataBacktesting, benchmark_asset=Asset("SPY", Asset.AssetType.STOCK), buy_trading_fees=[trading_fee], sell_trading_fees=[trading_fee] ) ``` -------------------------------- ### Run Backtest with Dates Specified in Code Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/backtesting.yahoo.rst This example demonstrates how to run a backtest using the YahooDataBacktesting by providing the start and end dates directly within the code. It includes a simple strategy that buys AAPL on the first trading day. ```python from datetime import datetime from lumibot.backtesting import BacktestingBroker, YahooDataBacktesting from lumibot.strategies import Strategy from lumibot.traders import Trader # A simple strategy that buys AAPL on the first day 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 in code backtesting_start = datetime(2025, 1, 1) backtesting_end = datetime(2025, 1, 31) # Run the backtest result = MyStrategy.run_backtest( YahooDataBacktesting, backtesting_start, backtesting_end, ) ``` -------------------------------- ### Initialize and Run Strategy with Interactive Brokers Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/brokers.interactive_brokers_legacy.rst Initialize the InteractiveBrokers class with your configuration and add a strategy to the trader. This example demonstrates setting up a Strangle strategy. ```python from lumibot.traders import Trader # Import interactive brokers from lumibot.brokers import InteractiveBrokers from lumibot.strategies.examples import Strangle from credentials import INTERACTIVE_BROKERS_CONFIG trader = Trader() # Initialize interactive brokers interactive_brokers = InteractiveBrokers(INTERACTIVE_BROKERS_CONFIG) strategy = Strangle(broker=interactive_brokers) trader.add_strategy(strategy) trader.run_all() ``` -------------------------------- ### Simple Futures Trading Strategy Example Source: https://github.com/lumiwealth/lumibot/blob/dev/llms-full.txt A basic futures trading strategy using a 20-day simple moving average. It demonstrates how to initialize assets, get historical data, calculate SMAs, and place buy/sell orders based on price relative to the SMA. ```python from lumibot.entities import Asset, Order from lumibot.strategies import Strategy class SimpleFuturesStrategy(Strategy): def initialize(self): # Use continuous futures for clean backtesting self.asset = Asset("MES", asset_type=Asset.AssetType.CONT_FUTURE) self.order_size = 10 # Log which asset we're trading self.log_message(f"Trading {self.asset.symbol} continuous futures") def on_trading_iteration(self): # Get current price current_price = self.get_last_price(self.asset) # Simple moving average strategy bars = self.get_historical_prices(self.asset, 20, "day") if bars and len(bars.df) >= 20: sma_20 = bars.df['close'].rolling(20).mean().iloc[-1] position = self.get_position(self.asset) # Buy signal: price above SMA if current_price > sma_20 and (position is None or position.quantity <= 0): if position and position.quantity < 0: # Cover short position self.create_order(self.asset, abs(position.quantity), "buy") # Go long order = self.create_order(self.asset, self.order_size, "buy") self.submit_order(order) # Sell signal: price below SMA elif current_price < sma_20 and (position is None or position.quantity >= 0): if position and position.quantity > 0: # Close long position self.create_order(self.asset, position.quantity, "sell") # Go short order = self.create_order(self.asset, self.order_size, "sell") self.submit_order(order) ``` -------------------------------- ### Futures Backtesting Setup Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/examples.rst Sets up a basic strategy for backtesting futures trading. It specifies the asset and includes a placeholder for trading logic. It also shows how to configure per-contract trading fees. ```python from lumibot.backtesting import DataBentoDataBacktesting from lumibot.entities import TradingFee class FuturesStrategy(Strategy): def initialize(self): self.asset = Asset("ES", asset_type=Asset.AssetType.CONT_FUTURE) def on_trading_iteration(self): # Your futures trading logic here pass if __name__ == "__main__": if IS_BACKTESTING: # Use per-contract fees for futures (typical: $0.85 per standard contract, $0.50 for micros) trading_fee = TradingFee(per_contract_fee=0.85) ``` -------------------------------- ### Alpaca News Built-in Strategy Example Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/agents.rst This Python code demonstrates how to create a Lumibot strategy that utilizes the Alpaca News agent. It initializes the agent with a system prompt guiding its decision-making process based on market news and configures it to use the alpaca_news tool. ```python import os from lumibot.components.agents import BuiltinTools from lumibot.strategies.strategy import Strategy class AlpacaNewsBuiltinStrategy(Strategy): def initialize(self): self.sleeptime = "1D" self.agents.create( name="news_trader", default_model=os.environ.get("AGENT_MODEL", "gemini-3.1-flash-lite-preview"), system_prompt=( "Use Alpaca news and market tools to decide whether to hold SPY, QQQ, or a defensive ETF. " "First call alpaca_news with symbols='SPY,QQQ,DIA,IWM', include_content=False, and limit=30. " "If a story looks market-moving, call alpaca_news again with include_content=True and " "exclude_contentless=True before trading. " "Use page_token when next_page_token is returned." ), tools=[BuiltinTools.news.alpaca_news()], ) def on_trading_iteration(self): self.agents["news_trader"].run( context={"current_datetime": self.get_datetime().isoformat()} ) ``` -------------------------------- ### Build and Test Lumibot Docs Locally Source: https://github.com/lumiwealth/lumibot/blob/dev/AGENTS.md Navigate to the 'docsrc' directory and run these commands to build the HTML documentation and start a local server for previewing. This is essential for testing changes before deployment. ```bash cd docsrc make clean html # Preview at _build/html/index.html # Or start local server: python3 -m http.server 8765 --directory _build/html ``` -------------------------------- ### Basic Strategy Initialization with Environment Variables Source: https://github.com/lumiwealth/lumibot/blob/dev/llms-full.txt Example of initializing a Lumibot strategy using environment variables for broker and data source configuration. The strategy is set to run every minute. ```python from lumibot.strategies import Strategy from lumibot.traders import Trader from lumibot.entities import Asset class MyFuturesStrategy(Strategy): def initialize(self): self.sleeptime = "1M" ``` -------------------------------- ### Install snakeviz for Visualization Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/getting_started.rst Install the snakeviz library using pip. This tool is used to visualize profiling results. ```bash pip install snakeviz ``` -------------------------------- ### Install DataBento Dependency Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/backtesting.databento.rst Install the DataBento package using pip. This is required to enable DataBento support in Lumibot. ```bash pip install databento ``` -------------------------------- ### Install Lumibot Version Source: https://github.com/lumiwealth/lumibot/blob/dev/docs/DEPLOYMENT.md Verifies if a specific Lumibot version is installable from PyPI. Useful for confirming release integrity. ```bash python3 -m pip install --no-deps "lumibot==X.Y.Z" ``` ```bash python3 -m pip show lumibot ``` -------------------------------- ### Example .env file for Schwab Credentials Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/brokers.schwab.rst Use this format to store your Schwab credentials locally for development. Ensure this file is kept secure and not committed to version control. ```bash # .env TRADING_BROKER=schwab SCHWAB_ACCOUNT_NUMBER=XXXXXXXX ``` -------------------------------- ### Local Cache Path Example Source: https://github.com/lumiwealth/lumibot/blob/dev/docs/REMOTE_CACHE.md Example of a local ThetaData quote cache file path on a macOS system. ```text /Users//Library/Caches/lumibot/1.0/thetadata/stock/minute/ohlc/stock_SPY_minute_ohlc.parquet ``` -------------------------------- ### Initialize and Run AI Agent in Backtest Source: https://github.com/lumiwealth/lumibot/blob/dev/docs/AI_TRADING_AGENTS.md Demonstrates how to initialize an AI agent with a system prompt and run it within a backtesting loop. The agent uses built-in FRED tools automatically when FRED_API_KEY is configured. ```python from lumibot.strategies import Strategy class M2LiquidityStrategy(Strategy): def initialize(self): self.sleeptime = "1D" self.agents.create( name="m2_analyst", default_model="gpt-4.1-mini", system_prompt=( "Use money supply and liquidity data to decide between " "TQQQ and SHV. Focus on whether M2 liquidity is expanding " "or contracting." ), ) def on_trading_iteration(self): result = self.agents["m2_analyst"].run() self.log_message(f"[m2_analyst] {result.summary}", color="yellow") if __name__ == "__main__": IS_BACKTESTING = True if IS_BACKTESTING: from datetime import datetime M2LiquidityStrategy.backtest( datasource_class=None, backtesting_start=datetime(2020, 1, 1), backtesting_end=datetime(2026, 3, 1), benchmark_asset="SPY", ) ``` -------------------------------- ### Verify Published Version on PyPI Source: https://github.com/lumiwealth/lumibot/blob/dev/docs/DEPLOYMENT.md Checks the installed versions of the 'lumibot' package to confirm the latest version is visible and installable on PyPI. ```bash python3 -m pip index versions lumibot | head ``` -------------------------------- ### Full Lumibot backtesting example with Polygon.io Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/backtesting.polygon.rst A complete script demonstrating how to set up and run a backtest using Polygon.io data. Remember to replace 'YOUR_POLYGON_API_KEY' with your actual API key. ```python from datetime import datetime from lumibot.backtesting import BacktestingBroker, PolygonDataBacktesting from lumibot.strategies import Strategy from lumibot.traders import Trader class MyStrategy(Strategy): parameters = { "symbol": "AAPL", } def initialize(self): self.sleeptime = "1D" def on_trading_iteration(self): if self.first_iteration: symbol = self.parameters["symbol"] price = self.get_last_price(symbol) qty = self.portfolio_value / price order = self.create_order(symbol, quantity=qty, side="buy") self.submit_order(order) if __name__ == "__main__": backtesting_start = datetime(2025, 1, 1) backtesting_end = datetime(2025, 1, 31) result = MyStrategy.run_backtest( PolygonDataBacktesting, backtesting_start, backtesting_end, benchmark_asset="SPY" ) ``` -------------------------------- ### Retry Lumibot Installation with Loop Source: https://github.com/lumiwealth/lumibot/blob/dev/docs/DEPLOYMENT.md Attempts to install a Lumibot version repeatedly with a delay, useful for overcoming transient PyPI propagation issues. ```bash VERSION="X.Y.Z" for i in {1..20}; do if python3 -m pip install --no-deps "lumibot==${VERSION}"; then echo "OK: lumibot==${VERSION} is installable" break fi echo "Waiting for PyPI propagation (${i}/20)..." sleep 15 done ``` -------------------------------- ### Basic Strategy Setup with Lumibot Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/brokers.interactive_brokers.rst This Python code demonstrates how to initialize the Lumibot Trader, add a strategy (Strangle in this case), and run it. Ensure all necessary environment variables for API connection are set. ```python from lumibot.traders import Trader from lumibot.strategies.examples import Strangle trader = Trader() strategy = Strangle() trader.add_strategy(strategy) trader.run_all() ``` -------------------------------- ### Create Stock Asset (AAPL Example) Source: https://github.com/lumiwealth/lumibot/blob/dev/llms-full.txt Example of creating an Asset object for Apple (AAPL) stock. This demonstrates the basic instantiation for a stock. ```python >>> # Create an Asset object for a stock. >>> from lumibot.entities import Asset >>> asset = Asset(symbol="AAPL") ``` -------------------------------- ### Create and Run Multiple Agents Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/agents_quickstart.rst Demonstrates how to create multiple agents with distinct configurations and run them individually within a trading strategy. ```python self.agents.create(name="agent1", system_prompt="You are a helpful assistant.") self.agents.create(name="agent2", system_prompt="You are a data analyst.") # In on_trading_iteration: result1 = self.agents["agent1"].run() result2 = self.agents["agent2"].run() ``` -------------------------------- ### Get Alpaca Quote Source: https://github.com/lumiwealth/lumibot/blob/dev/llms-full.txt Retrieves the latest quote information for a given asset. Use this to get real-time bid, ask, and last prices. ```python quote = alpaca.get_quote(asset=Asset(symbol="AAPL")) print(quote.bid) print(quote.ask) ``` -------------------------------- ### Enable Binance Backtesting Data Source Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/brokers.ccxt.binance.rst Set the BACKTESTING_DATA_SOURCE environment variable to 'binance' to use Binance data for backtesting. ```bash export BACKTESTING_DATA_SOURCE=binance ``` -------------------------------- ### Initialize Interactive Brokers Legacy Broker Source: https://github.com/lumiwealth/lumibot/blob/dev/llms-full.txt Sets up the Interactive Brokers legacy broker with specific configuration. Ensure your Trader Workstation is configured for API access. ```python from lumibot.traders import Trader # Import interactive brokers from lumibot.brokers import InteractiveBrokers from lumibot.strategies.examples import Strangle from credentials import INTERACTIVE_BROKERS_CONFIG trader = Trader() # Initialize interactive brokers interactive_brokers = InteractiveBrokers(INTERACTIVE_BROKERS_CONFIG) strategy = Strangle(broker=interactive_brokers) trader.add_strategy(strategy) trader.run_all() ``` -------------------------------- ### Create Basic Option Order Source: https://github.com/lumiwealth/lumibot/blob/dev/llms-full.txt Example of creating a simple option order with a specified strike price and limit price. ```python from lumibot.entities import Asset asset = Asset("SPY", asset_type=Asset.AssetType.OPTION, expiration="2019-01-01", strike=100.00) order = self.create_order(asset, 100, "buy", limit_price=100.00) self.submit_order(order) ``` -------------------------------- ### Correct and Incorrect File Naming Conventions Source: https://github.com/lumiwealth/lumibot/blob/dev/docs/README.md Examples demonstrating the mandatory uppercase and underscore-based file naming conventions for Lumibot documentation, contrasted with incorrect examples. ```markdown ✅ CORRECT: docs/BACKTESTING_ARCHITECTURE.md docs/handoffs/2026-01-04_THETADATA_HANDOFF.md docs/investigations/2026-01-02_ACCURACY_AUDIT.md ❌ WRONG: docs/backtesting_architecture.md (lowercase) docs/Backtesting-Architecture.md (mixed case, hyphens) docs/handoffs/thetadata_handoff.md (missing date, lowercase) ``` -------------------------------- ### Basic Backtest Configuration Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/backtesting.how_to_backtest.rst This snippet shows how to configure and run a backtest using explicit parameters for start and end dates, and specifying the data source and API key. ```python from lumibot.strategies import Strategy from datetime import datetime class MyStrategy(Strategy): parameters = { "symbol": "AAPL", } def initialize(self): self.sleeptime = "1D" def on_trading_iteration(self): if self.first_iteration: symbol = self.parameters["symbol"] price = self.get_last_price(symbol) qty = self.portfolio_value / price order = self.create_order(symbol, quantity=qty, side="buy") self.submit_order(order) if __name__ == "__main__": polygon_api_key = "YOUR_POLYGON_API_KEY" # Replace with your actual Polygon.io API key backtesting_start = datetime(2025, 1, 1) backtesting_end = datetime(2025, 5, 1) result = MyStrategy.run_backtest( PolygonDataBacktesting, backtesting_start, backtesting_end, benchmark_asset="SPY", polygon_api_key=polygon_api_key # Pass the Polygon.io API key here ) ``` -------------------------------- ### Backtest Using Environment Variables Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/backtesting.how_to_backtest.rst This example demonstrates running a backtest by relying entirely on environment variables for configuration (data source, start/end dates). The Polygon.io API key is still required. ```python from lumibot.strategies import Strategy class MyStrategy(Strategy): parameters = { "symbol": "AAPL", } def initialize(self): self.sleeptime = "1D" def on_trading_iteration(self): if self.first_iteration: symbol = self.parameters["symbol"] price = self.get_last_price(symbol) qty = self.portfolio_value / price order = self.create_order(symbol, quantity=qty, side="buy") self.submit_order(order) if __name__ == "__main__": # Set in environment: BACKTESTING_DATA_SOURCE=Polygon # Set in environment: BACKTESTING_START=2025-01-01 # Set in environment: BACKTESTING_END=2025-05-01 polygon_api_key = "YOUR_POLYGON_API_KEY" # Still required for Polygon result = MyStrategy.run_backtest( None, # Auto-selects from BACKTESTING_DATA_SOURCE env var polygon_api_key=polygon_api_key ) ``` -------------------------------- ### Create and Run an AI Agent Source: https://github.com/lumiwealth/lumibot/blob/dev/docsrc/examples.rst Demonstrates how to create an AI agent with specific tools and run it within a trading iteration. This pattern is useful for integrating AI-powered research into trading strategies. ```python from lumibot.components.agents import BuiltinTools, MCPServer def initialize(self): self.agents.create( name="research", default_model="gemini-3.1-flash-lite-preview", system_prompt="Use the available tools and return a short summary.", tools=[ BuiltinTools.account.positions(), BuiltinTools.account.portfolio(), BuiltinTools.market.last_price(), BuiltinTools.docs.search(), ], ) def on_trading_iteration(self): result = self.agents["research"].run( context={"symbol": "SPY", "current_datetime": self.get_datetime().isoformat()} ) self.log_message(f"[research] {result.summary}", color="yellow") ```