2

trying to plot a candlestick serie after importing datas from yahoo-finance. I'm using python 2.7

I have already a serie plotted and I want to add the same one as candlestick but I don't see how I can do that :

import matplotlib.pyplot as plt
from matplotlib.finance import candlestick2_ohlc

#Reset the index to remove Date column from index
df_ohlc = data.reset_index()
#Naming columns
df_ohlc.columns = ["Date","Open","High",'Low',"Close", "Adj Close", "Volume"]
#Normal plot
ax1 = plt.subplot()
ax1.plot(df_ohlc["Date"], df_ohlc["Close"], label = "Price", color="blue", linewidth=2.0)
#Candle plot
candlestick2_ohlc(ax1,df_ohlc['Open'],df_ohlc['High'],df_ohlc['Low'],df_ohlc['Close'],width=0.6)

If I plot candlestick alone, it looks fine but the x axis is a list of integers.

If I plot candlestick alone after converting df_ohlc["Date"] to float then reconverting to datetime, it plots the serie with the correct x axis but there are gaps on the weekend even if the serie isn't defined for these dates.

Is there a way to plot both series at the same time ? I'm planning to add more series like moving average, OLS, Bollinger etc...

Ankur Ankan
  • 2,953
  • 2
  • 23
  • 38
CDVC23
  • 127
  • 2
  • 9
  • As I understand, you want to plot candlestick chart with no gaps and to make xlables actual dates instead of integers. In order to do that, in your data array replace dates with integers starting from 0. In this way, gaps at weekends will disappear. Then to replace integers with dates create list that contains dates and set that xticklabels. You can use 'set_xticklabels' method for doing it. – Elgin Cahangirov Oct 28 '17 at 17:13
  • https://stackoverflow.com/questions/10529492/how-do-i-plot-only-weekdays-using-pythons-matplotlib-candlestick – Elgin Cahangirov Oct 28 '17 at 17:14
  • Im gonna try this out. Thanks – CDVC23 Oct 28 '17 at 18:25
  • So i tryed, i can plot both the line and candlesticks without gap if i use an integer list. But when i use ax1.set_xticklabels with a list to change names, ticks are totally static, if i zoom in, they just dont move. Only the first 10 elements from the list are displayed, the rest never appears. – CDVC23 Oct 28 '17 at 22:31
  • You can customize xticks list as you wish. Of course, setting first 10 elements of your date list xticklabels is not desirable. In order to avoid that, you should choose ten indices from your list which divides your list into 10 equal parts. I recommend you to use numpy linspace function for this task. – Elgin Cahangirov Oct 31 '17 at 17:12

2 Answers2

3

You can remove weekend gaps and make human-readable dates xticklabels in this way. Note that, this script is written in python 3 and there may be some differences from python 2.

import quandl
import numpy as np
from mpl_finance import candlestick_ohlc
import matplotlib.pyplot as plt

# getting data and modifying it to remove gaps at weekends
r = quandl.get('WIKI/AAPL', start_date='2016-01-01', end_date='2017-11-10')
date_list = np.array(r.index.to_pydatetime())
plot_array = np.zeros([len(r), 5])
plot_array[:, 0] = np.arange(plot_array.shape[0])
plot_array[:, 1:] = r.iloc[:, :4]

# plotting candlestick chart
fig, ax = plt.subplots()
num_of_bars = 100  # the number of candlesticks to be plotted
candlestick_ohlc(ax, plot_array[-num_of_bars:], colorup='g', colordown='r')
ax.margins(x=0.0, y=0.1)
ax.yaxis.tick_right()
x_tick_labels = []
ax.set_xlim(right=plot_array[-1, 0]+10)
ax.grid(True, color='k', ls='--', alpha=0.2)
# setting xticklabels actual dates instead of numbers
indices = np.linspace(plot_array[-num_of_bars, 0], plot_array[-1, 0], 8, dtype=int)
for i in indices:
    date_dt = date_list[i]
    date_str = date_dt.strftime('%b-%d')
    x_tick_labels.append(date_str)
ax.set(xticks=indices, xticklabels=x_tick_labels)

plt.show()

enter image description here

Elgin Cahangirov
  • 1,932
  • 4
  • 24
  • 45
0

I really need more information about your code and your dataframe, but you can use this example to do a candlestick

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

#Reset the index to remove Date column from index
df_ohlc = df.reset_index()
#Naming columns
df_ohlc.columns = ["Date","Open","High",'Low',"Close", "Adj Close", "Volume"]
#Converting dates column to float values
df_ohlc['Date'] = df_ohlc['Date'].map(mdates.date2num)

#Making plot
fig = plt.figure()
fig.autofmt_xdate()
ax1 = plt.subplot2grid((6,1), (0,0), rowspan=6, colspan=1)

#Converts raw mdate numbers to dates
ax1.xaxis_date()
plt.xlabel("Date")
print(df_ohlc)

#Making candlestick plot
candlestick_ohlc(ax1,df_ohlc.values,width=1, colorup='g', colordown='k',alpha=0.75)
plt.ylabel("Price")
plt.legend()

plt.show()

Diego muino
  • 96
  • 11
  • Thanks. I tried already this method and there are gaps when its plotted because there is no data on saturday & sunday on financial time series. My datas are loaded this way : data = web.DataReader(str(ent.get()), 'yahoo', start, end).sort_index() – CDVC23 Oct 28 '17 at 18:23
  • You can use a loop for read all dates in a list. ` for j in range(0, len(list)):` ` dates.append(matplotlib.dates.date2num([list[j]` – Diego muino Oct 29 '17 at 21:15