Show csv with candlestick_ohlc

I am trying to follow the first steps with pandas.

After several successful steps, I was stuck in the following task: display data using OHLC columns.

I downloaded data for Apple from Google Finance and saved it in a * .csv file.

After a great 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 an empty graph. What is wrong with this code?

Thanks.

+4
source share
1 answer

You need to change the last row 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);

It produces the following graph:

Follow the link to see the plot!

with which you can continue.

+8
source

Source: https://habr.com/ru/post/1611183/


All Articles