Objective is to acquire stock price data for each stock ticker, then assign a relevant variable its current price. ie. var 'sandp' links to ticker_symbol 'GSPC' which equals the stocks closing price. This bit works. However, I wish to return each variable value which I can then use within another function, but how do I access that variable and its value?
Here is my code:
def live_indices():
"""Acquire stock value from Yahoo Finance using stock ticker as key. Then assign the relevant variable to the respective value.
ie. variable 'sandp' equates to the value gathered from 'GSPC' stock ticker.
"""
import requests
import bs4
ticker_symbol_1 = ['GSPC', 'DJI', 'IXIC', 'FTSE', 'NSEI', 'FCHI', 'N225', 'GDAXI']
ticker_symbol_2 = ['IMOEX.ME', '000001.SS'] # Assigned to seperate list as url for webscraping is different
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36'}
all_indices_values = []
for i in range(len(ticker_symbol_1)):
url = 'https://uk.finance.yahoo.com/quote/%5E' + ticker_symbol_1[i] + '?p=%5E' + ticker_symbol_1[i]
tmp_res = requests.get(url, headers=headers)
tmp_res.raise_for_status()
soup = bs4.BeautifulSoup(tmp_res.text, 'html.parser')
indices_price_value = soup.select(
'#quote-header-info > div.My\(6px\).Pos\(r\).smartphone_Mt\(6px\).W\(100\%\) > div.D\(ib\).Va\(m\).Maw\('
'65\%\).Ov\(h\) > div > fin-streamer.Fw\(b\).Fz\(36px\).Mb\(-4px\).D\(ib\)')[
0].text
all_indices_values.append(indices_price_value)
for i in range(len(ticker_symbol_2)):
url = 'https://uk.finance.yahoo.com/quote/' + ticker_symbol_2[i] + '?p=' + ticker_symbol_2[i]
tmp_res = requests.get(url, headers=headers)
tmp_res.raise_for_status()
soup = bs4.BeautifulSoup(tmp_res.text, 'html.parser')
indices_price_value = soup.select(
'#quote-header-info > div.My\(6px\).Pos\(r\).smartphone_Mt\(6px\).W\(100\%\) > div.D\(ib\).Va\(m\).Maw\('
'65\%\).Ov\(h\) > div > fin-streamer.Fw\(b\).Fz\(36px\).Mb\(-4px\).D\(ib\)')[
0].text
all_indices_values.append(indices_price_value)
sandp, dow, nasdaq, ftse100, nifty50, cac40, nikkei, dax, moex, shanghai = [all_indices_values[i] for i in range(10)] # 10 stock tickers in total
return sandp, dow, nasdaq, ftse100, nifty50, cac40, nikkei, dax, moex, shanghai
I want the next function to simply be given the variable name returned from the first function to print out the stock value. I have tried the below to no avail-
def display_value(stock_name):
print(stock_name)
display_value(live_indices(sandp))
The obvious error here is that 'sandp' is not defined.
Additionally, the bs4 code runs fairly slowly, would it be best to use Threads() or is there another way to speed things up?