- Notifications
You must be signed in to change notification settings - Fork 46.7k
/
Copy pathcurrent_stock_price.py
40 lines (32 loc) · 1.21 KB
/
current_stock_price.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
importrequests
frombs4importBeautifulSoup
"""
Get the HTML code of finance yahoo and select the current qsp-price
Current AAPL stock price is 228.43
Current AMZN stock price is 201.85
Current IBM stock price is 210.30
Current GOOG stock price is 177.86
Current MSFT stock price is 414.82
Current ORCL stock price is 188.87
"""
defstock_price(symbol: str="AAPL") ->str:
"""
>>> stock_price("EEEE")
'- '
>>> isinstance(float(stock_price("GOOG")),float)
True
"""
url=f"https://finance.yahoo.com/quote/{symbol}?p={symbol}"
yahoo_finance_source=requests.get(
url, headers={"USER-AGENT": "Mozilla/5.0"}, timeout=10
).text
soup=BeautifulSoup(yahoo_finance_source, "html.parser")
ifspecific_fin_streamer_tag:=soup.find("span", {"data-testid": "qsp-price"}):
returnspecific_fin_streamer_tag.get_text()
return"No <fin-streamer> tag with the specified data-testid attribute found."
# Search for the symbol at https://finance.yahoo.com/lookup
if__name__=="__main__":
fromdoctestimporttestmod
testmod()
forsymbolin"AAPL AMZN IBM GOOG MSFT ORCL".split():
print(f"Current {symbol:<4} stock price is {stock_price(symbol):>8}")