In last article, I have demo how to download stock historical data from Yahoo finance server, and plot a simple candlestick chart. In this article, I am going to use the same daily data (in csv format) to plot candlestick chart in monthly (or weekly) interval.

How……?

You do not need to group the data manually or by complex program coding. In python programming language, there is a function called “resample”. By using this function, it will group the data with 1 line of code. Here is the source code:

Google stock candlestick chart in monthly interval
Google stock candlestick chart in monthly interval

 

YouTube video here:

 

Copy source code here:

import pandas as pd
import mplfinance as mpf

# stockname = 'GOOGL'
stockname = input("Input stock code here: ")

filepath = 'C:/pythonprojects/stocks/' + stockname + '.csv'

df = pd.read_csv(filepath, index_col=0, parse_dates=True)
totalrows = len(df.index)
print('total rows = ' + str(totalrows))

df = df.resample('M').agg({'Open': 'first', 'High': 'max', 'Low': 'min', 'Close': 'last', 'Volume': 'sum'})
totalrows = len(df.index)
print('total weeks or months = ' + str(totalrows))

mystyle = mpf.make_mpf_style(base_mpf_style='yahoo', mavcolors=["red", "blue", "fuchsia"])

mpf.plot(df, type='candle', style=mystyle, figscale=1.5, figratio=(18, 9), mav=(10, 20, 50), volume=True, title=stockname)
  • Line 5, instead of hardcode the stock code in program, we can use interactive input from console. Play the demo video to find out.
  • Line 7, assume you already downloaded the stock historical data and stored in the file path. If not, please use the last demo to download it first.
  • Line 9, read the csv file and store data into variable df
  • Line 13, use “resample” function to group the data. Use “W” for week, “M” for month, “Q” for quarter. Since yahoo daily data does not contain time, minute (“T”) or second (“S”) is not applicable.
  • Line 17-19, same as last 2 demo, we plot the chart in candlestick style, with simple moving average in 10, 20 and 50 units, showing volume in total of the interval.