loopsmatplotlibcomputational-financemplfinance

How to assign multiple variables in a loop for graphs in Python 3


I am relatively new to coding and I have a few issues I don't quite understand how to solve, yet. I'm trying to build code that will make graphs that will produce from a ticker list, with the data downloading from yahoo finance. Taking out of account manually assigning stock1 (and so forth) a ticker for a moment...

I want to figure out how to loop the data going into running the graph, so TSLA and MSFT in my code. So far I have the code below, which I already changed dfs and stocks. I just don't understand how to make the loop. If anyone has some good resources for loops, as well, let me know.

Later, I would like to save the graphs as a png with file names corresponding to the stock being pulled from yahoo, so extra points if someone knows how to change this code (savefig = dict(fname="tsla.png", bbox_inches= "tight") which goes after style = 'default'. Thanks for the help!

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

#yahoo info
start = "2020-01-01"
end = dt.datetime.now()
stock1 = 'TSLA'
stock2 = 'MSFT'
df1 = yf.download(stock1, start, end)
df2 = yf.download(stock2, start, end)

stocks = [[stock1],[stock2]]
dfs = [[df1],[df2]]
changingvars = [[stocks],[dfs]]

#graph1
short_sma = 20
long_sma = 50
SMAs = [short_sma, long_sma]

for i in SMAs:
dfs["SMA_"+ str(i)] = dfs.iloc[:,4].rolling(window=i).mean() 

graph1 = mpf.plot(dfs, type = 'candlestick',figratio=(16,6), 
 mav=(short_sma,long_sma), 
 volume=True, title= str(stocks), 
 style='default')
plt.show()

Solution

  • Not sure why you are calculating your own SMA's, and grouping your stocks and dataframes, if your goal is only to create multiple plots (one for each stock). Also, if you are using mplfinance, then there is no need to import and/or use matplotlib.pyplot (nor to call plt.show(); mplfinance does that for you).

    That said, here is a suggestion for your code. I've added tickers for Apple and Alphabet (Google), just to demonstrate how this can be extended.

    stocklist = ['TSLA','MSFT','AAPL','GOOGL']
    start = "2020-01-01"
    end = dt.datetime.now()
    short_sma = 20
    long_sma = 50
    
    for stock in stocklist:
        df = yf.download(stock, start, end)
        filename = stock.lower() + '.png'
        mpf.plot(df,type='candlestick',figratio=(16,6), 
                 mav=(short_sma,long_sma), 
                 volume=True, title=stock,style='default',
                 savefig=dict(fname=filename,bbox_inches="tight")
                )
    

    The above code will not display the plots for each stock, but will save each one in its own .png file locally (where you run the script) for you to view afterwards.

    Note also that it does not save the actual data; only plots the data and then moves on to the next stock, reassigning the dataframe variable (which automatically deletes the previous stock's data). If you want to save the data for each stock in a separate csv file, that is easy to do as well with Pandas' .to_csv() method.

    Also, I am assuming you are calling yf.download() correctly. I am not familiar with that API so I just left that part of the code as you had it.

    HTH. Let me know. --Daniel