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.