Issue
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?
Solution
This looks a bit complicated in my opinion, anyway focus on your question. So you are not returning a variable, you are returning a tuple
of values.
def live_indices():
all_indices_values = [1,2,3,4,5,6,7,8,9,10,11,12,13]
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
live_indices() #-> (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
What you want to make more likely to have is this assignment and it do not need the list comprehension
nor the range()
simply slice your list:
def live_indices():
all_indices_values = [1,2,3,4,5,6,7,8,9,10,11,12,13]
return all_indices_values
def display_value(x):
print(x)
sandp, dow, nasdaq, ftse100, nifty50, cac40, nikkei, dax, moex, shanghai = live_indices()[:10]
display_value(sandp)#-> 1
You may wanna work with more structured data, so return a dict
:
Example
import requests
from bs4 import BeautifulSoup
def live_indices():
all_indices_values = {}
symbols = ['GSPC', 'DJI', 'IXIC', 'FTSE', 'NSEI', 'FCHI', 'N225', 'GDAXI', 'IMOEX.ME', '000001.SS']
for ticker in symbols:
url = f'https://uk.finance.yahoo.com/lookup/all?s={ticker}'
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('#Main tbody>tr td')[2].text
all_indices_values[ticker] = indices_price_value
return all_indices_values
def display_value(live_indices):
for ticker in live_indices.items():
print(ticker)
display_value(live_indices())
Output
('GSPC', '3,873.33')
('DJI', '30,822.42')
('IXIC', '11,448.40')
('FTSE', '7,236.68')
('NSEI', '17,530.85')
('FCHI', '6,077.30')
('N225', '27,567.65')
('GDAXI', '12,741.26')
('IMOEX.ME', '2,222.51')
('000001.SS', '3,126.40')
Answered By - HedgeHog
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.