Many algorithmic trading strategies make use of technical analysis in order to determine its entries and exits. One form of technical analysis is technical indicators. Technical indicators are functions of price and volume which we can use as signals for entering or exiting positions. Since technical indicators are functions of price and volume, this means that if we have market data and we know the relevant formula, we can calculate our desired technical indicator and use it in our algorithmic trading strategy. However, this can be tedious to manage, especially if we want to create technical indicators across many symbols while also updating our indicators as new data arrives. This is where TA-Lib (Technical Analysis Library) comes in. TA-LIB is a python library which makes it easy to compute, manage and use technical indicators.
Getting Started
To kick things off, we’ll need to install ta-lib and alpaca_trade_api, which will provide the market data we will feed into our indicators.
pip install talib
pip install alpaca-trade-api
To access market data, we’ll need to create an instance of the Alpaca REST client and provide it with our API keys.
import talib as ta
from alpaca_trade_api import REST, TimeFrame
API_KEY = 'Your_API_Key'
SECRET_KEY = 'Your_Secret_Key'
rest_client = REST(API_KEY, SECRET_KEY)
Computing Indicators on Historical Data
Accessing Historical Market Data
Using the rest client, we can query historical market data for a specific stock or cryptocurrency over a desired period. For example, let’s query daily data for SPY between June 2021 and October 2021. We can do this with the following statement.
bars = rest_client.get_bars("SPY", TimeFrame.Day, "2021-06-01", "2021-10-01").df
bars
Simple Moving Average with TA-Lib
The simple moving average (SMA) calculates the average price over a period of bars. It is a rolling average, meaning that it is updated with a new value as each new bar is added.
bars['30_Day_SMA'] = ta.SMA(bars['close'], timeperiod=30)
# plotly imports
import plotly.graph_objects as go
import plotly.express as px
# SPY bar data candlestick plot
candlestick_fig = go.Figure(data=[go.Candlestick(x=bars.index,
open=bars['open'],
high=bars['high'],
low=bars['low'],
close=bars['close'])])
# creating a line plot for our sma
sma_fig = px.line(x=bars.index, y=30_Day_SMA)
# adding both plots onto one chart
fig = go.Figure(data=candlestick_fig.data + sma_fig.data)
# displaying our chart
fig.show()
Bollinger Bands with TA-Lib
Bollinger Bands allow us to measure the volatility of an asset. It does so by calculating the standard deviation of the price over a given period and then looking at multiples of the standard deviation above and below the current market price. If the market price crosses the upper or lower Bollinger Bands, it means that the current price is extreme compared to recent prices.
bars['upper_band'], bars['middle_band'], bars['lower_band'] =
ta.BBANDS(bars['Close'], timeperiod =30)
# creating a line plot for our sma
upper_line_fig = px.line(x=bars.index, y=upper_bands)
# creating a line plot for our sma
Lower_line_fig = px.line(x=bars.index, y=lower_bands)
# adding both plots onto one chart
fig = go.Figure(data=candlestick_fig.data + sma_fig.data + upper_line_fig.data + lower_line_fig.data)
# displaying our chart
fig.show()
Conclusion
TA-Lib contains over 100 indicators to choose from. In addition, with the Market Data API, you can compute indicators across thousands of equites and cryptocurrencies. Take a look at the TA-Lib documentation for more information on how you can integrate technical indicators into your algorithmic trading strategies.
This article is solely for informational purposes only. All images are for illustrative purposes only. Alpaca does not recommend any specific investments or cryptocurrencies or investment strategies. All investments involve risk and the past performance of a security, or financial product does not guarantee future results or returns. Keep in mind that while diversification may help spread risk it does not assure a profit, or protect against loss, in a down market. There is always the potential of losing money when you invest in securities, or other financial products. Investors should consider their investment objectives and risks carefully before investing.
Brokerage services are provided by Alpaca Securities LLC ("Alpaca"), member FINRA/SIPC, a wholly-owned subsidiary of AlpacaDB, Inc. Technology and services are offered by AlpacaDB, Inc.
This is not an offer, solicitation of an offer, or advice to buy or sell securities, or open a brokerage account in any jurisdiction where Alpaca is not registered (Alpaca is registered only in the United States).