<jupyter_start><jupyter_text>mplfinance - External Axes Method exerciseGoal: to plot OHLC data along with indicators using the **External Axes Method** of **mplfinance**.Here I am intentionally refraining from applying any chart style: I want to work with a *blank canvas* style that can be further cutomized. This approach can be useful when we want to plot OHLC bars or candlesticks within an exiting project that has already its own graphic design and customization.<jupyter_code>import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import mplfinance as mpf
import sys

print(f"Python version: {sys.version}")
print(f"pandas version:  {pd.__version__}")
print(f"matplotlib version: {mpl.__version__}")
print(f"mplfinance version: {mpf.__version__}")

pd.plotting.register_matplotlib_converters()
%matplotlib inline
data = pd.read_csv("data/QQQ.csv", index_col="Date")
data.index = pd.to_datetime(data.index)

data<jupyter_output><empty_output><jupyter_text>I add three moving averages to the data frame:<jupyter_code>sma_span = 40
ema_span = 15

data['H_sma'] = data['High'].rolling(sma_span).mean()
data['L_sma'] = data['Low'].rolling(sma_span).mean()
data['C_ema'] = data['Close'].ewm(span=ema_span).mean()

data<jupyter_output><empty_output><jupyter_text>For visual clarity, I select only the last 100 rows:<jupyter_code>data_sel = data[-100:]<jupyter_output><empty_output><jupyter_text>In the next chart, if I use `show_nontrading = False` I obtain an error. This is due to the mplfinance feature that removes days with no trading data from the *x* axis.<jupyter_code># here I could use mpf.figure() if I wanted to employ a chart style
# I just use the plain default from matplotlib
fig = plt.figure(figsize=(12,6))

ax = plt.subplot(1,1,1)
mpf.plot(data_sel, ax=ax, show_nontrading = True)
ax.plot(data_sel['H_sma'], color='blue')
ax.plot(data_sel['L_sma'], color='blue')
ax.plot(data_sel['C_ema'], color='red', linestyle = '--')<jupyter_output><empty_output><jupyter_text>The following **workaround** seems to be solve the problem:<jupyter_code>import numpy as np
xpoints = np.arange(len(data_sel))

fig = plt.figure(figsize=(12,6))

ax = plt.subplot(1,1,1)
# show_nontrading defaults to False:
mpf.plot(data_sel, ax=ax)
ax.plot(xpoints, data_sel['H_sma'], color='blue', linewidth = 2)
ax.plot(xpoints, data_sel['L_sma'], color='blue', linewidth =2)
ax.plot(xpoints, data_sel['C_ema'], color='red', linestyle = '--', linewidth = 1.5)<jupyter_output><empty_output><jupyter_text>I could obtain a similar result using the `addplot` feature, although I was not successful when passing `linewidth` as keyword argument.<jupyter_code>fig = plt.figure(figsize=(12,6))

ax = plt.subplot(1,1,1)
ap1 = mpf.make_addplot(data_sel[['H_sma', 'L_sma']], color = 'blue', ax = ax)
ap2 = mpf.make_addplot(data_sel['C_ema'], color = 'red', linestyle='--', ax = ax)
mpf.plot(data_sel, ax=ax, addplot = [ap1, ap2])<jupyter_output><empty_output><jupyter_text>I can use the same workaround to create a chart with an indicator subplot, where the subplot does not make use of mplfinance.<jupyter_code># Adding data for a ROC indicator with lag=9
lag = 9
data['ROC'] = ( data['Adj Close'] / data['Adj Close'].shift(lag) -1 ) * 100

data_sel = data[-100:]
xpoints = np.arange(len(data_sel))

import matplotlib.gridspec as gridspec

fig = plt.figure(figsize=(12,10))
gspec = gridspec.GridSpec(nrows=2, ncols=1, figure=fig, height_ratios= [3, 2])

price_ax = plt.subplot(gspec[0, 0])
roc_ax = plt.subplot(gspec[1,0], sharex=price_ax)

price_ax.set_title("QQQ Daily Price - Candlestick Chart", fontsize=16)

# Using mplfinance to plot a candlestick chart on price_ax:
mpf.plot(data_sel, ax=price_ax, type='candlestick')

# Plotting the ROC indicator using the workaround:
roc_ax.plot(xpoints, data_sel['ROC'], label="9-Day ROC", color="red", linewidth=2)
roc_ax.legend(loc="upper left")

price_ax.get_xaxis().set_visible(False)
fig.subplots_adjust(hspace=0)
roc_ax.axhline(0, color = (.5, .5, .5), linestyle = '--', alpha = 0.5)
price_ax.set_ylabel("Price ($)")
roc_ax.set_ylabel("% ROC")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13980582524271845, 'fraction_numerical': 0.01650485436893204, 'mean_word_length': 6.589318600368324, 'pattern_counts': {'":': 0, '<': 29, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '372010', 'license': 'CC0-1.0', 'n_tokens_mistral': 1551, 'n_tokens_neox': 1507, 'n_words': 391, 'path': 'mplfinance - External Axes exercise.ipynb', 'repo_name': 'stebas101/Visual-Sketchbook', 'size': '4120'}