Professional Documents
Culture Documents
In [ ]: #The MACD is calculated by subtracting the 26-period exponential moving average (EMA) from the 12-period EMA.
In [1]: '''
The moving average convergence divergence (MACD) helps traders of
sorts time their entries and exits with market momentum to minimize drawdowns.
'''
import yfinance as yf
# Request historic pricing data via finance.yahoo.com API
df = yf.Ticker('BTC-USD').history(period='1y')[['Close', 'Open', 'High', 'Volume']]
# View our data
print(df)
Date
Date
Date
In [12]: '''
Visualizing the MACD in Python with Plotly
Chart the price as a Candlestick visualization similar to the chart seen above;
Chart the MACD and Signal lines in a second chart, below the Candlestick;
Chart the Convergence/Divergence series as a Histogram overlaying our signal lines.
'''
import pandas_ta as ta
from plotly.subplots import make_subplots
import plotly.graph_objects as go
# get ticker data
df = yf.Ticker('BTC-USD').history(period='1y')[map(str.title, ['open', 'close', 'low', 'high', 'volume'])]
# calculate MACD values
df.ta.macd(close='close', fast=12, slow=26, append=True)
# Force lowercase (optional)
df.columns = [x.lower() for x in df.columns]
# Construct a 2 x 1 Plotly figure
fig = make_subplots(rows=2, cols=1)
# price Line
fig.append_trace(
go.Scatter(
x=df.index,
y=df['open'],
line=dict(color='#ff9900', width=1),
name='open',
# showlegend=False,
legendgroup='1',
), row=1, col=1
)
# Candlestick chart for pricing
fig.append_trace(
go.Candlestick(
x=df.index,
open=df['open'],
high=df['high'],
low=df['low'],
close=df['close'],
increasing_line_color='#ff9900',
decreasing_line_color='black',
showlegend=False
), row=1, col=1
)
# Fast Signal (%k)
fig.append_trace(
go.Scatter(
x=df.index,
y=df['macd_12_26_9'],
line=dict(color='#ff9900', width=2),
name='macd',
# showlegend=False,
legendgroup='2',
), row=2, col=1
)
# Slow signal (%d)
fig.append_trace(
go.Scatter(
x=df.index,
y=df['macds_12_26_9'],
line=dict(color='#000000', width=2),
# showlegend=False,
legendgroup='2',
name='signal'
), row=2, col=1
)
# Colorize the histogram values
colors = np.where(df['macdh_12_26_9'] < 0, '#000', '#ff9900')
# Plot the histogram
fig.append_trace(
go.Bar(
x=df.index,
y=df['macdh_12_26_9'],
name='histogram',
marker_color=colors,
), row=2, col=1
)
# Make it pretty
layout = go.Layout(
plot_bgcolor='#efefef',
# Font Families
font_family='Monospace',
font_color='#000000',
font_size=20,
xaxis=dict(
rangeslider=dict(
visible=False
)
localhost:8889/notebooks/MACD calculation for Yahoo finance BTC-USD.ipynb# 5/7
6/28/22, 3:34 PM MACD calculation for Yahoo finance BTC-USD - Jupyter Notebook
)
)
# Update options and show plot
fig.update_layout(layout)
fig.show()
60k
40k
20k
Jul 2021 Sep 2021 Nov 2021 Jan 2022 Mar 2022 May 2022
4000
2000
0
−2000
J l 2021 S 2021 N 2021 J 2022 M 2022 M 2022
In [ ]: