Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting candlestick data from a dataframe in Python

I would like create a daily candlestick plot from data i downloaded from yahoo using pandas. I'm having trouble figuring out how to use the candlestick matplotlib function in this context. Here is the code:

#The following example, downloads stock data from Yahoo and plots it.
from pandas.io.data import get_data_yahoo
import matplotlib.pyplot as plt

from matplotlib.pyplot import subplots, draw
from matplotlib.finance import candlestick

symbol = "GOOG"

data = get_data_yahoo(symbol, start = '2013-9-01', end = '2013-10-23')[['Open','Close','High','Low','Volume']]

ax = subplots()

candlestick(ax,data['Open'],data['High'],data['Low'],data['Close'])

Thanks

Andrew.

like image 298
user2918258 Avatar asked Oct 25 '13 02:10

user2918258


2 Answers

Using bokeh:

import io
from math import pi
import pandas as pd
from bokeh.plotting import figure, show, output_file

df = pd.read_csv(
    io.BytesIO(
        b'''Date,Open,High,Low,Close
2016-06-01,69.6,70.2,69.44,69.76
2016-06-02,70.0,70.15,69.45,69.54
2016-06-03,69.51,70.48,68.62,68.91
2016-06-04,69.51,70.48,68.62,68.91
2016-06-05,69.51,70.48,68.62,68.91
2016-06-06,70.49,71.44,69.84,70.11
2016-06-07,70.11,70.11,68.0,68.35'''
    )
)

df["Date"] = pd.to_datetime(df["Date"])

inc = df.Close > df.Open
dec = df.Open > df.Close
w = 12*60*60*1000

TOOLS = "pan,wheel_zoom,box_zoom,reset,save"

p = figure(x_axis_type="datetime", tools=TOOLS, plot_width=1000, title
= "Candlestick")
p.xaxis.major_label_orientation = pi/4
p.grid.grid_line_alpha=0.3

p.segment(df.Date, df.High, df.Date, df.Low, color="black")
p.vbar(df.Date[inc], w, df.Open[inc], df.Close[inc], fill_color="#D5E1DD", line_color="black")
p.vbar(df.Date[dec], w, df.Open[dec], df.Close[dec], fill_color="#F2583E", line_color="black")

output_file("candlestick.html", title="candlestick.py example")

show(p)

Candlestick plot from a Pandas DataFrame

Code above forked from here: http://docs.bokeh.org/en/latest/docs/gallery/candlestick.html

like image 110
ox. Avatar answered Oct 19 '22 21:10

ox.


I have no reputation to comment @randall-goodwin answer, but for pandas 0.16.2 line:

# convert the datetime64 column in the dataframe to 'float days'
data.Date = mdates.date2num(data.Date)

must be:

data.Date = mdates.date2num(data.Date.dt.to_pydatetime())

because matplotlib does not support the numpy datetime64 dtype

like image 41
El Ruso Avatar answered Oct 19 '22 21:10

El Ruso