-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstock_data.py
More file actions
339 lines (296 loc) · 20.1 KB
/
Copy pathstock_data.py
File metadata and controls
339 lines (296 loc) · 20.1 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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
"""
stock_data.py — Stock data via Yahoo Finance (yfinance). No API key required.
Alpha Vantage retained only for symbol search fallback (optional).
"""
import os
import json
import time
import logging
from pathlib import Path
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass
import yfinance as yf
import requests
log = logging.getLogger(__name__)
CACHE_DIR = Path("cache")
CACHE_DIR.mkdir(exist_ok=True)
AV_KEY = os.environ.get("ALPHA_VANTAGE_KEY", "")
AV_BASE = "https://www.alphavantage.co/query"
# ---------------------------------------------------------------------------
# Stock universe — 67 tickers across 10+ sectors
# Architecture: add/remove entries here only. No other code changes needed.
# ---------------------------------------------------------------------------
STOCK_META = {
# ── Technology ───────────────────────────────────────────────────────
"AAPL": {"name": "Apple Inc.", "sector": "Technology", "desc": "Consumer electronics, software & services giant."},
"MSFT": {"name": "Microsoft Corporation", "sector": "Technology", "desc": "Software, cloud, and enterprise solutions."},
"GOOGL": {"name": "Alphabet Inc.", "sector": "Technology", "desc": "Search, advertising, and cloud services."},
"GOOG": {"name": "Alphabet Inc. (C)", "sector": "Technology", "desc": "Search, advertising, and cloud services."},
"META": {"name": "Meta Platforms, Inc.", "sector": "Technology", "desc": "Social media and virtual reality platforms."},
"NVDA": {"name": "NVIDIA Corporation", "sector": "Semiconductors", "desc": "GPU and AI chip manufacturer."},
"CRM": {"name": "Salesforce Inc.", "sector": "Technology", "desc": "Cloud-based CRM and enterprise software."},
"ORCL": {"name": "Oracle Corporation", "sector": "Technology", "desc": "Enterprise database and cloud infrastructure."},
"ADBE": {"name": "Adobe Inc.", "sector": "Technology", "desc": "Creative, marketing, and document software."},
"SAP": {"name": "SAP SE", "sector": "Technology", "desc": "Enterprise resource planning and business software."},
"PLTR": {"name": "Palantir Technologies", "sector": "Technology", "desc": "Big data analytics and AI platform."},
"SNOW": {"name": "Snowflake Inc.", "sector": "Technology", "desc": "Cloud data warehousing and analytics."},
"MSTR": {"name": "MicroStrategy Inc.", "sector": "Technology", "desc": "Business intelligence and Bitcoin holdings."},
"SMCI": {"name": "Super Micro Computer", "sector": "Technology", "desc": "Server and storage solutions manufacturer."},
# ── Semiconductors ───────────────────────────────────────────────────
"AMD": {"name": "Advanced Micro Devices", "sector": "Semiconductors", "desc": "CPU, GPU, and semi-custom chips."},
"INTC": {"name": "Intel Corporation", "sector": "Semiconductors", "desc": "Microprocessors, chips, and computing solutions."},
"QCOM": {"name": "QUALCOMM Inc.", "sector": "Semiconductors", "desc": "Mobile chipsets and wireless technology."},
"TSM": {"name": "Taiwan Semiconductor", "sector": "Semiconductors", "desc": "World's largest contract chipmaker."},
"ASML": {"name": "ASML Holding", "sector": "Semiconductors", "desc": "Semiconductor lithography equipment maker."},
"ARM": {"name": "Arm Holdings", "sector": "Semiconductors", "desc": "Chip architecture and IP licensing."},
# ── Finance ──────────────────────────────────────────────────────────
"JPM": {"name": "JPMorgan Chase", "sector": "Finance", "desc": "Largest U.S. bank by assets."},
"GS": {"name": "Goldman Sachs", "sector": "Finance", "desc": "Global investment banking and securities."},
"BAC": {"name": "Bank of America", "sector": "Finance", "desc": "Second-largest U.S. bank by assets."},
"V": {"name": "Visa Inc.", "sector": "Finance", "desc": "Global digital payments network."},
"MA": {"name": "Mastercard Inc.", "sector": "Finance", "desc": "Global payment processing network."},
"PYPL": {"name": "PayPal Holdings", "sector": "Fintech", "desc": "Digital payments and financial services."},
"BRK-B": {"name": "Berkshire Hathaway", "sector": "Finance", "desc": "Diversified holding company run by Warren Buffett."},
"BLK": {"name": "BlackRock Inc.", "sector": "Finance", "desc": "World's largest asset management firm."},
"SQ": {"name": "Block, Inc.", "sector": "Fintech", "desc": "Payment and financial services ecosystem."},
"HOOD": {"name": "Robinhood Markets", "sector": "Fintech", "desc": "Commission-free investing platform."},
"COIN": {"name": "Coinbase Global", "sector": "Finance/Crypto", "desc": "Cryptocurrency exchange platform."},
# ── Healthcare ───────────────────────────────────────────────────────
"JNJ": {"name": "Johnson & Johnson", "sector": "Healthcare", "desc": "Pharmaceuticals, medical devices, and consumer health."},
"PFE": {"name": "Pfizer Inc.", "sector": "Healthcare", "desc": "Global pharmaceutical and vaccine manufacturer."},
"UNH": {"name": "UnitedHealth Group", "sector": "Healthcare", "desc": "Largest U.S. health insurance conglomerate."},
# ── Consumer / Retail ────────────────────────────────────────────────
"AMZN": {"name": "Amazon.com, Inc.", "sector": "Consumer/Cloud", "desc": "E-commerce and cloud computing behemoth."},
"WMT": {"name": "Walmart Inc.", "sector": "Retail", "desc": "World's largest retailer by revenue."},
"TGT": {"name": "Target Corporation", "sector": "Retail", "desc": "U.S. discount retailer and big-box stores."},
"COST": {"name": "Costco Wholesale", "sector": "Retail", "desc": "Membership warehouse club and retailer."},
"HD": {"name": "Home Depot", "sector": "Retail", "desc": "Largest U.S. home improvement retailer."},
"LOW": {"name": "Lowe's Companies", "sector": "Retail", "desc": "Second-largest U.S. home improvement retailer."},
"SBUX": {"name": "Starbucks Corporation", "sector": "Consumer", "desc": "Global coffeehouse chain and coffee brand."},
"MCD": {"name": "McDonald's Corporation", "sector": "Consumer", "desc": "World's largest fast food restaurant chain."},
"KO": {"name": "Coca-Cola Company", "sector": "Consumer", "desc": "World's largest non-alcoholic beverage company."},
"PEP": {"name": "PepsiCo Inc.", "sector": "Consumer", "desc": "Beverages and snacks conglomerate."},
"NKE": {"name": "Nike Inc.", "sector": "Consumer", "desc": "World's largest athletic footwear and apparel maker."},
"BABA": {"name": "Alibaba Group", "sector": "E-Commerce", "desc": "China's largest e-commerce conglomerate."},
"SHOP": {"name": "Shopify Inc.", "sector": "E-Commerce", "desc": "E-commerce platform for businesses."},
"GME": {"name": "GameStop Corp.", "sector": "Retail", "desc": "Video game and consumer electronics retailer."},
# ── Energy ───────────────────────────────────────────────────────────
"XOM": {"name": "Exxon Mobil Corporation", "sector": "Energy", "desc": "Largest U.S. oil and gas company."},
"CVX": {"name": "Chevron Corporation", "sector": "Energy", "desc": "Integrated energy and chemicals company."},
# ── Automotive ───────────────────────────────────────────────────────
"TSLA": {"name": "Tesla, Inc.", "sector": "Automotive/Energy", "desc": "Electric vehicles and clean energy pioneer."},
"F": {"name": "Ford Motor Company", "sector": "Automotive", "desc": "American automaker — trucks, EVs, and ICE vehicles."},
"GM": {"name": "General Motors", "sector": "Automotive", "desc": "American automaker and EV transition leader."},
"RIVN": {"name": "Rivian Automotive", "sector": "Automotive", "desc": "Electric vehicle manufacturer."},
# ── Industrial ───────────────────────────────────────────────────────
"BA": {"name": "Boeing Company", "sector": "Aerospace", "desc": "Commercial jets, defense, and space systems."},
"CAT": {"name": "Caterpillar Inc.", "sector": "Industrial", "desc": "Heavy equipment, machinery, and diesel engines."},
"DE": {"name": "Deere & Company", "sector": "Industrial", "desc": "Agricultural and construction equipment maker."},
# ── Entertainment / Media ────────────────────────────────────────────
"NFLX": {"name": "Netflix, Inc.", "sector": "Entertainment", "desc": "Global streaming entertainment service."},
"DIS": {"name": "The Walt Disney Company", "sector": "Entertainment", "desc": "Media, parks, and streaming entertainment."},
"SPOT": {"name": "Spotify Technology", "sector": "Entertainment", "desc": "Audio streaming and podcast platform."},
"AMC": {"name": "AMC Entertainment", "sector": "Entertainment", "desc": "Movie theater chain operator."},
# ── Telecom ──────────────────────────────────────────────────────────
"T": {"name": "AT&T Inc.", "sector": "Telecom", "desc": "U.S. telecommunications and media conglomerate."},
"VZ": {"name": "Verizon Communications", "sector": "Telecom", "desc": "U.S. telecom giant — wireless and broadband."},
# ── ETFs ─────────────────────────────────────────────────────────────
"SPY": {"name": "SPDR S&P 500 ETF", "sector": "ETF", "desc": "Tracks the S&P 500 index."},
"QQQ": {"name": "Invesco QQQ ETF", "sector": "ETF", "desc": "Tracks the Nasdaq-100 index."},
# ── Other ────────────────────────────────────────────────────────────
"UBER": {"name": "Uber Technologies", "sector": "Transportation", "desc": "Ride-sharing and food delivery platform."},
"SNAP": {"name": "Snap Inc.", "sector": "Technology", "desc": "Camera and messaging app platform."},
}
LOGO_MAP = {
"AAPL": "https://logo.clearbit.com/apple.com",
"MSFT": "https://logo.clearbit.com/microsoft.com",
"GOOGL": "https://logo.clearbit.com/google.com",
"GOOG": "https://logo.clearbit.com/google.com",
"META": "https://logo.clearbit.com/meta.com",
"NVDA": "https://logo.clearbit.com/nvidia.com",
"CRM": "https://logo.clearbit.com/salesforce.com",
"ORCL": "https://logo.clearbit.com/oracle.com",
"ADBE": "https://logo.clearbit.com/adobe.com",
"SAP": "https://logo.clearbit.com/sap.com",
"PLTR": "https://logo.clearbit.com/palantir.com",
"SNOW": "https://logo.clearbit.com/snowflake.com",
"AMD": "https://logo.clearbit.com/amd.com",
"INTC": "https://logo.clearbit.com/intel.com",
"QCOM": "https://logo.clearbit.com/qualcomm.com",
"TSM": "https://logo.clearbit.com/tsmc.com",
"ASML": "https://logo.clearbit.com/asml.com",
"ARM": "https://logo.clearbit.com/arm.com",
"JPM": "https://logo.clearbit.com/jpmorganchase.com",
"GS": "https://logo.clearbit.com/goldmansachs.com",
"BAC": "https://logo.clearbit.com/bankofamerica.com",
"V": "https://logo.clearbit.com/visa.com",
"MA": "https://logo.clearbit.com/mastercard.com",
"PYPL": "https://logo.clearbit.com/paypal.com",
"BRK-B": "https://logo.clearbit.com/berkshirehathaway.com",
"BLK": "https://logo.clearbit.com/blackrock.com",
"SQ": "https://logo.clearbit.com/block.xyz",
"HOOD": "https://logo.clearbit.com/robinhood.com",
"COIN": "https://logo.clearbit.com/coinbase.com",
"JNJ": "https://logo.clearbit.com/jnj.com",
"PFE": "https://logo.clearbit.com/pfizer.com",
"UNH": "https://logo.clearbit.com/unitedhealthgroup.com",
"AMZN": "https://logo.clearbit.com/amazon.com",
"WMT": "https://logo.clearbit.com/walmart.com",
"TGT": "https://logo.clearbit.com/target.com",
"COST": "https://logo.clearbit.com/costco.com",
"HD": "https://logo.clearbit.com/homedepot.com",
"LOW": "https://logo.clearbit.com/lowes.com",
"SBUX": "https://logo.clearbit.com/starbucks.com",
"MCD": "https://logo.clearbit.com/mcdonalds.com",
"KO": "https://logo.clearbit.com/coca-cola.com",
"PEP": "https://logo.clearbit.com/pepsico.com",
"NKE": "https://logo.clearbit.com/nike.com",
"BABA": "https://logo.clearbit.com/alibaba.com",
"SHOP": "https://logo.clearbit.com/shopify.com",
"GME": "https://logo.clearbit.com/gamestop.com",
"XOM": "https://logo.clearbit.com/exxonmobil.com",
"CVX": "https://logo.clearbit.com/chevron.com",
"TSLA": "https://logo.clearbit.com/tesla.com",
"F": "https://logo.clearbit.com/ford.com",
"GM": "https://logo.clearbit.com/gm.com",
"RIVN": "https://logo.clearbit.com/rivian.com",
"BA": "https://logo.clearbit.com/boeing.com",
"CAT": "https://logo.clearbit.com/caterpillar.com",
"DE": "https://logo.clearbit.com/deere.com",
"NFLX": "https://logo.clearbit.com/netflix.com",
"DIS": "https://logo.clearbit.com/disney.com",
"SPOT": "https://logo.clearbit.com/spotify.com",
"AMC": "https://logo.clearbit.com/amctheatres.com",
"T": "https://logo.clearbit.com/att.com",
"VZ": "https://logo.clearbit.com/verizon.com",
"UBER": "https://logo.clearbit.com/uber.com",
"SNAP": "https://logo.clearbit.com/snap.com",
}
# Issue #8 — pre-built search index at module load (O(1) lookup instead of O(n) scan)
_SEARCH_INDEX: dict[str, list[str]] = {}
def _build_index():
for ticker, meta in STOCK_META.items():
tl = ticker.lower()
words = [tl] + meta["name"].lower().replace(",", "").replace(".", "").replace("-", " ").split()
for word in set(words):
for length in range(1, len(word) + 1):
prefix = word[:length]
bucket = _SEARCH_INDEX.setdefault(prefix, [])
if ticker not in bucket:
bucket.append(ticker)
_build_index()
# ---------------------------------------------------------------------------
# Data fetching
# ---------------------------------------------------------------------------
def _cache_path(ticker: str) -> Path:
# Sanitize ticker for filename (BRK-B → BRK-B_yf.json, safe on all OS)
safe = ticker.upper().replace("/", "_")
return CACHE_DIR / f"{safe}_yf.json"
def _is_fresh(path: Path, hours: int = 12) -> bool:
return path.exists() and (time.time() - path.stat().st_mtime) < hours * 3600
def fetch_daily_ohlcv(ticker: str):
"""
Fetch full daily OHLCV via yfinance. Results cached to disk.
Cache is always preferred if it exists — historical data doesn't change.
yfinance is only called when no cache file is present.
Returns dict keyed by 'YYYY-MM-DD', or None on failure.
"""
ticker = ticker.upper()
cache_file = _cache_path(ticker)
# Always use cache if it exists and has valid data — no freshness check.
# Historical OHLCV never changes; this also makes Railway deployments work
# without hitting Yahoo Finance (which blocks datacenter IPs).
if cache_file.exists():
try:
with open(cache_file, encoding="utf-8") as f:
data = json.load(f)
if data and len(data) >= 30:
return data
except (json.JSONDecodeError, IOError):
pass
try:
t = yf.Ticker(ticker)
hist = t.history(period="max")
if hist is None or hist.empty:
hist = t.history(period="5y")
if hist is None or hist.empty:
return None
result = {}
for ts, row in hist.iterrows():
result[str(ts.date())] = {
"open": round(float(row["Open"]), 4),
"high": round(float(row["High"]), 4),
"low": round(float(row["Low"]), 4),
"close": round(float(row["Close"]), 4),
"volume": int(row["Volume"]),
}
if not result:
return None
with open(cache_file, "w", encoding="utf-8") as f:
json.dump(result, f)
return result
except Exception as e:
log.error("yfinance fetch failed for %s: %s", ticker, e)
# Last-resort: return stale cache rather than failing entirely
if cache_file.exists():
try:
with open(cache_file, encoding="utf-8") as f:
return json.load(f)
except Exception:
pass
return None
def get_current_price(ticker: str):
"""
Issue #4 — use yfinance fast_info for a lightweight price lookup.
Falls back to cached OHLCV data if fast_info fails.
"""
ticker = ticker.upper()
try:
fi = yf.Ticker(ticker).fast_info
price = getattr(fi, "last_price", None)
if price and float(price) > 0:
return round(float(price), 2)
except Exception:
pass
# Fallback: use last close from cached data (no new network call)
cache_file = _cache_path(ticker)
if cache_file.exists():
try:
with open(cache_file, encoding="utf-8") as f:
data = json.load(f)
if data:
return data[sorted(data.keys())[-1]]["close"]
except Exception:
pass
return None
def search_ticker(query: str):
"""O(1) prefix lookup via pre-built index. Only returns curated STOCK_META tickers."""
key = query.lower().strip()
results = []
seen = set()
for ticker in _SEARCH_INDEX.get(key, []):
if ticker not in seen:
seen.add(ticker)
meta = STOCK_META[ticker]
results.append({
"ticker": ticker,
"name": meta["name"],
"sector": meta["sector"],
"desc": meta["desc"],
"logo": LOGO_MAP.get(ticker, ""),
})
return results[:8]
def get_stock_info(ticker: str) -> dict:
ticker = ticker.upper()
meta = STOCK_META.get(ticker, {"name": ticker, "sector": "Unknown", "desc": ""})
return {
"ticker": ticker,
"name": meta["name"],
"sector": meta["sector"],
"desc": meta["desc"],
"logo": LOGO_MAP.get(ticker, ""),
"current_price": get_current_price(ticker),
}