Categories
Algorithmic Trading Uncategorized

How to Get an Asset’s Historical Prices Using Lumibot 

Introduction

Whether it is the daily historical data, tick level data, or the order book data, all these are the historical pricing details of an Asset for a specified period and used in the trading bot to craft simplest to most complex strategies, fundamental analysis, long term trend analysis and fulfilling loads of other requirements. When used in a trading bot, historical price data allows traders to plan their strategies based on the historical performance of that particular asset. In addition to Historical price data being handy for investment analysis, it is also beneficial when it comes to risk assessment and valuation. Hence, traders can do wonders in their trading bot using historical prices. 

Historical data on securities can serve as a record source of information for investors, analysts, and traders, which they can use to develop a more successful trading bot. The knowledge of the past performance of securities while creating the trading bot can help trading programmers gain valuable insights into market trends, and it can also help them make informed investment decisions through their trading bot strategies. Lumibot is a Python trading library that lets us quickly grab the asset’s historical prices, which can be further used to code highly effective strategy. 

Read on to find out how historical Price Data can be used and how it can be easily fetched from possible sources using Lumibot. 

Why You Should Use Historical Data in Your Trading Bot

Historical prices are financial data saved at various intervals, whether days, minutes, or annually. Different historical data types are daily, tick-level, and order-type data. While daily data is suitable for low-frequency trading strategies, the tick-level data is good for high-frequency trading strategies. The importance of using historical data in a trading bot can be understood by realizing that adding historical data to a trading bot can help you make predictions based on past occurrences. Such data can be used in various cases, including below. 

Investment Analysis

The knowledge of past data can not only help us understand future trends but can also help us make informed decisions. Such information is what traders use manually to earn profit in trading, and the same information can be used to program a proper strategy, which is essential when making the trading bot.

  1. Valuation

The valuation of securities is crucial while creating a trading bot strategy, and it’s easier to make a trading bot with such information. With the help of historical prices, it is possible to calculate the intrinsic value and compare it with the market price. Intrinsic value, when compared to the stock’s current market value, helps to determine whether the stock is a good buy or a good sale. The stock is supposed to be a good buy when the current market price of that stock is less than its intrinsic value.

  1. Risk Assessment 

Historical volatility is a statistical evaluation of the distribution of returns for a given financial instrument (security) or market index over a given period. In general, this measure is calculated by calculating the average deviation compared to a security’s average price over a given period. The more volatility there is, the riskier the asset is for trading. Historical volatility is calculated using the asset’s historical price data. This information plays a very crucial role in creating a trading bot strategy, as no strategy is complete without proper risk management.

  1. Machine Learning and Sentiment Analysis

Some bots employ machine learning algorithms to adapt and learn from market data, such as historical price data, and improve their trading strategies. While news plays an essential role in sentiment analysis as well as social media information, historical price data cannot be discarded when it comes to algorithmic trading. Bots could react to historical price data, much like news and social media trends, in real time.

Steps To Use get_historical_price() Method in Lumibot

Prerequisites

Must have Python installed in the system(version 3.10 or above)Install required Python packages.

pip install lumibot

Necessary imports for running the Python file.

from lumibot.strategies import Strategy

Create ALPACA_CONFIG with API KEY and API SECRET by logging in or signing up at https://alpaca.markets/

Steps for Using get_historical_price()

Step 1: Add ALPACA_CONFIG Details

Alpaca is a broker, just like the interactive broker. The details below are required to use the Alpaca broker API.

ALPACA_CONFIG = {
    "API_KEY": "YOUR_API_KEY_HERE", # Get your API Key from
https://alpaca.markets/
    "API_SECRET": "YOUR_SECRET_HERE", # Get your secret from
https://alpaca.markets/
    "PAPER":True # Set to False for real money
}

Step 2: Create a GetHistoricalPrice Class 

Once you have added the Alpaca config detail, create a GetHistoricalPrice class, which will inherit the Strategy class as below.

class GetHistoricalPrice(Strategy):

Step 3: Add  on_trading_iteration() Method 

 

Once you have added the initialize method, follow with the creation of  on_trading_iteration() method as below:

 def on_trading_iteration(self):
        """Get the historical price for an asset"""


        bars = self.get_historical_prices("AAPL", 10, "day")
        df = bars.df

        print(df)

        last_ohlc = df.iloc[-1]


        self.log_message(f"The last closing price of AAPL: {last_ohlc['close']}")
        # Calculate the maximum closing price over the last ten days

        max_close = df['close'].max()
        self.log_message(f"Maximum closing price of AAPL over the last 10 days: {max_close}")

        # Check if the last closing price is the highest

The above code snippet creates the on_trading_iteration() method, which chiefly fetches the asset’s historical price. Details of each term used are below:

Bars: This refers to the price bar or candlestick, which is a graphical representation of the price movement over a specific period of time. There is an open price, high price, low price, and close price, which are self-understood from the terms. For example, a high price means the highest price reached during the period. However, the bars here are variable and have been named as such. For example, the output from the get_historical_price() will have data ranging from open price to dividend and volume. 

bars.df: This is the panda data frame of the historical price data of the specified asset.

Note: The bars  variable is assigned its value through:

bars =  self.get_historical_prices("AAPL", 10, "day")

The data stored in bars is, hence, like open price, close price, etc., as mentioned above. Some others can be volume and dividend.

Iloc[-1]: This integer-location-based indexing method allows users to access data in specific positions in the data frame. It is strictly integer-based, starting from 0 to the length-1 of the axis, and is used for retrieving rows and columns by integer positions.

The above will assign the values from the last row of the PDF to the last_ohlc variable. This variable will store the OHLC (Open, High, Low, Close) data for the last period. The data in the last_ohlc variable can then be applied for further analysis to calculate the most recent OHLC values. Above, we are extracting the last closing price from the data frame and checking whether it is the maximum.

Note 1: Running the Code in the Same File 

In Python, if __name__ == “__main__”: is a conditional statement, which allows you to control the execution of code depending on whether the script is run directly or imported as a module. This implies that the code will run only if runs as a script and not as a module. 

if __name__ == "__main__": 

Step 4: Import Alpaca and Trader 

Import Alpaca and Trader classes from Lumibot.brokers and Lumibot.traders modules. While Alpaca is an interface to the Alpaca trading platform, it leverages us with the functionalities to interact with the Alpaca API for implementing things like placing orders, managing positions, and fetching market data like Historical Price Data, which we are doing in this blog.

The Trader class helps orchestrate the trading process, managing multiple trading strategies, interacting with brokers like Alpaca, Interactive Brokers, and Tradiers, handling order execution and position management, and ensuring a framework for live trading and backtesting. 

from lumibot.brokers import Alpaca
from lumibot.traders import Trader

Step 5: Create Trader Class Object

As you import the Alpaca and Trader class, create the trader object of the Trader() class.

trader = Trader()

Step 6: Create an Object of Alpaca Class

On creation of the trader class object, create the object of the Alpaca class by passing the Alpaca_Config array created above.

broker = Alpaca(ALPACA_CONFIG)

Step 7: Create an Object of GetHistoricalPrice Class

Once we have created the object for the Alpaca class, we will create an object of the GetHistoricalPrice class by passing the Alpaca object (broker) as a parameter to the GetHistoricalPrice class. 

strategy = GetHistoricalPrice(broker=broker)

Step 8: Pass the Strategy to the Trader Class Object

On creation of the object of the GetHistoricalPrice class, add the strategy to the trader class object using the add_strategy() method.

trader.add_strategy(strategy)

Step 9: Start the Overall Trading Process

The code below starts the overall trading process. This typically executes backtesting or a live trading process for a collection of strategies within a trading platform. This command starts the execution engine. It establishes the connection with a broker, which is Alpaca, and starts background tasks like market data ingestion and order management. Briefly, it is the starting point of the trading process.

trader.run_all()

Complete Code

Below is the entire code. Simply paste the code below in a gethistprice.py file, add the Alpaca API and secret keys, install the prerequisites, and run the code. However, ensure the market is open, which applies to US markets. The pre-trading hours start at 4 a.m. and end at 9:30 a.m. The regular trading hours begin at 9:30 a.m. and end at 4 p.m., and the after-trading hours last from 4 p.m. to 8 p.m. All timings are in Eastern Time (ET). Run the below code during regular trading hours.

from lumibot.strategies import Strategy

ALPACA_CONFIG = {
    "API_KEY": "",
    "API_SECRET": "",
    "PAPER": True,
}

class GetHistoricalPrice(Strategy):

    def on_trading_iteration(self):
        """Get the historical price for an asset"""


        bars = self.get_historical_prices("AAPL", 10, "day")
        df = bars.df

        print(df)

        last_ohlc = df.iloc[-1]


        self.log_message(f"The last closing price of AAPL: {last_ohlc['close']}")
        # Calculate the maximum closing price over the last 10 days

        max_close = df['close'].max()
        self.log_message(f"Maximum closing price of AAPL over the last 10 days: {max_close}")

        # Check if the last closing price is the highest


if __name__ == "__main__":
    from lumibot.brokers import Alpaca
    from lumibot.traders import Trader

    trader = Trader()
    broker = Alpaca(ALPACA_CONFIG)
    strategy = GetHistoricalPrice(broker=broker)
    trader.add_strategy(strategy)
    trader.run_all()

Output

Conclusion

Not only can historical price data help traders discover trading opportunities, risk management, and portfolio development, but it also helps evaluate strategies through backtesting. Nowadays, with new technologies like machine learning and sentiment analysis, the historical price data, whether daily, intra-day, tick level, or order type, have become even more powerful weapons for traders as they can predict future trends and compete better with their competitors. New storage technologies from cloud service providers have made the heavy storage requirements quite cheaper. However, having this historical data in-house is not always possible, and the attributes vary for different assets. Thanks to third-party data sources, which now provide highly accurate historical data in real-time. Are you looking to use the asset’s historical price in your Python trading bot using Lumibot to backtest and optimize your trading strategy? Developed by expert developers and financial experts at Lumiwealth, Lumibot is a trading framework that can effortlessly help you add an asset’s historical price to even the most complex trading strategies. Visit our site now to register for a training course where our expert programmers with ample knowledge in trading will teach you the nitty-gritty of algorithmic trading programming in Python using Lumibot.




Categories
Uncategorized

How to Get An Asset’s Last Price Using Lumibot

Introduction

Let’s face it, navigating the dynamic world of financial markets demands a well-defined approach, and it’s here where an asset’s last trading price plays a vital role. Whether you are developing a trading bot for options trading or futures trading, adding the asset’s last price is essential as the bot must consider the price movement each second and work dynamically on the strategy it is built upon. Unlike the closing price, which is the final price at the end of the trading session, the asset’s last price fluctuates as trades occur. It shows the current price of a lump sum transaction where a buyer and seller agree to some terms while trading any security or asset. It offers investors a method to gauge the most recent trading value of a security, offering an alternative for those aiming to make quick gains without engaging in continuous trading.

By adding the asset’s last price to your trading bot, you can not only fetch it in real-time till required but can also automate the code execution and use the refreshed value in your strategy. Built using Python, Lumibot allows you to get the asset’s last price in your trading strategies t. Whether it is to fetch an asset’s last price or a set of asset’s last prices, Lumibot lets users fetch through a few simple lines of code in Python.  

Let’s find out how you can get an asset’s last price using Lumibot’s last price method.

But before getting into the nitty-gritty, let’s find out why you need an asset’s last price in your trading bot.

Why You Need Asset’s Last Price in Your Trading Bot

Whether you want to implement real-time decision-making functionality in your trading bot or calculate the profit target, adding the Asset’s last price to your trading bot is essential. By adding the asset’s last price to your trading bot, you can not only do a proper risk assessment, but you can also create more profitable strategies. 

Read on to find out why you need to add Asset’s Last Price to your trading bot.

  • Real-time Decision-making

It goes without saying that real-time data can be essential for traders who have to make informed decisions every hour, especially for traders who want to implement a real-time decision-making feature in their bot. While implementing different strategies in a trading bot, the first and foremost requirement is the asset’s last price. The value also requires updating each second. Many Python trading bot frameworks like Lumibot come with the asset_last_price() method, which, on implementation, updates the asset’s last price variable each hour with the most recent value.

  • Market Sentiment

In addition to helping you make real-time decisions, adding the asset’s last price to your trading bot can also help you determine the shifts in market sentiment. Furthermore, sudden increases or decreases convey investor perceptions, which impact buying or selling decisions. On this basis, traders can program trading bots to make buying or selling decisions on their own. 

  • Analyzing Price Movements

No matter what trading strategy the traders are looking to make, observing the LTP over a period in the trading bot from an investor perspective is essential as it helps analyze price movements and identify trends in the stock’s performance. Knowing an asset’s last price is a must for technical analysis, where traders study historical price data to predict future price movements.

  • Execution of Market Orders

The trading bots can be triggered to execute the market order using the asset’s last price. While the market order conveys a clear-cut message to buy or sell the asset immediately at the best available price, the asset’s last price helps the traders figure out the market condition. The market order is generally filled at a price different from the last traded price, but the asset’s last price ideally helps in deciding when to execute the market order.

Steps to Use the get_last_price() Method in Lumibot

Prerequisites

Before adding the main code, you need to ensure the following prerequisites:

Must have Python installed in the system(version 3.10 or above)

Setting Up Lumibot

  1. Ensure you have Python installed on your PC. 

Note 1: Users can download the most recent stable version of Python from here.

Note 2: For the screenshots below, we used Pycharm as an IDE.


Check the Python version using the command: python –version

python -version

2. Once you have downloaded and installed Python, install Lumibot using pip: pip install Lumibot from the terminal.

pip install lumibot

3. After you have installed the Lumibot, import the classes below to run the Python file.


import lumibot
from lumibot.strategies import Strategy
from lumibot.entities import Asset
from lumibot.traders import Trader
from datetime import datetime

4. Finally, create ALPACA_CONFIG with API KEY and API SECRET by logging in or signing up at https://alpaca.markets/.

Steps for Using get_last_price()

Step 1: Add ALPACA_CONFIG Details

To get an asset’s last price using Lumibot, you need to configure a broker.

Note: For this blog, ALPACA has been used as a broker.

To use ALPACA broker API, add the API Key and API secret key as below:

ALPACA_CONFIG = {
    "API_KEY": "YOUR_API_KEY_HERE", # Get your API Key from
https://alpaca.markets/
    "API_SECRET": "YOUR_SECRET_HERE", # Get your secret from
https://alpaca.markets/
    "PAPER":True # Set to False for real money
}

Step 2: Create a GetLastPrice Class 

Once you have added ALPACA_CONFIG details, you need to create a GetLastPrice class, which will inherit the Strategy class below.

class GetLastPrice(Strategy):

Step 3: Add Class Parameters

After you have created the GetLastPrice() class, add the class parameters like last_price_symbol and expiry.

parameters = {
        "last_price_symbol": "AAPL",  # The symbol of the asset to get the last Price
        "expiry": datetime(2024, 11, 20),  # The expiry date 
    }


Step 4: Add Initialize Method 

Add an initializing method and set the sleep time as per your preference

  def initialize(self):
        self.sleeptime = "1m" 

Step 5: Add  on_trading_iteration() Method 

Once you have initialized the initialize() method, create the on_trading_iteration() method as below:

  • Create the last_price_symbol variable and assign it the value of last_price_symbol, which is the parameter of the GetLastPrice class in self.parameters. 
  • Create an object of Asset class and set its symbol as last_price_symbol and asset type as stock.
  • The GetLastPrice is the Strategy class, which contains the get_last_price(symbol) method. Call the method using self and pass last_price_symbol as a method parameter. 
  • Finally, using log_message, print the fetched last price for the stock used.
def on_trading_iteration(self):
        """get the last price for an asset"""
        last_price_symbol = self.parameters['last_price_symbol']

        if self.first_iteration:
            asset = Asset(
                symbol=last_price_symbol,
                asset_type='stock',
            )
            last_price = self.get_last_price(last_price_symbol)
            self.log_message(f'Last Price {last_price} for {last_price_symbol}')

Note 1: Running the Code in the Same File
In Python, if name == “main“: is a conditional statement with which you can control the execution of code based on whether the script should be run directly or you require importing as a module. We can run the code from the same file with the help of the code mentioned below.

if __name__ == "__main__": 

Step 6: Import Alpaca and Trader 

Once you have created the class and methods as above, import Alpaca and Trader classes into the main method, as below

from lumibot.brokers import Alpaca
from lumibot.traders import Trader

Step 7: Create Trader Class Object

After you have imported Alpaca and trader, create an object of the Trader Class.

 trader = Trader()

Step 8: Create an Object of Alpaca Class

Created the object of the Alpaca class by passing the Alpaca_Config list created previously.

broker = Alpaca(ALPACA_CONFIG)

Step 9: Create an Object of GetLastPrice Class

Once you have created the object for the Alpaca class, you need to create an object of the GetLastPrice class by passing the alpaca object (broker) as a parameter to the GetLastPrice class.

 strategy = GetLastPrice(broker = broker)

Step 10: Pass the Strategy to Trader Class Object

Using the add_strategy method (), pass the strategy as a parameter, and add the strategy to the object of the Trader() class.

trader.add_strategy(strategy)

Step 11: Execute Strategy for Getting the Last Price of the Asset

Finally, to execute the get_last_prices() method, run the run_all method of the trader class using the trader object

trader.run_all()

Complete Program Code

import lumibot
from lumibot.strategies import Strategy
from lumibot.entities import Asset
from lumibot.traders import Trader
from datetime import datetime

ALPACA_CONFIG = {
    "API_KEY": "",
    "API_SECRET": "",
    "PAPER":True
}

class GetLastPrice(Strategy):
    parameters = {
        "last_price_symbol":"AAPL",  # The symbol of the asset to get the last Price
        "expiry": datetime(2024, 11, 20),  # The expiry date 
    }

    def initialize(self):
        self.sleeptime = "1m"  

    def on_trading_iteration(self):
        """get the last price for an asset"""
        last_price_symbol = self.parameters['last_price_symbol']

        if self.first_iteration:
            asset = Asset(
                symbol=last_price_symbol,
                asset_type='stock',
            )
        last_price = self.get_last_price(last_price_symbol)
        self.log_message(f'Last Price {last_price} for {last_price_symbol}')



if __name__ == "__main__":

        from lumibot.brokers import Alpaca
        from lumibot.traders import Trader

        trader = Trader()
        broker = Alpaca(ALPACA_CONFIG)
        strategy = GetLastPrice(broker = broker)
        trader.add_strategy(strategy)
        trader.run_all()

Output

Conclusion

With the rapid evolution in technology and the improving accessibility of the financial markets, it has become more important than ever to have an in-depth understanding of the last traded price and its impact on trading decisions. Whether you are building a trading bot for options trading or futures, adding the asset’s last price is important as the bot must look into the price movement each second and operate dynamically on the strategy it is built upon. Are you looking to add an asset’s last price to your trading bot using Lumibot? Developed by expert developers and financial experts at Lumiwealth Lumibot is a trading framework that can help you easily add asset’s last price in even the most complex trading strategies effortlessly. Visit our site now to register for a training course where our expert programmers with ample knowledge in trading will teach you the nitty-gritty of algorithmic trading programming in Python using Lumibot. 

Categories
Algorithmic Trading

How to Build an Options Trading Bot with Lumibot

Introduction

With the rise in popularity of options trading and the increase in the use of algorithmic trading, more and more traders have started using Options Trading Bots. Not only can options trading bots remove issues like emotional bias, as is the case in manual trading due to various factors like overconfidence, greed, fear, and personal sentiments towards trades, but they can also protect traders from illogical decision-making, increased risks, and a shattered portfolio, which can otherwise result in losses. Unlike human traders, bots don’t require rest, which allows them to respond to market events in real time, even when the traders are not actively monitoring the markets. Whether you employ a covered call strategy or any other, options trading bots can help you optimize your approach by endlessly monitoring market fluctuations and adjusting your holdings as per the requirements.

When it comes to algorithmic trading, there has always been a demand for a user-friendly library that supports options or any other derivative instrument. Built using Python, Lumibot is one of the top trading libraries for a wide array of derivative instruments, including options trading. With its backtesting and live trading feature, it is a fully-featured, superfast library that allows you to easily create profitable trading robots in many different asset classes.

Let’s find out how to build an options trading bot using Lumibot and take your trading business to new heights.

However, before getting into the nitty-gritty, let’s find out the factors to consider when creating an options trading bot.

Factors to Consider When Creating an Options Trading Bot

Let’s face it, maintaining an edge is of utmost importance in the ever-changing world of options trading. Given the unpredictable market dynamics and the constant nature of the trading market, traders are progressively adopting trading bots driven by Artificial Intelligence (AI) to streamline their strategies and increase their earnings. However, when it comes to making an options trading bot, there are a number of elements that you need to take into consideration. Read on to find out the factors to consider while developing the Options trading bot.

Define Your Strategy

It goes without saying that even excellent trading strategies can result in significant losses, whether in the bullish or the bearish market. It is important to understand the market beforehand to sort out its current state and what a trader can expect in the near future. Needless to say, a good strategy is essential for the success of the trading bot. When it comes to creating an options trading bot, selecting the right strategy is hence essential. If the trader selects the wrong strategy, they can end up with losses and expenses, which can lead to severe setbacks in their trading business. Furthermore, the strategy must be backtested appropriately and results verified by an economic expert before going live trading.

Optimize Your Trading Bot

In addition to defining your strategy, you also need to optimize the strategy used in the trading based on backtesting results to increase profit, though it is also required to face fierce competition. After initial backtests, the strategy’s parameters or rules can be optimized to enhance performance. Factors like risk management, automation, speed, and efficiency can be considered during the optimization of the trading bot. 

Select the Right Trading Platform 

Choosing the right trading platform can make or break your trading bot. As traders, you must select a platform that meets your needs, provides easy-to-use tools and customer support, charges less commission, and ensures security and stability. 

Proper Use of Parameters

When it comes to developing an Options trading bot, parameters like entry price, exit price, stop losses, take profit prices, and various others should be used after deep research as these inputs are crucial for your trading strategy’s success. Furthermore, there should be deep research on underlying strengths, expiry, and premium to set entry, hold until expiry, and price movements to decide the adjustments in stop losses. 

Steps to Create an Options Trading Bot Using Lumibot

Building an options trading bot using Lumibot involves several steps, like defining your strategy, setting up the necessary infrastructure, coding the bot, and testing the bot completely. From determining the parameters to writing trading strategy algorithms using derivative instrument fundamentals, you have to keep in mind several factors. Listed below are the steps to create an options trading bot using Lumibot.

Prerequisites

Before creating an options trading bot using Lumibot, you need to ensure the following prerequisites:

Setting Up Lumibot

  • Ensure you have Python installed on your PC. 

Note 1: Users can download the most recent stable version of Python from here.

Note 2: For the screenshots below, we used Pycharm as an IDE.


Check the Python version using command: Python –version

Python –version

Once you have downloaded and installed Python, install Lumibot using pip: pip install lumibot from the terminal.

pip install lumibot 

Choose a broker that supports options trading and Lumibot integration (e.g., Interactive Brokers). You are not required to do anything for this, as Lumibot will automatically do this for you. 

Options Bot – Backtesting & Live Trading

Step 1 – Lumibot Strategy Code

When it comes to creating an options trading bot using Lumibot, start writing the code as shown below. 

Note: The strategy that is being discussed here is the Long Call Option Buy and Hold until Expiry strategy, which is implemented using the Lumibot.  

Step 1.1 – Imports and Initial Class Definition

To start building the strategy, simply Import the classes as shown below:

from datetime import datetime
from lumibot.entities import Asset
from lumibot.strategies.strategy import Strategy

"""
Strategy Description

An example strategy for buying an option and holding it to expiry.
"""

Imports and Comments

Asset: Represents a financial instrument like a stock or option.

datetime: Used for handling date and time, especially for option expiry dates.

Strategy: Base class for creating trading strategies in Lumibot.

Docstring: Provides a brief description of the strategy.

Step 1.2 – Strategy Class Definition and Parameters

Once you have imported the classes, define the parameters and provide the class definition for the OptionsHotdToExpiry class, as below.

IS_BACKTESTING = True  # Flag to indicate live trading or backtesting
BACKTESTING_START = datetime(2023, 06, 24)
BACKTESTING_END = datetime(2024, 06, 24)

class OptionsHoldToExpiry(Strategy):
  # Define parameters for the strategy
  parameters = {
    "buy_symbol": "SPY",  # The symbol of the asset to buy
    "expiry": datetime(2024, 10, 20),  # The expiry date of the option
    }

Class Definition and Parameters:

OptionsHoldToExpiry inherits from Strategy.

buy_symbol: The ticker symbol of the asset to purchase options on.

expiry: The expiration date for the options.

Step 1.3 – Initialize Method

Once you have provided the class definition and parameter details, provide the implementation code for the initialize method with initial variables and constants.

 def initialize(self):
        # Set initial variables or constants
        # Built-in variable for the sleep time between iterations
        self.sleeptime = "1D"  # Sleep for 1 day between iterations

initialize Method:

Called once at the start of the strategy.

self.sleeptime: Sets the interval between each trading iteration to 1 day.

Step 1.4- on_trading_iteration Method

The following method is executed to buy the traded symbol once and then never again. So, this method is only invoked once.

 def on_trading_iteration(self):
      """Buys the self.buy_symbol once, then never again"""

      buy_symbol = self.parameters["buy_symbol"]
      expiry = self.parameters["expiry"]

      # What to do each iteration
      underlying_price = self.get_last_price(buy_symbol)
      self.log_message(f"The value of {buy_symbol} is {underlying_price}")

      if self.first_iteration:
          # Calculate the strike price (round to nearest 1)
          strike = round(underlying_price)

          # Create options asset
          asset = Asset(
              symbol=buy_symbol,
              asset_type="option",
              expiration=expiry,
              strike=strike,
              right="call",
          )

          # Create order
          order = self.create_order(
              asset,
              10,
              "buy_to_open",
          )

          # Submit order
          self.submit_order(order)

          # Log a message
          self.log_message(f"Bought {order.quantity} of {asset}")

on_trading_iteration Method:

Called on each trading iteration.

Retrieves buy_symbol and expiry from parameters.

Gets the last price of the asset and logs it.

On the first iteration:

Calculate the strike price by rounding the last price.

Creates an Asset instance representing the option.

Creates an order to buy the option.

Submit the order.

Logs the purchase.

Step 1.5 – Main Block for Running the Strategy

Finally, write the main block, which handles the entire operation based on the constants and variables, i.e. if IS_BACKTESTING = TRUE Then, the bot will do the backtesting, or otherwise, it will do the live trading. In this block, you also need to pass the configurations from your broker or the Polygon.io API key. Polygon.io provides the historical data for backtesting. 

if __name__ == "__main__":

    
        from lumibot.backtesting import PolygonDataBacktesting

        # Define the backtesting period

        # Run backtesting on the strategy
        results = OptionsHoldToExpiry.backtest(
            PolygonDataBacktesting,
            BACKTESTING_START,
            BACKTESTING_END,
            benchmark_asset="SPY",
            polygon_api_key="Mention API Key here",  # Add your polygon API key here
        )

   

      

Main Block:

Determines whether to run the strategy live or in backtesting mode based on the is_live flag.

Live Trading:

Imports credentials and modules for live trading.

Creates a Trader and InteractiveBrokers instance.

Initializes the strategy with the broker.

Adds the strategy to the trader.

Runs all strategies.

Backtesting:

Imports the module for backtesting.

Defines the backtesting period.

Runs backtesting on the strategy with specified parameters and logs the results. Developers need to create an account in Polygon.io and paste the API key from there above for backtesting.

Backtesting or Live Trading

Lumibot allows you to backtest your strategy using historical data as well as run it for live trading. 

Backtesting

Polygon.io provides the historical data for any mentioned time period (historical data), and we need to create a free account for it, as well as add the API key in the main code and run the code in  Pycharm, a popular IDE for Polygon.io.

Live Testing

The code snippet above initializes Lumibot for live trading with Interactive Brokers (IB). 

Below are the details:

Conditional Check:

if is_live:: It is first required if the is_live is true. The program will run for live trading if this is set as true.

The INTERACTIVE_BROKERS_CONFIG variable contains the Interactive broker’s account credentials. It’s not shown in the code above as we are not performing live trading here. The live trading will be discussed later in some other blog.

from lumibot.brokers import InteractiveBrokers

This line imports the InteractiveBrokers class from the lumibot.brokers module, and this caters to the developers an interface to connect with IB.

from lumibot.traders import Trader

This line shows how the developers can import the Trader class from the lumibot.traders module. Remember it is the Lumibot that manages the execution of trading strategies.

Live Trading Objects:

trader = Trader()

This line is required for the creation of the Trader object, which is necessary for running the trading strategies.

broker = InteractiveBrokers(INTERACTIVE_BROKERS_CONFIG)

This line is written for the creation of the InteractiveBrokers object, ensuring the connection and communication with the developer’s IB account with the help of the Interactive broker credentials.

Strategy and Trader Setup:

strategy = OptionsHoldToExpiry(broker=broker)

This is how an instance of a strategy named OptionsHoldToExpiry can be created. This strategy focuses on buying options and holding them until expiry. The broker argument ensures the connection to your IB account for the execution of the order.

trader.add_strategy(strategy)

This line is written for adding the created OptionsHoldToExpiry strategy to the Trader object. For a trader its possible to manage multiple strategies in parallel.

Live Trading Execution:

strategy_executors = trader.run_all():

This line initiates the live execution of the trading strategies managed by the Trader object. Since InteractiveBrokers is used as the broker, trades will be placed on your IB account based on the logic of the OptionsHoldToExpiry strategy.

Important Note: Make sure your IB account credentials are secure. You can do this by storing such sensitive details in a separate credentials.py file, which should not be shared and likely uses secure methods to store your keys. If we add this in gitignore, it will not be shared while we share the code through a GitHub account.

Conclusion

In the fast-paced world of options trading, where market shifts occur around the clock, traders are seeking new ways to optimize their strategies and boost their profits. The emergence of options trading bots has provided a powerful solution to navigate this dynamic landscape. Developed by expert developers and financial experts at Lumiwealth, Lumibot can help traders build a trading strategy that can help them beat the fierce competition. From the ability to operate non-stop and manage multiple markets to the precision and speed of execution, options trading bots created using Lumibot provide a level of efficiency that is challenging to achieve with manual trading. With minor programming skills, traders can develop an outstanding trading bot using different derivative instrument concepts to make a fortune that can help them ensure a good life for their families. So, what are you waiting for? Register for our paid training classes on our website, or attend free classes to confirm what we have for you here:  lumiwealth.com/2-hour-algo-slo-page-current