banner



How To Use Candlestick_ohlc To Draw A Simple Candlestick On Python

A quick guide on how to depict these essential charts for stock analysis

OHLC chart with volume — Paradigm by the Author

With a history going back to the 18th century, Open up-High-Low-Close (OHLC) charts are among the most pop financial analysis tools, typically used to illustrate stock prices over time.

In this article, nosotros'll see how to build an OHLC nautical chart with Matplotlib from scratch, explore the advantages and limitations of this visualization, and get a look at a more straightforward approach with mplfinance.

How does an OHLC chart work?

The chart is composed of a series of vertical lines that pack 4 critical variables about the price; The minimum, maximum, initial, and ending values over time, commonly measured in hours, days, or weeks.

OHLC — Image past the author

What's the difference from a Candlestick chart?

OHLC is very similar to Candlestick charts equally they both brandish the same information and are used to illustrate the toll over time. Usually of a stock, currency, bond, commodity, and others.

OHLC and Candlestick charts — Image by the Author

They slightly differ in how they display the data; OHLC open cost is always on the stick's left side and the close price on the right.

Candlesticks don't have markers on the left or correct. They take a box.

The box's filling represents the price'due south direction. Usually, a filled or red box means the price went downwards (Bearish market), so the open price is the rectangle's top part.

An empty or green box means the opposite (Bullish market), and the meridian part of the box is the closing price.

Candlestick — From Investopedia

Matplotlib

Let'south start building our OHLC chart. Offset, we'll import the required libraries.

                import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import math

The information in this example comes from a Kaggle dataset titled S&P 500 stock data.

                df = pd.read_csv('../data/all_stocks_5yr.csv')
df.head()

Data frame'south first 5 rows — Image by the Author

It's an extensive dataset, and we won't be plotting all this data at once, so earlier we start, let's select a smaller subset.

                # filter Apple stocks
df_apple = df[df['Name'] == 'AAPL'].copy()
# convert date column from string to date
df_apple['date'] = pd.to_datetime(df_apple['date'])
# filter records after 2017
df_apple = df_apple[df_apple['date'].dt.twelvemonth > 2017]
df_apple.reset_index(inplace=True)

Now let's plot the sticks. They should extend from the everyman to the highest toll.

Instead of using the date as our x, nosotros'll create a NumPy array for it. That array will get from 0 to the length of our data frame. It'south easier to manipulate a numerical sequence, which will help position the sticks and the markers for open/shut prices.

To draw the lines, we'll iterate through our information frame, plotting a line for each tape of data.

                x = np.arange(0,len(df_apple))
fig, ax = plt.subplots(1, figsize=(12,6))
for idx, val in df_apple.iterrows():
plt.plot([x[idx], x[idx]], [val['low'], val['high']])
plt.testify()

Rainbow lines in a rectangle — Image past the Writer

Crawly, at present nosotros can add together the markers.

                10 = np.arange(0,len(df_apple))
fig, ax = plt.subplots(1, figsize=(12,6))
for idx, val in df_apple.iterrows():
# loftier/depression lines
plt.plot([x[idx], x[idx]],
[val['depression'], val['loftier']],
color='black')
# open marker
plt.plot([x[idx], ten[idx]-0.ane],
[val['open up'], val['open up']],
color='blackness')
# shut marker
plt.plot([10[idx], 10[idx]+0.1],
[val['close'], val['close']],
color='black')
plt.show()

OHLC chart — Image by the Author

There it is! It's pretty easy to plot an OHLC chart with Matplotlib. Unlike candlesticks, you don't need colour or different fillings in the symbols to understand the visualization.

In its simplest form, this chart is readable and relatively straightforward.

Colors

They are not necessary just can take our visualization to another level.

Nosotros'll add a variable with green color at the outset of the loop; then we'll add a condition to check if the open cost was higher than the closing price; when true, nosotros'll modify the color to red.

                x = np.arange(0,len(df_apple))
fig, ax = plt.subplots(1, figsize=(12,half dozen))
for idx, val in df_apple.iterrows():
color = '#2CA453'
if val['open'] > val['close']: color= '#F04730'

plt.plot([x[idx], x[idx]],
[val['depression'], val['high']],
color=color)
plt.plot([ten[idx], x[idx]-0.ane],
[val['open'], val['open']],
colour=color)
plt.plot([10[idx], ten[idx]+0.i],
[val['close'], val['close']],
color=colour)
plt.show()

Color-coded OHLC chart— Image by the Author

Adding color to our OHLC charts makes the past trends way more visible and our visualization more insightful.

Ticks

Our visualization already looks great, but the x-axis is useless equally it is.

Using a numerical sequence as our x helped cartoon the lines and markers, just we tin't tell the dates like this.

We'll use x to position our ticks and the dates as the labels. Nosotros likewise need to consider that if nosotros print every appointment, our x-axis will be unreadable, so we'll skip some values when plotting.

                10 = np.arange(0,len(df_apple))
fig, ax = plt.subplots(1, figsize=(12,6))
for idx, val in df_apple.iterrows():
colour = '#2CA453'
if val['open'] > val['shut']: color= '#F04730'
plt.plot([x[idx], x[idx]],
[val['depression'], val['high']],
color=color)
plt.plot([x[idx], x[idx]-0.1],
[val['open'], val['open']],
color=color)
plt.plot([ten[idx], x[idx]+0.ane],
[val['close'], val['close']],
colour=color)

# ticks
plt.xticks(x[::3], df_apple.date.dt.date[::3])

plt.evidence()

OHLC chart with a proper x-centrality— Image by the Author

That's neat! Now we can add together some styling to our visualization to make information technology more highly-seasoned.

                10 = np.arange(0,len(df_apple))
fig, ax = plt.subplots(1, figsize=(12,6))
for idx, val in df_apple.iterrows():
color = '#2CA453'
if val['open'] > val['close']: color= '#F04730'
plt.plot([ten[idx], ten[idx]], [val['low'], val['high']], color=color)
plt.plot([x[idx], x[idx]-0.one], [val['open'], val['open']], color=color)
plt.plot([x[idx], x[idx]+0.1], [val['shut'], val['close']], colour=color)

# ticks
plt.xticks(10[::iii], df_apple.date.dt.appointment[::3])
ax.set_xticks(x, minor=True)

# labels
plt.ylabel('USD')
# grid
ax.xaxis.grid(color='black', linestyle='dashed', which='both', alpha=0.1)
# remove spines
ax.spines['right'].set_visible(Fake)
ax.spines['tiptop'].set_visible(False)
# title
plt.title('Apple tree Stock Price', loc='left', fontsize=xx)
plt.show()

OHLC chart with details — Prototype by the Author

OHLC charts are a groovy starting signal for analysis since they give us a decent overview on which we can build upon.

Improving and customizing

Y'all can plot some predicted prices, confidence intervals, moving averages, trades volume, and many more than variables and statistics to complement your visualization.

Building our visualization from scratch with Matplotlib gives the states a lot of freedom.

                x = np.arange(0,len(df_apple))
fig, (ax, ax2) = plt.subplots(2, figsize=(12,viii), gridspec_kw={'height_ratios': [4, one]})
for idx, val in df_apple.iterrows():
colour = '#2CA453'
if val['open'] > val['shut']: color= '#F04730'
ax.plot([x[idx], x[idx]], [val['depression'], val['high']], color=color)
ax.plot([ten[idx], ten[idx]-0.i], [val['open'], val['open']], color=color)
ax.plot([x[idx], x[idx]+0.1], [val['close'], val['close']], color=color)

# ticks acme plot
ax2.set_xticks(ten[::iii])
ax2.set_xticklabels(df_apple.date.dt.date[::three])
ax.set_xticks(10, minor=True)

# labels
ax.set_ylabel('USD')
ax2.set_ylabel('Book')
# grid
ax.xaxis.grid(color='black', linestyle='dashed', which='both', alpha=0.1)
ax2.set_axisbelow(True)
ax2.yaxis.grid(color='blackness', linestyle='dashed', which='both', alpha=0.1)
# remove spines
ax.spines['right'].set_visible(Simulated)
ax.spines['left'].set_visible(Simulated)
ax.spines['top'].set_visible(False)
ax2.spines['right'].set_visible(False)
ax2.spines['left'].set_visible(Faux)
# plot volume
ax2.bar(ten, df_apple['book'], color='lightgrey')
# go max volume + x%
mx = df_apple['volume'].max()*1.ane
# ascertain tick locations - 0 to max in 4 steps
yticks_ax2 = np.arange(0, mx+ane, mx/4)
# create labels for ticks. Supersede i.000.000 by 'mi'
yticks_labels_ax2 = ['{:.2f} mi'.format(i/million) for i in yticks_ax2]
ax2.yaxis.tick_right() # Motion ticks to the left side
# plot y ticks / skip first and final values (0 and max)
plt.yticks(yticks_ax2[1:-1], yticks_labels_ax2[1:-i])
plt.ylim(0,mx)

# championship
ax.set_title('Apple Stock Price\due north', loc='left', fontsize=20)
# no spacing betwixt the subplots
plt.subplots_adjust(wspace=0, hspace=0)
plt.show()

OHLC chart with volume — Image by the Writer

Matplotlib Finance

At the starting time of the article, I mentioned an easier way to plot OHLC charts. mplfinance is an excellent pack of utilities for financial visualizations.

                pip install --upgrade mplfinance              

Let's take a look at how easy it is to use information technology.

The data frame should comprise the fields: Open, Close, Loftier, Low, and Book. Information technology also should take a DateTime index.

Our data has the proper fields, so we only need to change the index.

                import mplfinance as mpf                df_google = df[df['Name'] == 'GOOGL'].copy()
df_google['appointment'] = pd.to_datetime(df_google['appointment'])
df_google = df_google[df_google['date'] > pd.to_datetime('2017-12-31')]
df_google = df_google.set_index('date')
mpf.plot(df_google)

OHLC chart — Prototype past the Author

Merely like that, we accept our OHLC chart!

Nosotros can besides add lines for moving average and visualize the volume with a single line of lawmaking.

                mpf.plot(df_google,blazon='candle',mav=(3, 5),volume=True, title='Google')              

OHLC nautical chart with moving averages and volume — Epitome by the Author

Matplotlib Finance utilities are easier to use than drawing the chart from scratch, but they are not easily customizable.

For about quick analysis, you need a functional and readable nautical chart, and mplfinance will be more than enough.

For other more specific constraints, when y'all demand to add a particular component to your visualization or customize the style to follow some blueprint standards, mplfinance may fall short.

Those are the cases where drawing the chart from scratch with Matplotlib pays off. Nosotros can hands add, change, or remove whatever office of the visualization, making it a neat tool to have under your chugalug.

Source: https://towardsdatascience.com/basics-of-ohlc-charts-with-pythons-matplotlib-56d0e745a5be

Posted by: hassourprive.blogspot.com

0 Response to "How To Use Candlestick_ohlc To Draw A Simple Candlestick On Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel