6.6 KiB
This notebook demonstrates the use of technical indicators for stock analysis using OpenBB Terminal and TA-Lib. It loads historical stock prices for Apple (AAPL) and calculates Bollinger Bands (BBANDS), Relative Strength Index (RSI), and Moving Average Convergence Divergence (MACD). The data is then visualized to provide insights into stock price trends and potential trading signals. This analysis is useful for investors and traders to make informed decisions based on technical analysis.
import matplotlib.pyplot as plt import pandas as pd from talib import RSI, BBANDS, MACD
from openbb_terminal.sdk import openbb from openbb_terminal.sdk import TerminalStyle theme = TerminalStyle("light", "light", "light")
Load historical stock data for Apple (AAPL) and rename 'Adj Close' to 'close'
data = ( openbb .stocks .load("AAPL", start_date="2020-01-01") .rename(columns={"Adj Close": "close"}) )
Calculate Bollinger Bands (BBANDS) for the close prices with a 21-day period
up, mid, low = BBANDS( data.close, timeperiod=21, nbdevup=2, nbdevdn=2, matype=0 )
Calculate Relative Strength Index (RSI) for the close prices with a 14-day period
rsi = RSI(data.close, timeperiod=14)
Calculate Moving Average Convergence Divergence (MACD) for the close prices with standard parameters
macd, macdsignal, macdhist = MACD( data.close, fastperiod=12, slowperiod=26, signalperiod=9 )
Create a DataFrame for the MACD components
macd = pd.DataFrame( { "MACD": macd, "MACD Signal": macdsignal, "MACD History": macdhist, } )
Create a DataFrame for the stock data and technical indicators
data = pd.DataFrame( { "AAPL": data.close, "BB Up": up, "BB Mid": mid, "BB down": low, "RSI": rsi, } )
Plot the Bollinger Bands, RSI, and MACD indicators in subplots
fig, axes = plt.subplots( nrows=3, figsize=(15, 10), sharex=True )
Plot Bollinger Bands and close prices
data.drop(["RSI"], axis=1).plot( ax=axes[0], lw=1, title="BBANDS" )
Plot RSI and add horizontal lines at 70 and 30 to indicate overbought and oversold levels
data["RSI"].plot( ax=axes[1], lw=1, title="RSI" ) axes[1].axhline(70, lw=1, ls="--", c="k") axes[1].axhline(30, lw=1, ls="--", c="k")
Plot MACD components
macd.plot( ax=axes[2], lw=1, title="MACD", rot=0 ) axes[2].set_xlabel("") fig.tight_layout()
PyQuant News is where finance practitioners level up with Python for quant finance, algorithmic trading, and market data analysis. Looking to get started? Check out the fastest growing, top-selling course to get started with Python for quant finance. For educational purposes. Not investment advise. Use at your own risk.
