13.08.2022 Views

advanced-algorithmic-trading

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

312

[

"Open", "High", "Low",

"Close", "Volume", "Adj Close"

],

axis=1, inplace=True

)

return df

The following function plot_candlesticks makes use of the Matplotlib candlestick_ohlc

method to create a financial candlestick chart of the provided price series. The majority of

the function involves specific Matplotlib formatting to achieve correct data formatting. The

comments explain each setting in more depth:

def plot_candlesticks(data, since):

"""

Plot a candlestick chart of the prices,

appropriately formatted for dates

"""

# Copy and reset the index of the dataframe

# to only use a subset of the data for plotting

df = copy.deepcopy(data)

df = df[df.index >= since]

df.reset_index(inplace=True)

df[’date_fmt’] = df[’Date’].apply(

lambda date: mdates.date2num(date.to_pydatetime())

)

# Set the axis formatting correctly for dates

# with Mondays highlighted as a "major" tick

mondays = WeekdayLocator(MONDAY)

alldays = DayLocator()

weekFormatter = DateFormatter(’%b %d’)

fig, ax = plt.subplots(figsize=(16,4))

fig.subplots_adjust(bottom=0.2)

ax.xaxis.set_major_locator(mondays)

ax.xaxis.set_minor_locator(alldays)

ax.xaxis.set_major_formatter(weekFormatter)

# Plot the candlestick OHLC chart using black for

# up days and red for down days

csticks = candlestick_ohlc(

ax, df[

[’date_fmt’, ’Open’, ’High’, ’Low’, ’Close’]

].values, width=0.6,

colorup=’#000000’, colordown=’#ff0000’

)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!