In first article, I have demo plot a simple candlestick chart with stock historical data (downloaded in csv data format). This webpage will demo how to plot 2 set of stock data on the same graph. This is to find out if one stock is leading another one. Pairs trading investor may found this useful.

 

Pairs trade HK0347 with HK0358
Pairs trade HK0347 with HK0358

 

YouTube demo video here:

 

Copy program source code here. Please review our terms of use.

import pandas as pd
import mplfinance as mpf


myinput1 = input("Input stock code here: ")
myinput2 = input("Input another stock code: ")

stockname1 = 'HK' + myinput1
filepath1 = 'C:/pythonprojects/stocks/' + stockname1 + '.csv'

stockname2 = 'HK' + myinput2
filepath2 = 'C:/pythonprojects/stocks/' + stockname2 + '.csv'

df1 = pd.read_csv(filepath1, index_col=0, parse_dates=True)
df1 = df1.loc['2010-01-01':, :]
df2 = pd.read_csv(filepath2, index_col=0, parse_dates=True)
df2 = df2.loc['2010-01-01':, :]

totalrows1 = len(df1.index)
print('total rows of ' + stockname1 + ' = ' + str(totalrows1))

totalrows2 = len(df2.index)
print('total rows of ' + stockname2 + ' = ' + str(totalrows2))


if totalrows1 != totalrows2:
    print('Data length not matched. Exit now.')
    exit()

print('continue ...')

line2 = mpf.make_addplot(df2['Close'], panel=0, color='b', secondary_y=True)

addition = [line2]

mystyle = mpf.make_mpf_style(base_mpf_style='yahoo')
mytitle = stockname1 + ' with ' + stockname2

mpf.plot(df1, type='line', style=mystyle, figscale=1.5, figratio=(24, 12), volume=False, title=mytitle, addplot=addition)

 

  • Most of the source code is quite similar to the first demo, except this time, we are adding a new function “addplot” on line 32 and 39. If user is not familiar with line 1-5, please visit last demo video.
  • Line 7-11, remember to change the file name and location for your historical stock data file. My file name starts with “HK”, then stock code, followed by “.csv”
  • To plot 2 different set of data on the same graph, it is very important that they must have the same length on x-axis (i.e. date). In this case, I limit the data to start with date 2010-01-01, up to all days.
  • Line 26, we check if length of days are matched. If not, there is a problem on data sets, and exit the program in the middle.
  • Line 32, we choose data set 2 closing price as a subplot. “panel=0” is to plot the data on the same panel. “color” can be adjusted as described in last article.
  • Line 34, put result “line2” into a python list.
  • Line 39, plot 2 sets of historical stock data into 1 chart.

 

HK0347 鞍鋼股份 is Angang Steel (steel maker), where HK0358 江西銅業 is Jiangxi Copper (copper producer). They are both related to raw material and the price is close to each other. User can also compare stock index with a stock, or compare oil price with oil related stock, or gold price with gold related stock. If 1 is leading to another, investor may predict the stock price of the follower.