Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to plot candlesticks in python

I´m trying to create a simple plot with candlesticks. For that I get the data from Yahoo and plot it using the function candlestick2_ohlc. The goal is to export the image in a jpg file using.

This is the code what I´m using:

from pandas_datareader import data
import matplotlib.pyplot as plt
from mpl_finance import candlestick2_ohlc
import matplotlib.dates as mdates
import fix_yahoo_finance as yf
import datetime

start = datetime.date(2018, 1, 1)
end = datetime.date.today()

aapl = yf.download("AAPL",start,end) 
aapl.reset_index(inplace=True)

aapl['Date'] = aapl.index.map(mdates.date2num)

fig, ax = plt.subplots()
plt.xlabel("Date")
plt.ylabel("Price")

candlestick2_ohlc(ax, aapl.Open, aapl.High, aapl.Low, aapl.Close, width=1, colorup='g')
plt.savefig('my_figure.png')
plt.show()

My first question is: there is another simple way to do it? Could you please give me an example to work with finance data? I usually work with quantmod in R.

The second question is: In my example, there is no Date in the X axi. What can I do to show the plot with Dates in the X axi? I should transform the Date into a AX format but I don't know a simple way to do it.

Thanks

like image 717
Alberto Aguilera Avatar asked Dec 09 '18 23:12

Alberto Aguilera


People also ask

How do I make a candlestick chart in Matplotlib?

We have to install mpl_finance. Example 2: Here, we define a dataset of stock prices that contains 5 parameters i.e open, close, high, low, and index (i.e date) and after that, we used pandas.to DateTime to convert the date, and then pandas. astype to convert all of the data to float ().

How do candle graphs work?

Just above and below the real body are the "shadows" or "wicks." The shadows show the high and low prices of that day's trading. If the upper shadow on a down candle is short, it indicates that the open that day was near the high of the day. A short upper shadow on an up day dictates that the close was near the high.


2 Answers

There are many ways of how plotting candlesticks in python using different package like:

  1. mplfinance
  2. plotly
  3. finplot
  4. etc.

You can also create your own specialized version of candlesticks using matplotlib package.

mplfinance Package

You can install the package using the following command:

pip install mplfinance

Then, you should use it as the following:

  1. Indices should be from DatetimeIndex format.
  2. The dataset should have the columns named: High, Open, Close and Low. (it's case-sensitive)
  3. (optional) if you want to show the volume, the Volume named column is required.

PS 1: You can create DatetimeIndex using pandas to_datetime method. PS 2: You can rename a column using rename method on dataframe.

Sample:

import pandas as pd
import mplfinance as mpf

df = pd.read_csv("<dataframe-path>", index_col=0)
mpf.plot(df, type='candle', style='yahoo', volume=True)

plotly Package

First you need to install the plotly package using:

pip install plotly

Then, you can plot the candle plots as easy as the following code:

import plotly.graph_objects as go

import pandas as pd
from datetime import datetime

df = pd.read_csv('your_file_address')

fig = go.Figure(data=[go.Candlestick(x=df['name_of_time_column'],
                open=df['name_of_open_column'],
                high=df['name_of_high_column'],
                low=df['name_of_low_column'],
                close=df['name_of_close_column'])])

fig.show()

finplot Package

You can install finplot package using the following command:

pip install finplot

then, it's really easy to build a candlestick plot.

Example:

import finplot as fplt
import pandas as pd
df = pd.read_csv("<data-path.csv>")

fplt.candlestick_ochl(df[['Open', 'Close', 'High', 'Low']])
fplt.show()
like image 139
Mostafa Ghadimi Avatar answered Oct 19 '22 23:10

Mostafa Ghadimi


finplot has working dates:

import finplot as fplt
import yfinance
df = yfinance.download('AAPL')
fplt.candlestick_ochl(df[['Open', 'Close', 'High', 'Low']])
fplt.show()

finplot shows your dates

Not only does it show your dates, but also has many improvements (too many to list here).

Disclaimer: I dislike matplotlib's and plotly's API's (and performance and lack of functionality), so created finplot. Already it has 9% of the mpl_finance's pypi stars, so check it!

like image 30
Jonas Byström Avatar answered Oct 19 '22 21:10

Jonas Byström