-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStock_Update.py
More file actions
110 lines (83 loc) · 3.84 KB
/
Copy pathStock_Update.py
File metadata and controls
110 lines (83 loc) · 3.84 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import yfinance as yf
Stock_Symbol = ""
while Stock_Symbol != "R":
def is_valid_ticker(symbol: str) -> bool:
"""
Checks if a ticker symbol is valid by trying to fetch recent price history.
Returns True if data exists, False otherwise.
"""
try:
ticker = yf.Ticker(symbol)
# Try to get the last 5 trading days of data
hist = ticker.history(period="5d")
# If DataFrame is empty or has no rows → likely invalid
if hist.empty:
return False
# Optional: extra strict check — ensure we have at least one valid close price
if hist['Close'].dropna().empty:
return False
return True
except Exception as e:
# Catches JSON decode errors, connection issues, invalid symbols, etc.
# print(f"Validation error for {symbol}: {e}") # optional for debugging
return False
while not Stock_Symbol:
print("Welcome to Stock Update Tool. (To exit, enter 'R')")
Stock_Symbol = input("Enter Stock Symbol: ").strip().upper()
if not Stock_Symbol:
print("Stock Symbol cannot be empty. Please try again.")
elif not Stock_Symbol.isalnum():
print("Stock Symbol must be alphanumeric. Please try again.")
Stock_Symbol = ""
elif len(Stock_Symbol) > 5:
print("Stock Symbol must be 5 characters or fewer. Please try again.")
Stock_Symbol = ""
elif not is_valid_ticker(Stock_Symbol):
print(f"'{Stock_Symbol}' is not a valid stock ticker. Please try again.")
Stock_Symbol = ""
def get_stock_percent_change(symbol: str) -> float:
"""
Fetches the stock data and calculates the percentage change from open to close.
Returns the percentage change as a float.
"""
ticker = yf.Ticker(symbol)
hist = ticker.history(period="1d")
if hist.empty:
raise ValueError(f"No data found for ticker '{symbol}'")
open_price = hist['Open'].iat[0]
close_price = hist['Close'].iat[0]
percent_change = ((close_price - open_price) / open_price) * 100
return percent_change
def news_fetcher(symbol: str, debug: bool = False):
news = yf.Ticker(symbol).news
if not news:
print("No news items found.")
return news
from datetime import datetime
for item in news:
# Handle both old & new yfinance formats
content = item.get("content") if isinstance(item.get("content"), dict) else item
title = content.get("title")
link = content.get("canonicalUrl", {}).get("url") or content.get("link")
publisher = content.get("provider", {}).get("displayName") or content.get("publisher")
published = content.get("pubDate")
# 🔥 Skip non-articles
if not title or not link:
continue
print(f"- {title}")
print(f" Source: {publisher or 'Unknown'}")
if published:
print(f" Published: {published}")
print(f" Link: {link}")
print("-" * 40)
return news
if Stock_Symbol == "R":
print("Exiting the Stock Update Tool. Goodbye!")
break
else:
Percentage_Change = get_stock_percent_change(Stock_Symbol)
print(f"'{Stock_Symbol}' is a valid stock ticker.")
print(f"Percentage Change from Open to Close: {Percentage_Change:.2f}%")
print("Latest News:")
news = news_fetcher(Stock_Symbol)
Stock_Symbol = "" # Reset for next iteration