Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display csv with candlestick_ohlc

Tags:

python

pandas

I try to do first steps with pandas.

After a few successful steps I stuck with the following task: display data with OHLC bars.

I downloaded data for Apple stock from Google Finance and stored it to *.csv file.

After a lot of search I wrote the following code:

  import pandas as pd
  import numpy as np
  import matplotlib.pyplot as plt
  import matplotlib.dates as mdates
  import datetime as dt
  from matplotlib.finance import candlestick_ohlc

  #read stored data

  #First two lines of csv:
  #Date,Open,High,Low,Close
  #2010-01-04,30.49,30.64,30.34,30.57

  data = pd.read_csv("AAPL.csv")

  #graph settings
  fig, ax = plt.subplots()
  ax.xaxis_date()
  ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d"))
  plt.xlabel("Date")
  plt.ylabel("Price")
  plt.title("AAPL")

  #convert date to float format 
  data['Date2'] = data['Date'].map(lambda d: mdates.date2num(dt.datetime.strptime(d, "%Y-%m-%d")))

  candlestick_ohlc(ax, (data['Date2'], data['Open'], data['High'], data['Low'], data['Close']))
  plt.show()

But it displays empty graph. What is wrong with this code?

Thanks.

like image 423
Alexei Avatar asked Feb 09 '23 20:02

Alexei


1 Answers

You need to change the last line to combine tuples daily. The following code:

start = dt.datetime(2015, 7, 1)
data = pd.io.data.DataReader('AAPL', 'yahoo', start)
data = data.reset_index()
data['Date2'] = data['Date'].apply(lambda d: mdates.date2num(d.to_pydatetime()))
tuples = [tuple(x) for x in data[['Date2','Open','High','Low','Close']].values]

fig, ax = plt.subplots()
ax.xaxis_date()
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d"))
plt.xticks(rotation=45)
plt.xlabel("Date")
plt.ylabel("Price")
plt.title("AAPL")
candlestick_ohlc(ax, tuples, width=.6, colorup='g', alpha =.4);

Produces the below plot:

Follow link to see the plot!

which you can further tinker with.

like image 133
Sergey Bushmanov Avatar answered Feb 15 '23 10:02

Sergey Bushmanov