mdkb
mdkb

Reputation: 402

Plot multiple charts from a number of yFinance tickers

The below code works to create one chart from "stock1" taken from Yfinance. I am now trying to plot multiple charts using "myTickers" to collect a set of tickers from YFinance. I can get the data, but I can't get it to plot that data to multiple charts.

I want them to share the x-axis and be aligned vertically (the window can scroll if they do not fit on screen). So far any attempts have resulted in empty charts or dataframe errors that I can't solve.

I tried to adapt it to the suggestion from Daniel Goldfarb in this link Plot multiple mplfinance plots sharing x axis but so far failed to have any success. The github info for matplotlib has also not given me enough info to get past the dataframe errors.

import pandas as pd 
import numpy as np 
import yfinance as yf 
import datetime as dt 
import mplfinance as mpf
import matplotlib.pyplot as plt
from pandas_datareader import data as pdr 

yf.pdr_override() # Activate Yahoo Finance Workaround

stock1 = 'M6A=F' # Gets individual ticker
# collect many tickers instead of one
myTickers = ['M6A=F','M6B=F','M6C=F','M6E=F','MBT=F','MGC=F','SIL=F','MCL=F','MES=F','MNQ=F','MYM=F','M2K=F']

startDay = 1 # Day to start gathering data
startMonth = 1 # Month to start gathering data
startYear = 2022 # Year to start gathering data
startDate = dt.datetime(startYear, startMonth, startDay) # Date to start gathering data
endDate = dt.datetime.now() # Today's date

df = pdr.get_data_yahoo(stock1, startDate, endDate) # Get data for selected stock1, from start date until today
print(df.tail())

# get data for all myTickers
#myData = pdr.get_data_yahoo(myTickers, startDate, endDate)
#print(myData.tail())

# Create custom chart style, based on Yahoo style, with black outline
chartColors = mpf.make_marketcolors(base_mpf_style="yahoo", edge="#505050", wick="#505050")
chartStyle = mpf.make_mpf_style(base_mpf_style="yahoo", marketcolors=chartColors)

# Plot custom candlestick chart for chosen stock
mpf.plot(df, type="candle", volume=True, show_nontrading=True, style=chartStyle, title="{} Daily Chart".format(stock1)) # original single chart code method
#

Upvotes: 0

Views: 2288

Answers (1)

r-beginners
r-beginners

Reputation: 35155

There are a few points to be realized using the technique in the answer to the link in the question: from the structure of mplfinance, to add graphs of other tickers to the base graph, the first ticker must be the graph to the base, and the stocks to be added must be given panel numbers. Simply put, the first floor is the first graph, and then the graph continues up to the 11th floor. You can understand this if you think of the panel number as a floor. Later, it makes no sense to display volume only on the base graph, so I have disabled it. The title position is not appropriate, so I have corrected it using the method described in this response. Check here for details on additional graphs.

import pandas as pd 
import numpy as np 
import yfinance as yf 
import datetime as dt 
import mplfinance as mpf
import matplotlib.pyplot as plt
from pandas_datareader import data as pdr 

yf.pdr_override() # Activate Yahoo Finance Workaround

stock1 = 'M6A=F' # Gets individual ticker
# collect many tickers instead of one
myTickers = ['M6A=F','M6B=F','M6C=F','M6E=F','MBT=F','MGC=F','SIL=F','MCL=F','MES=F','MNQ=F','MYM=F','M2K=F']

startDay = 1 # Day to start gathering data
startMonth = 1 # Month to start gathering data
startYear = 2022 # Year to start gathering data
startDate = dt.datetime(startYear, startMonth, startDay) # Date to start gathering data
endDate = dt.datetime.now() # Today's date

df = pdr.get_data_yahoo(stock1, startDate, endDate)
# Get data for selected stock1, from start date until today
df1 = pdr.get_data_yahoo(myTickers[1:], startDate, endDate, group_by='ticker')

# get data for all myTickers
aps = []
for i,t in enumerate(myTickers[1:]):
    aps.append(mpf.make_addplot(df1.loc[:,t], panel=i+1, ylabel=t, type='candle'))

# Create custom chart style, based on Yahoo style, with black outline
chartColors = mpf.make_marketcolors(base_mpf_style="yahoo", edge="#505050", wick="#505050")
chartStyle = mpf.make_mpf_style(base_mpf_style="yahoo", marketcolors=chartColors)

# Plot custom candlestick chart for chosen stock
fig,axlist = mpf.plot(df, type="candle", volume=False,
               show_nontrading=True, style=chartStyle,
               panel_ratios=(1,1),
               figratio=(1,1),
               figscale=3.0,
               addplot=aps,
               returnfig=True)

fig.suptitle("12 Ticker Daily Chart", y=0.90, x=0.59, fontsize=18)

enter image description here

Upvotes: 1

Related Questions