Context: I'm using an API to retrieve stock data and I've created a function that loops through the elements of a list and retrieves the data for each stock in the tickerList.
Main goal: My main goal with this is so I can create individual variables for each ticker in the tickerList
. Would that be possible? For example, after passing the for loop, could I create variables like historyAAPL
, historyHOOD
, historyTSLA
... (i.e. for each element in the tickerList) and retrieve the data individually? I want to do this so that, in the future, I can send the data of each variable to a MySQL database (where each data from each stock is a table - historyAAPL would be it's own table, historyHOOD would be another table, etc). But first I would like to create the variables with the data (I've thought of using classes, but not sure if it would work for this)
Problem: I can't seem to figure out how to add the suffix on the variable history
so that each suffix equals the elements on the tickerList. It seems that executing the function moduleApi
will only retrieve the last element on the list (MSFT). I've also tried using locals()
, but with no success as well
Any help is welcome as I'm a beginner. Also, is it a good idea to save the data as data frame to then send to a database on MySQL? Or would you recommend other format? I've also thought of using dictionaries where each key is the stock name and the values are the open, close, high, low, date values, but I've read that this format isn't ideal if we then want to push the data onto a table in MySQL
Thank you
import pandas as pd
import numpy as np
import yfinance as yf
tickerList = ("AAPL", "HOOD", "TSLA", "GOOG", "MSFT")
history = ()
def moduleApi(setTicker, setPeriod, setInterval):
for setTicker in tickerList:
stock = yf.Ticker(setTicker)
history[setTicker] = pd.DataFrame(stock.history(
period=setPeriod,
interval=setInterval,
group_by='ticker',
proxy=None))
return history[setTicker]
moduleApi(tickerList, 'max', '1d')
historyAAPL #this should retrieve the data for the ticker AAPL