File size: 9,860 Bytes
78e48a1 |
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 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 |
# ==============================
# Imports
# ==============================
import yfinance as yf
import pandas as pd
import traceback
# ==============================
# Yahoo Finance info fetch
# ==============================
def yfinfo(symbol):
try:
t = yf.Ticker(symbol)
info = t.info
if not info or not isinstance(info, dict):
return {}
return info
except Exception as e:
return {"__error__": str(e)}
# ==============================
# HTML card renderer
# ==============================
def html_card(title, body, mini=False):
font = "12px" if mini else "14px"
pad = "6px" if mini else "10px"
return f"""
<div style="
background:#111;
border:1px solid #333;
border-radius:6px;
padding:{pad};
margin:6px 0;
color:#eee;
font-size:{font};
">
<div style="
font-weight:600;
color:#6cf;
margin-bottom:4px;
">
{title}
</div>
<div>{body}</div>
</div>
"""
# ==============================
# DataFrame β HTML table
# ==============================
def make_table(df, compact=False):
if df is None or df.empty:
return "<i>No data</i>"
font = "11px" if compact else "13px"
pad = "2px 6px" if compact else "4px 8px"
th = "".join(
f"<th style='padding:{pad};border-bottom:1px solid #444'>{c}</th>"
for c in df.columns
)
rows = ""
for _, r in df.iterrows():
tds = "".join(
f"<td style='padding:{pad};border-bottom:1px solid #222'>{v}</td>"
for v in r
)
rows += f"<tr>{tds}</tr>"
return f"""
<table style="
width:100%;
border-collapse:collapse;
font-size:{font};
color:#eee;
">
<thead><tr>{th}</tr></thead>
<tbody>{rows}</tbody>
</table>
"""
# ==============================
# Number formatting
# ==============================
def format_number(x):
try:
if x is None:
return "-"
x = float(x)
if abs(x) >= 100:
return f"{x:,.0f}"
if abs(x) >= 1:
return f"{x:,.2f}"
return f"{x:.4f}"
except Exception:
return str(x)
def format_large_number(x):
try:
x = float(x)
for u in ["", "K", "M", "B", "T"]:
if abs(x) < 1000:
return f"{x:.2f}{u}"
x /= 1000
return f"{x:.2f}P"
except Exception:
return str(x)
# ==============================
# HTML error block
# ==============================
def html_error(msg):
return f"""
<div style="
background:#300;
color:#f88;
border:1px solid #800;
border-radius:6px;
padding:10px;
font-weight:600;
">
β {msg}
</div>
"""
# ------------------------------------------------------------
# 1. Noise keys (internal Yahoo junk)
# ------------------------------------------------------------
NOISE_KEYS = {
"maxAge", "priceHint", "triggerable",
"customPriceAlertConfidence",
"sourceInterval", "exchangeDataDelayedBy",
"esgPopulated"
}
def is_noise(k):
return k in NOISE_KEYS
# ------------------------------------------------------------
# 2. Duplicate resolution priority
# ------------------------------------------------------------
DUPLICATE_PRIORITY = {
"price": ["regularMarketPrice", "currentPrice"],
"prev": ["regularMarketPreviousClose", "previousClose"],
"open": ["regularMarketOpen", "open"],
"high": ["regularMarketDayHigh", "dayHigh"],
"low": ["regularMarketDayLow", "dayLow"],
"volume": ["regularMarketVolume", "volume"],
}
def resolve_duplicates(data):
resolved = {}
used = set()
for _, keys in DUPLICATE_PRIORITY.items():
for k in keys:
if k in data:
resolved[k] = data[k]
used.update(keys)
break
for k, v in data.items():
if k not in used:
resolved[k] = v
return resolved
# ------------------------------------------------------------
# 3. Short display names (<=12 chars)
# ------------------------------------------------------------
SHORT_NAMES = {
"regularMarketPrice": "Price",
"regularMarketChange": "Chg",
"regularMarketChangePercent": "Chg%",
"regularMarketPreviousClose": "Prev",
"regularMarketOpen": "Open",
"regularMarketDayHigh": "High",
"regularMarketDayLow": "Low",
"regularMarketVolume": "Vol",
"averageDailyVolume10Day": "AvgV10",
"averageDailyVolume3Month": "AvgV3M",
"fiftyDayAverage": "50DMA",
"fiftyDayAverageChangePercent": "50DMA%",
"twoHundredDayAverage": "200DMA",
"twoHundredDayAverageChangePercent": "200DMA%",
"fiftyTwoWeekLow": "52WL",
"fiftyTwoWeekHigh": "52WH",
"fiftyTwoWeekRange": "52WR",
"beta": "Beta",
"targetHighPrice": "TgtH",
"targetLowPrice": "TgtL",
"targetMeanPrice": "Tgt",
"recommendationMean": "Reco",
}
def pretty_key(k):
return SHORT_NAMES.get(k, k[:12])
# ------------------------------------------------------------
# 4. Price / Volume sub-group classifier
# ------------------------------------------------------------
def classify_price_volume_subgroup(key):
k = key.lower()
if any(x in k for x in [
"price", "open", "close", "change", "day"
]):
return "Live Price"
if "volume" in k:
return "Volume"
if "average" in k or "fiftyday" in k or "twohundredday" in k:
return "Moving Avg"
if any(x in k for x in ["week", "range", "high", "low", "alltime", "beta"]):
return "Range / Vol"
if any(x in k for x in ["bid", "ask", "target", "recommendation", "analyst"]):
return "Bid / Analyst"
return "Other"
def build_price_volume_subgroups(data):
sub = {}
for k, v in data.items():
sg = classify_price_volume_subgroup(k)
sub.setdefault(sg, {})[k] = v
return sub
# ------------------------------------------------------------
# 5. Main key classifier
# ------------------------------------------------------------
def classify_key(key, value):
k = key.lower()
if isinstance(value, str) and len(value) > 80:
return "long_text"
if isinstance(value, (int, float)) and any(x in k for x in [
"price", "volume", "avg", "average", "change",
"percent", "market", "day", "week", "bid",
"ask", "beta", "target", "recommendation"
]):
return "price_volume"
if any(x in k for x in [
"revenue", "income", "earnings", "profit",
"margin", "pe", "pb", "roe", "roa",
"cash", "debt", "equity", "dividend",
"ebitda", "growth", "ratio", "shares"
]):
return "fundamental"
return "profile"
# ------------------------------------------------------------
# 6. Group builder
# ------------------------------------------------------------
def build_grouped_info(info):
groups = {
"price_volume": {},
"fundamental": {},
"profile": {},
"long_text": {}
}
for k, v in info.items():
if v in [None, "", [], {}]:
continue
grp = classify_key(k, v)
groups[grp][k] = v
return groups
# ------------------------------------------------------------
# 7. Final DataFrame builder
# ------------------------------------------------------------
def build_df_from_dict(data):
rows = []
for k, v in data.items():
if is_noise(k):
continue
if isinstance(v, (int, float)):
v = format_number(v)
elif isinstance(v, list):
v = ", ".join(map(str, v[:5]))
rows.append([pretty_key(k), v])
return pd.DataFrame(rows, columns=["Field", "Value"])
# ------------------------------------------------------------
# 8. MAIN FUNCTION (NAME UNCHANGED)
# ------------------------------------------------------------
def fetch_info(symbol):
try:
info = yfinfo(symbol)
if not info:
return html_error(f"No information found for {symbol}")
groups = build_grouped_info(info)
final_html = ""
# ---------------- PRICE / VOLUME ----------------
price_data = groups["price_volume"]
price_data = resolve_duplicates(price_data)
price_subgroups = build_price_volume_subgroups(price_data)
price_html = ""
for title, data in price_subgroups.items():
df = build_df_from_dict(data)
if not df.empty:
price_html += html_card(
title,
make_table(df, compact=True),
mini=True
)
if price_html:
final_html += html_card("π Price / Volume", price_html)
# ---------------- FUNDAMENTALS ----------------
if groups["fundamental"]:
df = build_df_from_dict(groups["fundamental"])
final_html += html_card(
"π Fundamentals",
make_table(df, compact=True)
)
# ---------------- PROFILE ----------------
if groups["profile"]:
df = build_df_from_dict(groups["profile"])
final_html += html_card(
"π’ Company Profile",
make_table(df, compact=True)
)
# ---------------- LONG TEXT ----------------
for k, v in groups["long_text"].items():
final_html += html_card(
pretty_key(k),
f"<div class='long-text'>{v}</div>"
)
return final_html
except Exception as e:
return html_error(
f"INFO ERROR: {e}<br><pre>{traceback.format_exc()}</pre>"
) |