In [ ]:
import sys

sys.path.insert(0, ".")
sys.path.append("../")  # import py files from parent folders/..*

Average True Range (ATR)¶

In [ ]:
# Importing Required Libraries
import pandas as pd
import yfinance as yf
import cufflinks as cf
import plotly.offline

cf.go_offline()
cf.set_config_file(offline=False, world_readable=True)

# Define the Ticker Symbol
ticker_symbol = "AAPL"

# Get the data on this ticker
ticker_data = yf.Ticker(ticker_symbol)

# Get the historical prices for the specified period
ticker_df = ticker_data.history(period="1d", start="2023-1-1", end="2023-07-07")

# Calculate True Range and Average True Range
ticker_df['HL'] = ticker_df['High'] - ticker_df['Low']
ticker_df['HC'] = abs(ticker_df['High'] - ticker_df['Close'].shift())
ticker_df['LC'] = abs(ticker_df['Low'] - ticker_df['Close'].shift())
ticker_df['TR'] = ticker_df[['HL', 'HC', 'LC']].max(axis=1)
ticker_df['ATR'] = ticker_df['TR'].rolling(window=14).mean()

# Plot the chart
ticker_df[['Close', 'ATR']].iplot(
    title="Average True Range of " + ticker_symbol,
    xTitle="Date",
    yTitle="Price / ATR",
    secondary_y = 'ATR',
    secondary_y_title = 'ATR',
    theme="pearl",
)