### Install Yappi Profiling Tool Source: https://github.com/demierdm/lumibot/blob/dev/docsrc/_build/html/_sources/getting_started.rst.txt Command to install the 'yappi' library, a Python profiler used for performance analysis. It is executed from the terminal. ```bash pip install yappi ``` -------------------------------- ### Visualize Yappi Profiling Results with Snakeviz Source: https://github.com/demierdm/lumibot/blob/dev/docsrc/_build/html/_sources/getting_started.rst.txt Command to install and use 'snakeviz' to visualize profiling data generated by 'yappi'. This command launches a web browser displaying the profiling results. ```bash pip install snakeviz snakeviz yappi.prof ``` -------------------------------- ### Define a Simple Trading Strategy in Lumibot Source: https://github.com/demierdm/lumibot/blob/dev/docs/_sources/getting_started.rst.txt Creates a basic trading strategy class inheriting from Lumibot's Strategy. This example defines parameters for symbol, quantity, and side, and includes methods to initialize and execute a trade during a trading iteration. ```python class MyStrategy(Strategy): # Custom parameters parameters = { "symbol": "SPY", "quantity": 1, "side": "buy" } def initialize(self, symbol=""): # Will make on_trading_iteration() run every 180 minutes 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) ``` -------------------------------- ### Set Up Lumibot Strategy Backtesting Source: https://github.com/demierdm/lumibot/blob/dev/docs/_sources/getting_started.rst.txt Imports necessary modules for backtesting a trading strategy with Lumibot. It includes defining the start date for historical data retrieval from Yahoo Finance. ```python from datetime import datetime from lumibot.backtesting import YahooDataBacktesting backtesting_start = datetime(2020, 1, 1) ``` -------------------------------- ### Install LumiBot using pip Source: https://github.com/demierdm/lumibot/blob/dev/docs/_sources/backtesting.how_to_backtest.rst.txt This command installs the LumiBot library using pip. Ensure you have Python and pip installed on your system. For an upgrade, use the --upgrade flag. ```bash pip install lumibot ``` ```bash pip install lumibot --upgrade ``` -------------------------------- ### Lumibot Example Strategy Setup (Python) Source: https://github.com/demierdm/lumibot/blob/dev/docs/_sources/brokers.interactive_brokers.rst.txt This code snippet demonstrates how to set up and run an example strategy using the Lumibot library. It requires importing the Trader and Strangle classes and then initializing and running the strategy. ```python from lumibot.traders import Trader from lumibot.strategies.examples import Strangle trader = Trader() strategy = Strangle() trader.add_strategy(strategy) trader.run_all() ``` -------------------------------- ### Instantiate Lumibot Trader, Broker, and Strategy Source: https://github.com/demierdm/lumibot/blob/dev/docs/_sources/getting_started.rst.txt Initializes the core components of a Lumibot trading application. This includes creating instances of the Trader, Alpaca broker (with configuration), and a specific trading strategy. ```python trader = Trader() broker = Alpaca(ALPACA_CONFIG) strategy = MyStrategy(name="My Strategy", budget=10000, broker=broker, symbol="SPY") ``` -------------------------------- ### Tradovate Configuration Examples Source: https://github.com/demierdm/lumibot/blob/dev/docsrc/_build/html/brokers.html Illustrative examples of how to configure the Tradovate broker, likely showing how to set up the broker instance and potentially combine it with a data source. ```python # Example configuration for Tradovate broker from lumibot.brokers import Tradovate from lumibot.strategies import Strategy from lumibot.traders import Trader # Assuming TRADOVATE_API_TOKEN and TRADOVATE_ACCOUNT_ID are set in environment variables # Basic Tradovate broker setup broker = Tradovate() # Example of combining Tradovate with a data source (if applicable) # from lumibot.data import AggregatedDataSource # data_source = AggregatedDataSource(Tradovate()) # broker = Tradovate(data_source=data_source) class MyTradovateStrategy(Strategy): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def on_tick(self): # Strategy logic here pass if __name__ == "__main__": trader = Trader(MyTradovateStrategy, broker=broker) trader.run() ``` -------------------------------- ### Backtest with Trading Fees Source: https://github.com/demierdm/lumibot/blob/dev/docsrc/getting_started.rst This Python code illustrates how to incorporate trading fees into Lumibot backtests. It demonstrates the creation of both percentage-based and flat-fee trading fees and their application to both buy and sell orders during the backtesting process. ```python from lumibot.backtesting import YahooDataBacktesting from lumibot.entities import TradingFee from datetime import datetime # Create two trading fees, one that is a percentage and one that is a flat fee trading_fee_1 = TradingFee(flat_fee=5) # $5 flat fee trading_fee_2 = TradingFee(percent_fee=0.01) # 1% trading fee backtesting_start = datetime(2020, 1, 1) backtesting_end = datetime(2020, 12, 31) strategy.run_backtest( YahooDataBacktesting, backtesting_start, backtesting_end, parameters={"symbol": "SPY"}, buy_trading_fees=[trading_fee_1, trading_fee_2], sell_trading_fees=[trading_fee_1, trading_fee_2], ) ``` -------------------------------- ### Profile Code with Yappi Source: https://github.com/demierdm/lumibot/blob/dev/docsrc/getting_started.rst This Python snippet shows how to use the 'yappi' library for profiling code execution. It covers starting and stopping the profiler, printing function and thread statistics, and saving the profiling results to a file for later analysis with tools like snakeviz. ```python import yappi from datetime import datetime from lumibot.backtesting import PandasDataBacktesting # Assuming backtesting_start, backtesting_end, pandas_data, and MachineLearningLongShort are defined elsewhere # Start the profiler yappi.start() ####### # Run your code here, eg. a backtest ####### MachineLearningLongShort.run_backtest( PandasDataBacktesting, backtesting_start, backtesting_end, pandas_data=pandas_data, benchmark_asset="TQQQ", ) # Stop the profiler yappi.stop() # Save the results to files yappi.get_func_stats().print_all() yappi.get_thread_stats().print_all() # Save the results to a file yappi.get_func_stats().save("yappi.prof", type="pstat") ``` -------------------------------- ### Profile Lumibot Code Performance with Yappi Source: https://github.com/demierdm/lumibot/blob/dev/docs/_sources/getting_started.rst.txt This snippet shows how to use the `yappi` library to profile Python code, such as a Lumibot backtest. It covers starting and stopping the profiler, printing function and thread statistics, and saving the profiling results to a file for later analysis with tools like `snakeviz`. ```bash pip install yappi ``` ```python import yappi # Start the profiler yappi.start() ####### # Run your code here, eg. a backtest ####### MachineLearningLongShort.run_backtest( PandasDataBacktesting, backtesting_start, backtesting_end, pandas_data=pandas_data, benchmark_asset="TQQQ", ) # Stop the profiler yappi.stop() # Save the results to files yappi.get_func_stats().print_all() yappi.get_thread_stats().print_all() # Save the results to a file yappi.get_func_stats().save("yappi.prof", type="pstat") ``` ```bash pip install snakeviz snakeviz yappi.prof ``` -------------------------------- ### Add Trading Fees to Lumibot Backtesting Source: https://github.com/demierdm/lumibot/blob/dev/docs/_sources/getting_started.rst.txt This snippet illustrates how to incorporate trading fees into Lumibot backtests. It demonstrates the creation of `TradingFee` objects for both percentage-based and flat-fee charges, and how to apply these fees to both buy and sell orders during the backtesting process. ```python from lumibot.backtesting import YahooDataBacktesting from lumibot.entities import TradingFee # Create two trading fees, one that is a percentage and one that is a flat fee trading_fee_1 = TradingFee(flat_fee=5) # $5 flat fee trading_fee_2 = TradingFee(percent_fee=0.01) # 1% trading fee backtesting_start = datetime(2020, 1, 1) backtesting_end = datetime(2020, 12, 31) strategy.run_backtest( YahooDataBacktesting, backtesting_start, backtesting_end, parameters={"symbol": "SPY"}, buy_trading_fees=[trading_fee_1, trading_fee_2], sell_trading_fees=[trading_fee_1, trading_fee_2], ) ``` -------------------------------- ### Run Lumibot Strategy Source: https://github.com/demierdm/lumibot/blob/dev/docs/index.html Code example for executing a Lumibot trading strategy in a live or paper trading environment. This starts the trading bot. ```python from lumibot.strategies.strategy import Strategy from lumibot.traders import Trader from lumibot.brokers.alpaca import Alpaca class MyStrategy(Strategy): def __init__(self, broker, params): super().__init__(broker, params) def on_trading_iteration(self): pass alpaca = Alpaca(API_KEY, API_SECRET, paper=True) trader = Trader(alpaca, MyStrategy) trader.run() ``` -------------------------------- ### Run Lumibot Strategy with Alpaca Broker and Backtesting Source: https://github.com/demierdm/lumibot/blob/dev/docs/_sources/getting_started.rst.txt This snippet demonstrates how to set up and run a Lumibot trading strategy. It includes broker configuration (Alpaca with paper trading enabled), strategy definition with custom parameters, and executing a backtest using Yahoo Finance data. The code also shows how to add the strategy to a trader and run all active strategies. ```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() ``` -------------------------------- ### Import Lumibot Trader and Broker Modules Source: https://github.com/demierdm/lumibot/blob/dev/docs/_sources/getting_started.rst.txt Imports necessary classes from the Lumibot library for creating trading bots. Specifically, it imports the Trader class for managing strategies and the Alpaca class for broker integration. ```python # importing the trader class from lumibot.traders import Trader # importing the alpaca broker class from lumibot.brokers import Alpaca ``` -------------------------------- ### Create and Submit Order Example - Python Source: https://github.com/demierdm/lumibot/blob/dev/docsrc/_build/html/strategy_methods.misc/lumibot.strategies.strategy.Strategy.wait_for_order_registration.html Demonstrates the process of creating a market buy order for a given asset and quantity, submitting it to the broker, and then waiting for its registration using lumibot. This example showcases a common workflow for initiating and tracking trades. ```python order = self.create_order("SPY", 100, "buy") self.submit_order(order) self.wait_for_order_registration(order) ``` -------------------------------- ### Configure Alpaca API Keys for Lumibot Source: https://github.com/demierdm/lumibot/blob/dev/docs/_sources/getting_started.rst.txt Sets up the configuration dictionary for connecting to Alpaca's trading API. It includes placeholders for your API key and secret, and specifies whether to use a paper trading account. ```python ALPACA_CONFIG = { # Put your own Alpaca key here: "API_KEY": "YOUR_ALPACA_API_KEY", # Put your own Alpaca secret here: "API_SECRET": "YOUR_ALPACA_SECRET", # Set this to False to use a live account "PAPER": True } ``` -------------------------------- ### Install Lumibot using pip Source: https://github.com/demierdm/lumibot/blob/dev/docs/index.html This command installs the Lumibot library on your system. It's the first step to begin using Lumibot for backtesting and algorithmic trading. Ensure you have pip installed. ```bash pip install lumibot ``` -------------------------------- ### Complete Lumibot Example: Backtesting and Live Trading Source: https://github.com/demierdm/lumibot/blob/dev/docs/_sources/index.rst.txt This comprehensive Python script combines backtesting and live trading setups using Lumibot. It includes necessary imports, Alpaca configuration, a sample strategy, and the runner logic for both backtesting and live execution. ```python 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() ``` -------------------------------- ### Bitunix Example Usage Source: https://github.com/demierdm/lumibot/blob/dev/docsrc/_build/html/brokers.html Demonstrates a practical example of how to use the Bitunix broker within the LumiBot framework. This could involve initializing the broker and possibly executing a simple trading action. ```python # Example usage of the Bitunix broker from lumibot.brokers import Bitunix from lumibot.strategies import Strategy from lumibot.traders import Trader class MyBitunixStrategy(Strategy): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def on_start(self): self.log_message("Bitunix strategy started.") def on_tick(self): # Example: Fetch account balance balance = self.broker.get_balance() if balance: self.log_message(f"Current balance: {balance}") def on_stop(self): self.log_message("Bitunix strategy stopped.") if __name__ == "__main__": # Initialize the Bitunix broker # Ensure BITUNIX_API_KEY and BITUNIX_API_SECRET are set in environment variables broker = Bitunix() # Initialize the trader trader = Trader(MyBitunixStrategy, broker=broker) # Run the trader trader.run() ``` -------------------------------- ### Tradovate Configuration Examples Source: https://github.com/demierdm/lumibot/blob/dev/docs/brokers.html Provides examples of configuration settings for the Tradovate broker integration. These examples illustrate how to set up environment variables, API keys, and other parameters necessary for LumiBot to connect and trade with Tradovate. ```ini # Example .env file for Tradovate TRADOVATE_API_KEY=your_api_key_here TRADOVATE_SECRET_KEY=your_secret_key_here TRADOVATE_ACCOUNT_ID=your_account_id_here # Optional environment variables TRADOVATE_BASE_URL=https://api.tradovate.com TRADOVATE_WS_URL=wss://stream.tradovate.com/websocket ``` -------------------------------- ### Order Management Examples Source: https://github.com/demierdm/lumibot/blob/dev/docsrc/_build/html/brokers.bitunix.html Provides practical examples for placing limit orders, closing positions, cancelling orders, and checking available cash using the Bitunix broker in Lumibot. ```APIDOC ## Example Usage with Bitunix Broker ### Placing a Limit Order for a Futures Contract ```python from lumibot.entities import Asset, Order asset = Asset("HBARUSDT", Asset.AssetType.CRYPTO_FUTURE) asset.leverage = 5 # Example: set leverage to 5x order = self.create_order( asset=asset, quantity=100, side=Order.OrderSide.BUY, order_type=Order.OrderType.LIMIT, limit_price=0.18 ) submitted_order = self.submit_order(order) if submitted_order: self.log_message(f"Placed order: ID={submitted_order.identifier}, Status={submitted_order.status}") ``` ### Closing a Position ```python # Wait for a few seconds if needed import time time.sleep(10) self.close_position(asset) ``` ### Cancelling Open Orders ```python orders = self.get_orders() for order in orders: if order.asset.symbol == "HBARUSDT" and order.asset.asset_type == Asset.AssetType.CRYPTO_FUTURE and order.status in [ Order.OrderStatus.NEW, Order.OrderStatus.SUBMITTED, Order.OrderStatus.OPEN, Order.OrderStatus.PARTIALLY_FILLED ]: self.cancel_order(order) self.log_message(f"Order {order.identifier} cancellation submitted.") ``` ### Checking Available Cash ```python cash = self.get_cash() self.log_message(f"Current cash {cash}") ``` **Note:** For best results, ensure all funds in your Bitunix Futures account are in USDT. Crypto balances may not be counted as available cash for order sizing. ``` -------------------------------- ### CCXT Full Example Strategy Source: https://github.com/demierdm/lumibot/blob/dev/docsrc/_build/html/brokers.html A comprehensive example demonstrating how to use a broker integrated via the CCXT library within a LumiBot strategy. This would include authentication, fetching data, and placing orders. ```python # Full example strategy using CCXT for a broker (e.g., Binance) from lumibot.brokers import CCXT from lumibot.strategies import Strategy from lumibot.traders import Trader class MyCCXTStrategy(Strategy): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def on_start(self): self.log_message("CCXT strategy started.") def on_tick(self): symbol = "BTC/USDT" exchange_name = "binance" # Fetch ticker information ticker = self.broker.fetch_ticker(symbol) if ticker: self.log_message(f"Current {symbol} price on {exchange_name}: {ticker['last']}") # Example: Place a buy order if price is below a threshold # if ticker['last'] < 50000: # self.submit_order(symbol, 0.001, "buy", exchange=exchange_name) def on_stop(self): self.log_message("CCXT strategy stopped.") if __name__ == "__main__": # Initialize CCXT broker for Binance # Ensure BINANCE_API_KEY and BINANCE_API_SECRET are set in environment variables broker = CCXT(exchange_id='binance') # Initialize trader trader = Trader(MyCCXTStrategy, broker=broker) # Run the trader trader.run() ``` -------------------------------- ### Complete Lumibot Futures Trading Strategy Example (Python) Source: https://github.com/demierdm/lumibot/blob/dev/docsrc/_build/html/_sources/futures.rst.txt Presents a full example of a futures trading strategy implemented with Lumibot. This strategy utilizes continuous futures for reliable backtesting and includes basic logic for fetching prices and a placeholder for a moving average strategy. ```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 ``` -------------------------------- ### Complete Lumibot Backtesting Example Source: https://github.com/demierdm/lumibot/blob/dev/docsrc/_build/html/backtesting.pandas.html A comprehensive example demonstrating the entire process of setting up and running a backtest with Lumibot using Pandas. It includes data downloading, strategy definition, and backtest execution. ```python import yfinance as yf import pandas as pd from lumibot.backtesting import BacktestingBroker, PandasDataBacktesting from lumibot.entities import Asset, Data from lumibot.strategies import Strategy from lumibot.trader import Trader # Download minute data for the last 5 days for AAPL data_download = yf.download("AAPL", period="5d", interval="1m") # Save the data to a CSV file data_download.to_csv("AAPL.csv") # Define Asset and load data asset = Asset( symbol="AAPL", asset_type=Asset.AssetType.STOCK, ) df = pd.read_csv("AAPL.csv") data_obj = Data( asset, df, timestep="minute", ) pandas_data = { asset: data_obj } # Define backtesting parameters backtesting_start = pd.Timestamp("2020-01-02 09:30:00") backtesting_end = pd.Timestamp("2020-01-02 15:59:00") # A simple strategy that buys AAPL on the first day class MyStrategy(Strategy): def on_trading_iteration(self): if self.first_iteration: order = self.create_order("AAPL", 100, "buy") # Run the backtesting trader = Trader(backtest=True) data_source = PandasDataBacktesting( pandas_data=pandas_data, datetime_start=backtesting_start, datetime_end=backtesting_end, ) broker = BacktestingBroker(data_source) strat = MyStrategy( broker=broker, budget=100000, ) trader.add_strategy(strat) trader.run_all() ``` -------------------------------- ### Create Market Buy Order Example Source: https://github.com/demierdm/lumibot/blob/dev/docsrc/_build/html/strategy_methods.misc/strategies.strategy.Strategy.wait_for_orders_registration.html An example demonstrating how to create a market buy order for a specified asset and quantity. This is a fundamental operation for initiating trades within the Lumibot strategy. ```python order1 = self.create_order("SPY", 100, "buy") ``` -------------------------------- ### Install and Upgrade LumiBot using pip Source: https://github.com/demierdm/lumibot/blob/dev/docsrc/_build/html/backtesting.how_to_backtest.html Commands to install LumiBot and upgrade to the latest version using pip. Ensure you have Python and pip installed before running these commands. ```bash pip install lumibot pip install lumibot --upgrade ``` -------------------------------- ### Implement Lumibot Strategy: initialize and on_trading_iteration Source: https://github.com/demierdm/lumibot/blob/dev/docs/_sources/lifecycle_methods.summary.rst.txt This example shows how to implement both the `initialize` and `on_trading_iteration` methods within a Lumibot trading strategy. The `initialize` method is called once at the beginning, before any trading iterations, and is used for setup. The `on_trading_iteration` method contains the primary trading logic executed repeatedly. ```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 ``` -------------------------------- ### Complete Simple Futures Trading Strategy Example in Python Source: https://github.com/demierdm/lumibot/blob/dev/docs/_sources/futures.rst.txt A full Python example of a Lumibot trading strategy that utilizes continuous futures for the Micro E-mini S&P 500 (MES). It demonstrates initializing the asset, logging the trading symbol, and includes a placeholder for implementing a trading logic like a simple moving average. ```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 ``` -------------------------------- ### Lumibot Strategy Initialization Examples Source: https://github.com/demierdm/lumibot/blob/dev/docs/lifecycle_methods.initialize.html Provides multiple examples of initializing a Lumibot strategy's `initialize` method. These examples demonstrate setting different attributes like `sleeptime`, `ticker`, `minutes_before_closing`, `max_bars`, and `count` with various time interval formats (seconds, minutes, hours, days). ```python def initialize(self): self.sleeptime = 5 self.ticker = "AAPL" self.minutes_before_closing = 5 self.max_bars = 100 ``` ```python def initialize(self): # Set the strategy to call on_trading_interation every 2 seconds self.sleeptime = "2S" self.count = 0 ``` ```python def initialize(self): # Set the strategy to call on_trading_interation every 10 minutes self.sleeptime = "10M" self.count = 0 ``` ```python def initialize(self): # Set the strategy to call on_trading_interation every 20 hours self.sleeptime = "20H" self.count = 0 ``` ```python def initialize(self): # Set the strategy to call on_trading_interation every 2 days (48 hours) self.sleeptime = "2D" self.count = 0 ``` -------------------------------- ### Run Backtest with Polygon.io Data in Python Source: https://github.com/demierdm/lumibot/blob/dev/docs/_sources/backtesting.how_to_backtest.rst.txt This Python code demonstrates how to configure and run a backtest using LumiBot with Polygon.io as the data source. It requires a Polygon.io API key, backtesting start and end dates, and a custom trading strategy. ```python from datetime import datetime from lumibot.backtesting import PolygonDataBacktesting from lumibot.strategies import Strategy class MyStrategy(Strategy): parameters = { "symbol": "AAPL", } def initialize(self): self.sleeptime = "1D" # Sleep for 1 day between iterations 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, ``` -------------------------------- ### Install Lumibot using pip Source: https://github.com/demierdm/lumibot/blob/dev/docs/_sources/index.rst.txt This command installs or upgrades the Lumibot package to the latest version. Ensure you have pip installed and accessible in your system's PATH. ```bash pip install lumibot --upgrade ``` ```bash pip install lumibot ``` -------------------------------- ### Lumibot Python Strategy for Crypto Trading with CCXT Source: https://github.com/demierdm/lumibot/blob/dev/docs/_sources/brokers.ccxt.rst.txt A Python example demonstrating how to create a Lumibot trading strategy. It shows how to initialize the market, get the last price of Bitcoin, and place a limit buy order using CCXT integration. ```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 from environment variables) strategy = MyStrategy() strategy.run_live() ``` -------------------------------- ### Complete Lumibot Strategy Example (Backtesting and Live) Source: https://github.com/demierdm/lumibot/blob/dev/docs/index.html This Python code provides a complete example of a Lumibot trading strategy that can be used for both backtesting and live trading. It imports necessary modules from lumibot, configures Alpaca credentials, and defines a simple strategy to buy AAPL on the first iteration. ```python 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() ``` -------------------------------- ### Install DataBento Dependency for Lumibot Source: https://github.com/demierdm/lumibot/blob/dev/docs/_sources/backtesting.databento.rst.txt This command installs the necessary DataBento library for Lumibot integration. Ensure you have pip installed. ```bash pip install databento ``` -------------------------------- ### Interactive Brokers Example Strategy Source: https://github.com/demierdm/lumibot/blob/dev/docsrc/_build/html/brokers.html A sample strategy designed to run with the Interactive Brokers (IBKR) broker. This example likely covers basic interactions like fetching market data or placing simulated orders. ```python # Example strategy for Interactive Brokers from lumibot.brokers import InteractiveBrokers from lumibot.strategies import Strategy from lumibot.traders import Trader class MyIBStrategy(Strategy): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def on_start(self): self.log_message("Interactive Brokers strategy started.") # Subscribe to market data for a symbol self.subscribe_market_data("IBM", "100") # Subscribe to IBM stock, 100ms interval def on_market_data(self, symbol, data): self.log_message(f"Received market data for {symbol}: {data}") # Example: Place an order if price meets a condition # if data['ask'] < 150.0: # self.submit_order(symbol, 10, "buy", account_id=self.broker.account_id) # Use account_id if needed def on_stop(self): self.log_message("Interactive Brokers strategy stopped.") if __name__ == "__main__": # Initialize Interactive Brokers # Ensure IBKR API credentials and connection details are configured (e.g., via environment variables or directly) # For connection, ensure IB TWS or Gateway is running and API is enabled. broker = InteractiveBrokers() # Initialize trader trader = Trader(MyIBStrategy, broker=broker) # Run the trader trader.run() ``` -------------------------------- ### Schwab Example .env Configuration Source: https://github.com/demierdm/lumibot/blob/dev/docs/brokers.html Illustrates the structure of an example `.env` file for configuring the Schwab broker integration. This typically includes API keys, client secrets, and other credentials required for authentication and connecting to Schwab's trading platform. ```dotenv # Example .env file for Schwab integration SCHWAB_API_KEY=your_api_key SCHWAB_CLIENT_SECRET=your_client_secret SCHWAB_ACCOUNT_NUMBER=your_account_number SCHWAB_REFRESH_TOKEN=your_refresh_token # Specify environment (sandbox or production) SCHWAB_ENVIRONMENT=sandbox ``` -------------------------------- ### Lumibot Strategy Example with CCXT Source: https://github.com/demierdm/lumibot/blob/dev/docsrc/_build/html/_sources/brokers.ccxt.rst.txt A basic Lumibot trading strategy in Python that utilizes CCXT for cryptocurrency trading. It includes initializing the market, fetching the last price of Bitcoin, and placing a limit buy order. CCXT automatically detects broker credentials from environment variables. ```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 from environment variables) strategy = MyStrategy() strategy.run_live() ``` -------------------------------- ### Schwab Example Strategy Snippet Source: https://github.com/demierdm/lumibot/blob/dev/docsrc/_build/html/brokers.html A code snippet demonstrating an example strategy for the Schwab broker. This likely involves setting up the broker connection, defining trading logic, and handling market data. ```python # Example strategy snippet for Schwab broker # Ensure you have the necessary environment variables set for API credentials and token management. from lumibot.brokers import Schwab from lumibot.strategies import Strategy from lumibot.traders import Trader class MySchwabStrategy(Strategy): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def on_start(self): self.log_message("Schwab strategy started.") def on_tick(self): # Implement your trading logic here # Example: Get current price and place an order symbol = "AAPL" price = self.get_last_price(symbol) if price: self.log_message(f"Current price of {symbol}: {price}") # self.submit_order(symbol, 10, "buy") # Example order submission def on_stop(self): self.log_message("Schwab strategy stopped.") if __name__ == "__main__": # Initialize the Schwab broker # Ensure SCHWAB_API_KEY, SCHWAB_API_SECRET, SCHWAB_ACCOUNT_ID are set in environment variables broker = Schwab() # Initialize the trader with the strategy and broker trader = Trader(MySchwabStrategy, broker=broker) # Run the trader trader.run() ``` -------------------------------- ### Tradier Full Example Strategy Source: https://github.com/demierdm/lumibot/blob/dev/docsrc/_build/html/brokers.html A complete strategy example for the Tradier broker. This code would illustrate how to connect to Tradier, manage orders, and implement trading logic within LumiBot. ```python # Full example strategy for Tradier broker from lumibot.brokers import Tradier from lumibot.strategies import Strategy from lumibot.traders import Trader class MyTradierStrategy(Strategy): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def on_start(self): self.log_message("Tradier strategy started.") def on_tick(self): # Example: Get account details account_info = self.broker.get_account_info() if account_info: self.log_message(f"Tradier Account Info: {account_info}") # Example: Fetch historical data (if supported) # history = self.broker.get_historical_data('SPY', '1D', 10) # if history: # self.log_message(f"Historical data for SPY: {history}") def on_stop(self): self.log_message("Tradier strategy stopped.") if __name__ == "__main__": # Initialize the Tradier broker # Ensure TRADIER_API_KEY and TRADIER_API_SECRET are set in environment variables broker = Tradier() # Initialize the trader trader = Trader(MyTradierStrategy, broker=broker) # Run the trader trader.run() ``` -------------------------------- ### Schwab Example Strategy Snippet Source: https://github.com/demierdm/lumibot/blob/dev/docs/brokers.html Demonstrates a strategy snippet for the Schwab broker integration. This example likely showcases how to implement trading logic or interact with Schwab's API within the LumiBot framework. It might require specific environment variables for authentication and API access. ```python # Example strategy snippet for Schwab # Requires Schwab API credentials and specific environment variables set. def initialize(self): # Strategy initialization logic pass def handle_data(self, data): # Trading logic based on incoming data pass # Example of placing an order (details depend on LumiBot's Schwab integration) # self.submit_order(symbol='AAPL', qty=10, side='buy', type='market') ``` -------------------------------- ### Get Start Datetime and Timestep Unit (Pandas) Source: https://github.com/demierdm/lumibot/blob/dev/docs/lumibot.data_sources.html Calculates the start datetime and timestep unit for data retrieval. It takes the desired data length and timestep as input, with optional start date and buffer for flexibility. ```python def get_start_datetime_and_ts_unit(_length_, _timestep_, _start_dt=None_, _start_buffer=datetime.timedelta(days=5)_): """Get the start datetime for the data.""" pass ``` -------------------------------- ### LumiBot Backtesting Using Environment Variables Source: https://github.com/demierdm/lumibot/blob/dev/docs/_sources/backtesting.pandas.rst.txt This example demonstrates how to run a LumiBot backtest where the start and end dates are read from environment variables (BACKTESTING_START, BACKTESTING_END) instead of being hardcoded. It defines a simple strategy and loads data, relying on LumiBot to auto-detect the backtesting dates. This requires pandas and lumibot to be installed, and the environment variables to be set. ```python import pandas as pd from lumibot.backtesting import BacktestingBroker, PandasDataBacktesting from lumibot.entities import Asset, Data from lumibot.strategies import Strategy class MyStrategy(Strategy): def on_trading_iteration(self): if self.first_iteration: order = self.create_order("AAPL", 100, "buy") self.submit_order(order) if __name__ == "__main__": df = pd.read_csv("AAPL.csv") asset = Asset(symbol="AAPL", asset_type=Asset.AssetType.STOCK) pandas_data = { asset: Data(asset, df, timestep="minute"), } # We do not specify any backtesting_start or backtesting_end here. # LumiBot will look for them in environment variables (BACKTESTING_START, BACKTESTING_END). result = MyStrategy.run_backtest( PandasDataBacktesting, pandas_data=pandas_data ) ``` -------------------------------- ### Get Start Datetime and Timestep Unit (Pandas) Source: https://github.com/demierdm/lumibot/blob/dev/docsrc/_build/html/lumibot.data_sources.html Retrieves the starting datetime and the appropriate timestep unit based on the provided length and timestep string. It utilizes the Pandas data source. ```python get_start_datetime_and_ts_unit(_length_, _timestep_, _start_dt=None_, _start_buffer=datetime.timedelta(days=5)_) ``` -------------------------------- ### Example Lumibot Strategy with Schwab Integration Source: https://github.com/demierdm/lumibot/blob/dev/docs/_sources/brokers.schwab.rst.txt Demonstrates how to create a trading strategy using Lumibot and Schwab. It shows how to initialize the strategy, fetch the last price of an asset, and submit a buy order. This example assumes Schwab credentials are set up via an environment file or other environment variables. ```python from lumibot.traders import Trader from lumibot.strategies.strategy import Strategy class MyStrategy(Strategy): def initialize(self): self.sleeptime = "1D" self.symbol = "SPY" def on_trading_iteration(self): last = self.get_last_price(self.symbol) self.log_message(f"Last price for {self.symbol}: {last}") asset = self.create_asset(self.symbol) order = self.create_order(asset, 1, "buy") self.submit_order(order) trader = Trader() strategy = MyStrategy() trader.add_strategy(strategy) trader.run_all() ``` -------------------------------- ### Get Round Day Datetime Source: https://github.com/demierdm/lumibot/blob/dev/docsrc/_build/html/lumibot.data_sources.html Returns the current date rounded to the start of the day, with an optional timeshift applied in days. ```APIDOC ## GET /api/data/round_day ### Description Returns the current datetime rounded to the day and applies a timeshift in days. ### Method GET ### Endpoint /api/data/round_day ### Parameters #### Query Parameters - **timeshift** (int) - Optional - The number of days to shift the datetime by. Defaults to 0. ### Response #### Success Response (200) - **datetime** (datetime) - The rounded datetime with the timeshift applied. #### Response Example ```json { "datetime": "2023-10-27T00:00:00Z" } ``` ``` -------------------------------- ### Initialize and Run Lumibot with Interactive Brokers (Python) Source: https://github.com/demierdm/lumibot/blob/dev/docsrc/_build/html/brokers.interactive_brokers_legacy.html This example demonstrates how to set up a Lumibot trader using the Interactive Brokers broker. It imports necessary components, initializes the InteractiveBrokers broker with the defined configuration, assigns a strategy, and then runs the trader. This serves as a complete entry point for a trading bot. ```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() ``` -------------------------------- ### Get Time to Open Source: https://github.com/demierdm/lumibot/blob/dev/docsrc/_build/html/brokers.alpaca.html Retrieves the remaining time in seconds until the market next opens. This helps in planning for the start of trading sessions. ```APIDOC ## GET /api/market/time-to-open ### Description How much time in seconds remains until the market next opens? ### Method GET ### Endpoint /api/market/time-to-open ### Parameters None ### Request Example ```json { "example": "No request body needed" } ``` ### Response #### Success Response (200) - **seconds_until_open** (int) - Number of seconds until the market opens. #### Response Example ```json { "seconds_until_open": 3600 } ``` ``` -------------------------------- ### Close a Futures Position Source: https://github.com/demierdm/lumibot/blob/dev/docs/_sources/brokers.bitunix.rst.txt Provides an example of how to close an existing futures position on Bitunix using Lumibot. ```python # Wait for a few seconds if needed import time time.sleep(10) self.close_position(asset) ``` -------------------------------- ### Complete Futures Strategy Example (Python) Source: https://github.com/demierdm/lumibot/blob/dev/docs/futures.html Presents a full Lumibot strategy example utilizing continuous futures for backtesting. This strategy, `SimpleFuturesStrategy`, initializes by defining the MES continuous future and logging the trading symbol. It then implements a simple moving average (SMA) crossover strategy in the `on_trading_iteration` method to generate buy signals. ```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): self.log_message(f"Buy signal for {self.asset.symbol} at {current_price}") self.submit_order(self.asset, self.order_size) # Sell signal: price below SMA (example - not fully implemented) # elif current_price < sma_20 and position and position.quantity > 0: # self.log_message(f"Sell signal for {self.asset.symbol} at {current_price}") # self.submit_order(self.asset, -self.order_size) ``` -------------------------------- ### Lumibot Get Selling Order Strategy Method Source: https://github.com/demierdm/lumibot/blob/dev/docs/index.html Example of using `self.get_selling_order` to retrieve information about a pending selling order for a given symbol. ```python from lumibot.strategies.strategy import Strategy class MyStrategy(Strategy): def __init__(self, broker, params): super().__init__(broker, params) def on_trading_iteration(self): # Check if there is an existing selling order for AAPL selling_order = self.get_selling_order("AAPL") if selling_order: print(f"Found pending selling order for AAPL: {selling_order.id}") else: print("No pending selling order for AAPL found.") ``` -------------------------------- ### Get Selling Order for a Position (Python) Source: https://github.com/demierdm/lumibot/blob/dev/docsrc/_build/html/strategy_methods.orders/strategies.strategy.Strategy.get_selling_order.html Retrieves the selling order for a given position. This method is part of the Strategy class and requires a Position object as input. It returns an Order object or None if no selling order is found. The example demonstrates how to get a position, retrieve its selling order, and then submit that order. ```python from lumibot.strategies import Strategy from lumibot.entities import Position, Order # Assuming 'self' is an instance of Strategy and has access to other methods like get_position and submit_order # Get the selling order for a position position = self.get_position("SPY") order = self.get_selling_order(position) if order: self.submit_order(order) else: print("No selling order found for the position.") ``` -------------------------------- ### Get Portfolio Value - Python Source: https://github.com/demierdm/lumibot/blob/dev/docs/strategy_properties/lumibot.strategies.strategy.Strategy.portfolio_value.html This example demonstrates how to retrieve and log the current portfolio value using the `portfolio_value` property. It assumes an active Lumibot strategy instance is available. ```python self.log_message(self.portfolio_value) ```