You are on page 1of 7

6/28/22, 3:34 PM MACD calculation for Yahoo finance BTC-USD - Jupyter Notebook

In [ ]: #The MACD is calculated by subtracting the 26-period exponential moving average (EMA) from the 12-period EMA.

In [4]: import pandas as pd


import matplotlib.pyplot as plt
from six import StringIO
import numpy as np
import seaborn as sns
%matplotlib inline
from sklearn import tree
import six
import sys
sys.modules['sklearn.externals.six'] = six

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)

Close Open High Volume

Date

2021-06-28 34434.335938 34679.121094 35219.890625 33892523752

2021-06-29 35867.777344 34475.558594 36542.109375 37901460044

2021-06-30 35040.835938 35908.386719 36074.757812 34059036099

2021-07-01 33572.117188 35035.984375 35035.984375 37838957079

2021-07-02 33897.046875 33549.601562 33939.589844 38728974942

... ... ... ... ...

2022-06-24 21231.656250 21084.648438 21472.917969 24957784918

2022-06-25 21502.337891 21233.609375 21520.914062 18372538715

2022-06-26 21027.294922 21496.494141 21783.724609 18027170497

2022-06-27 20735.478516 21028.238281 21478.089844 20965695707

2022-06-28 20863.091797 20746.535156 20863.091797 21304393728

[366 rows x 4 columns]

localhost:8889/notebooks/MACD calculation for Yahoo finance BTC-USD.ipynb# 1/7


6/28/22, 3:34 PM MACD calculation for Yahoo finance BTC-USD - Jupyter Notebook

In [5]: 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', 'Low']]
# # Calculate MACD values using the pandas_ta library
# df.ta.macd(close='close', fast=12, slow=26, signal=9, append=True)
# Get the 26-day EMA of the closing price
k = df['Close'].ewm(span=12, adjust=False, min_periods=12).mean()
# Get the 12-day EMA of the closing price
d = df['Close'].ewm(span=26, adjust=False, min_periods=26).mean()
# Subtract the 26-day EMA from the 12-Day EMA to get the MACD
macd = k - d
# Get the 9-Day EMA of the MACD for the Trigger line
macd_s = macd.ewm(span=9, adjust=False, min_periods=9).mean()
# Calculate the difference between the MACD - Trigger for the Convergence/Divergence value
macd_h = macd - macd_s
# Add all of our new values for the MACD to the dataframe
df['macd'] = df.index.map(macd)
df['macd_h'] = df.index.map(macd_h)
df['macd_s'] = df.index.map(macd_s)
# View our data
pd.set_option("display.max_columns", None)
print(df)

Close Open High Volume \

Date

2021-06-28 34434.335938 34679.121094 35219.890625 33892523752

2021-06-29 35867.777344 34475.558594 36542.109375 37901460044

2021-06-30 35040.835938 35908.386719 36074.757812 34059036099

2021-07-01 33572.117188 35035.984375 35035.984375 37838957079

2021-07-02 33897.046875 33549.601562 33939.589844 38728974942

... ... ... ... ...

2022-06-24 21231.656250 21084.648438 21472.917969 24957784918

2022-06-25 21502.337891 21233.609375 21520.914062 18372538715

2022-06-26 21027.294922 21496.494141 21783.724609 18027170497

2022-06-27 20735.478516 21028.238281 21478.089844 20965695707

2022-06-28 20860.703125 20746.535156 20860.703125 21333374976

Low macd macd_h macd_s

Date

2021-06-28 33902.074219 NaN NaN NaN

2021-06-29 34252.484375 NaN NaN NaN

localhost:8889/notebooks/MACD calculation for Yahoo finance BTC-USD.ipynb# 2/7


6/28/22, 3:34 PM MACD calculation for Yahoo finance BTC-USD - Jupyter Notebook

2021-06-30 34086.152344 NaN NaN NaN

2021-07-01 32883.781250 NaN NaN NaN

2021-07-02 32770.679688 NaN NaN NaN

... ... ... ... ...

2022-06-24 20777.511719 -2649.820287 -56.601718 -2593.218569

2022-06-25 20964.585938 -2488.411810 83.845407 -2572.257217

2022-06-26 21016.269531 -2371.489373 160.614275 -2532.103648

2022-06-27 20620.199219 -2276.136757 204.773513 -2480.910270

2022-06-28 20577.003906 -2165.501983 252.326630 -2417.828613

[366 rows x 8 columns]

localhost:8889/notebooks/MACD calculation for Yahoo finance BTC-USD.ipynb# 3/7


6/28/22, 3:34 PM MACD calculation for Yahoo finance BTC-USD - Jupyter Notebook

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)

localhost:8889/notebooks/MACD calculation for Yahoo finance BTC-USD.ipynb# 4/7


6/28/22, 3:34 PM MACD calculation for Yahoo finance BTC-USD - Jupyter Notebook

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 [ ]: ​

localhost:8889/notebooks/MACD calculation for Yahoo finance BTC-USD.ipynb# 6/7


6/28/22, 3:34 PM MACD calculation for Yahoo finance BTC-USD - Jupyter Notebook

localhost:8889/notebooks/MACD calculation for Yahoo finance BTC-USD.ipynb# 7/7

You might also like