candlestick plot from pandas dataframe, replace index by dates

python candlestick chart
python interactive candlestick chart
candlestick chart python plotly
dash candlestick chart python
python candlestick patterns
how to make a stock chart in python
candlestick chart creator
mpl_finance

This code gives plot of candlesticks with moving averages but the x-axis is in index, I need the x-axis in dates. What changes are required?

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_finance import candlestick2_ohlc

#date format in data-> dd-mm-yyyy
nif = pd.read_csv('data.csv')   


#nif['Date'] = pd.to_datetime(nif['Date'], format='%d-%m-%Y', utc=True)

mavg = nif['Close'].ewm(span=50).mean()
mavg1 = nif['Close'].ewm(span=13).mean()

fg, ax1 = plt.subplots()

cl = candlestick2_ohlc(ax=ax1,opens=nif['Open'],highs=nif['High'],lows=nif['Low'],closes=nif['Close'],width=0.4, colorup='#77d879', colordown='#db3f3f')

mavg.plot(ax=ax1,label='50_ema')
mavg1.plot(color='k',ax=ax1, label='13_ema')

plt.legend(loc=4)
plt.subplots_adjust(left=0.09, bottom=0.20, right=0.94, top=0.90, wspace=0.2, hspace=0)
plt.show()

Output:

I also had a lot of "fun" with this in the past... Here is one way of doing it using mdates:

import pandas as pd
import pandas_datareader.data as web
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib.finance import candlestick_ohlc
import matplotlib.dates as mdates

ticker = 'MCD'
start = dt.date(2014, 1, 1)

#Gathering the data
data = web.DataReader(ticker, 'yahoo', start)


#Calc moving average
data['MA10'] = data['Adj Close'].rolling(window=10).mean()
data['MA60'] = data['Adj Close'].rolling(window=60).mean()
data.reset_index(inplace=True)
data['Date']=mdates.date2num(data['Date'].astype(dt.date))

#Plot candlestick chart
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = fig.add_subplot(111)
ax3 = fig.add_subplot(111)
ax1.xaxis_date()
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))
ax2.plot(data.Date, data['MA10'], label='MA_10')
ax3.plot(data.Date, data['MA60'], label='MA_60')
plt.ylabel("Price")
plt.title(ticker)
ax1.grid(True)
plt.legend(loc='best')
plt.xticks(rotation=45)
candlestick_ohlc(ax1, data.values, width=0.6, colorup='g', colordown='r')
plt.show()

Output:

Hope this helps.

Plot Candlestick Charts in Python, In this tutorial we are going to learn how to plot these with Python. four relevant columns in the right order and replacing our current data frame. So what we do is, we drop the index and map the date2num function onto our Date column. I didn't notice I was using the wrong function (candlestick_ohlc instead of candlestick2_ohlc), which explained why I didn't manage to make work the documentation I looked about my issue. I tried to do the same as I found here: Overlapping Dates in Candlestick Plot from a Pandas DataFrame

Clunky workaround here, derived from other post (if i can find again, will reference). Using a pandas df, plot by index and then reference xaxis tick labels to date strings for display. Am new to python / matplotlib, and this this solution is not so flexible, but it works basically. Also using a pd index for plotting removes the blank 'weekend' daily spaces on market price data. Matplotlib xaxis index as dates

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_finance import candlestick2_ohlc
from mpl_finance import candlestick_ohlc

%matplotlib notebook # for Jupyter

# Format m/d/Y,Open,High,Low,Close,Adj Close,Volume
# csv data does not include NaN, or 'weekend' lines, 
# only dates from which prices are recorded
DJIA = pd.read_csv('yourFILE.csv') #Format m/d/Y,Open,High,
    Low,Close,Adj Close,Volume

print(DJIA.head())

fg, ax1 = plt.subplots()

cl =candlestick2_ohlc(ax=ax1,opens=DJIA['Open'],
    highs=DJIA['High'],lows=DJIA['Low'],
    closes=DJIA['Close'],width=0.4, colorup='#77d879', 
    colordown='#db3f3f')

ax1.set_xticks(np.arange(len(DJIA)))
ax1.set_xticklabels(DJIA['Date'], fontsize=6, rotation=-90)

plt.show()

ENH: Add ohlc / candlestick plotting option for DataFrame · Issue , Mixing ordinal and datetime index plots on the same axes wouldn't work. The module itself is If we were to change the plot functions to lookup kind Candlestick plot, Pandas and Seaborn mwaskom/seaborn#387. Closed. I would like create a daily candlestick plot from data i downloaded from yahoo using pandas. Plotting candlestick data from a dataframe in Python and plots it

Simple df:

Using plotly:

import plotly.figure_factory
fig = plotly.figure_factory.create_candlestick(df.open, df.high, df.low, df.close, dates=df.ts)
fig.show()

will automatically parse the ts column to be displayed correctly on x.

Pandas dataframe candlestick, The . plotting import figure, show, output_file df = pd. dates. Must have the same index as df. technicals: A list of additional data series to Replace method in​  Firstly, we have made the necessary imports, we will be using matplotlib.pyplot() to plot the chart, candlestick_ohlc() from mpl_finance to plot the Matplotlib Candlestick chart, Pandas to extract datetime-CSV data using read_csv() method, matplotlib.dates for formatting the datetime data in Matplotlib. We are using the style ‘ggplot’.

How to plot simple and Candlestick chart using Python, Simple timeseries plot and candlestick are basic graphs used by technical analyst for identifying the trend. Simple time Series Chart using Python – pandas matplotlib. Here is the Converting date to pandas datetime format. df['Date'] ax.plot(ohlc.index, df['SMA100'], color = 'blue', label = 'SMA100'). I have a pandas DataFrame that looks like this training.head() The DataFrame has been sorted by date. I'd like to make a scatterplot where the date of the campaign is on the x axis and the rate of success is on the y axis. I was able to get a line graph by using training.plot(x='date',y='rate').

Plot Candlestick Charts in Research, It makes a candlestick chart from the dataframe returned by get_pricing. I wrote this to use in my research notebooks and it has made me  Replace values given in to_replace with value. Values of the DataFrame are replaced with other values dynamically. This differs from updating with .loc or .iloc, which require you to specify a location to update with some value. How to find the values that will be replaced. First, if to_replace and value are both lists, they must be the same

Matplotlib 2.x By Example, FacetGrid, factor plot, and pair plot may take up a lot of space when we need to handy if you want the maximize space efficiency--Heatmaps and Candlestick plots. function expects a 2D list, 2D Numpy array, or pandas DataFrame as input. names as columns, date as index, and the change in closing price as values. pandas.DataFrame.set_index¶ DataFrame.set_index (self, keys, drop=True, append=False, inplace=False, verify_integrity=False) [source] ¶ Set the DataFrame index using existing columns. Set the DataFrame index (row labels) using one or more existing columns or arrays (of the correct length). The index can replace the existing index or expand on it.

Comments
  • if my reply below helped you achieve what you needed, would appreciate if you accepted my answer..