Spaces:
Sleeping
Sleeping
File size: 12,547 Bytes
2cf0213 2fc92c5 5d05f18 fde7ebe 2fc92c5 2cf0213 23f2565 2cf0213 23f2565 2cf0213 9f80da5 2cf0213 9f80da5 2cf0213 17164cf 2cf0213 23f2565 2cf0213 36afc06 2cf0213 23f2565 2cf0213 17164cf 9f80da5 2cf0213 17164cf 2cf0213 9f80da5 2cf0213 9f80da5 2cf0213 9f80da5 2cf0213 9f80da5 2cf0213 9f80da5 2cf0213 9f80da5 2cf0213 9f80da5 2cf0213 9f80da5 2cf0213 9f80da5 2cf0213 9f80da5 2cf0213 9f80da5 2cf0213 9f80da5 2cf0213 9f80da5 2cf0213 9f80da5 2cf0213 |
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 377 378 379 380 381 382 383 384 385 |
# stock.py — compact, merged, single-file (collision-safe)
import traceback
import pandas as pd
import yfinance as yf
from datetime import datetime as dt
# persist helpers
from . import persist
from .common import *
from . import backblaze as b2
from . import ta_indi_pat
# ================================================================
# BASIC YFINANCE FETCHERS
# ================================================================
def yfinfo(symbol):
return yf.Ticker(symbol + ".NS").info
def qresult(symbol):
return yf.Ticker(symbol + ".NS").quarterly_financials
def result(symbol):
return yf.Ticker(symbol + ".NS").financials
def balance(symbol):
return yf.Ticker(symbol + ".NS").balance_sheet
def cashflow(symbol):
return yf.Ticker(symbol + ".NS").cashflow
def dividend(symbol):
return yf.Ticker(symbol + ".NS").dividends.to_frame("Dividend")
def split(symbol):
return yf.Ticker(symbol + ".NS").splits.to_frame("Split")
def intraday(symbol):
print(f"[{dt.now().strftime('%Y-%m-%d %H:%M:%S')}] yf called for {symbol}")
return yf.download(symbol + ".NS", period="1d", interval="5m").round(2)
def daily(symbol,date_end,date_start):
print(f"[{dt.now().strftime('%Y-%m-%d %H:%M:%S')}] yf called for {symbol}")
start = dt.strptime(date_start, "%d-%m-%Y").strftime("%Y-%m-%d")
end = dt.strptime(date_end, "%d-%m-%Y").strftime("%Y-%m-%d")
return yf.download(symbol + ".NS", start=start,end=end).round(2)
# ================================================================
# INTRADAY
# ================================================================
def fetch_intraday(symbol, indicators=None,b2_save=False):
key = f"intraday_{symbol}"
if persist.exists(key, "html"):
cached = persist.load(key, "html")
if cached is not False:
print(f"[{dt.now().strftime('%Y-%m-%d %H:%M:%S')}] Using cached intraday for {symbol}")
return cached
try:
df = intraday(symbol)
if df is None or df is False or df.empty:
return wrap_html(f"<h1>No intraday data for {symbol}</h1>")
if isinstance(df.columns, pd.MultiIndex):
df.columns = df.columns.get_level_values(0)
if b2_save:
b2.upload_file("eshanhf", f"intraday/{symbol}.csv", df)
df_display = df.copy()
df_display.reset_index(inplace=True)
html = wrap_html(
f"<h2>Last 50 Rows</h2>{make_table(df_display)}",
title=f"{symbol} Intraday"
)
persist.save(key, html, "html")
return html
except Exception as e:
print(f"[{dt.now().strftime('%Y-%m-%d %H:%M:%S')}] Error fetch_intraday: {e}")
return wrap_html(f"<h1>Error: {e}</h1>")
# ================================================================
# DAILY
# ================================================================
def fetch_daily(symbol,date_end,date_start,b2_save=False):
key = f"daily_{symbol}"
if persist.exists(key, "html"):
cached = persist.load(key, "html")
if cached is not False:
print(f"[{date_end}] Using cached daily for {symbol}")
return cached
try:
df = daily(symbol,date_end,date_start)
if df is None or df is False or df.empty:
return wrap_html(f"<h1>No daily data for {symbol}</h1>")
if isinstance(df.columns, pd.MultiIndex):
df.columns = df.columns.get_level_values(0)
if b2_save:
b2.upload_file("eshanhf", f"intraday/{symbol}.csv", df)
df_display = df.copy()
df_display.reset_index(inplace=True)
html = wrap_html(
f"<h2>Last 50 Rows</h2>{make_table(df_display)}",
title=f"{symbol} Daily"
)
persist.save(key, html, "html")
return html
except Exception as e:
print(f"[{dt.now().strftime('%Y-%m-%d %H:%M:%S')}] Error fetch_daily: {e}")
return wrap_html(f"<h1>Error: {e}</h1>")
# ================================================================
# QUARTERLY
# ================================================================
def fetch_qresult(symbol,b2_save=False):
key = f"qresult_{symbol}"
if persist.exists(key, "html"):
cached = persist.load(key, "html")
if cached is not False:
print(f"[{dt.now().strftime('%Y-%m-%d %H:%M:%S')}] Using cached quarterly for {symbol}")
return cached
try:
df = qresult(symbol)
if df.empty:
return wrap_html(f"<h1>No quarterly results for {symbol}</h1>")
if b2_save:
b2.upload_file("eshanhf", f"intraday/{symbol}.csv", df)
df_display = df.copy()
for col in df_display.columns:
df_display[col] = df_display[col].apply(
lambda x: format_large_number(x) if isinstance(x, (int, float)) else x
)
df_display.reset_index(inplace=True)
html = wrap_html(make_table(df_display), title=f"{symbol} Quarterly Results")
persist.save(key, html, "html")
return html
except Exception as e:
print(f"[{dt.now().strftime('%Y-%m-%d %H:%M:%S')}] Error fetch_qresult: {e}")
return wrap_html(html_error(f"Quarterly Error: {e}"))
# ================================================================
# ANNUAL
# ================================================================
def fetch_result(symbol,b2_save=False):
key = f"result_{symbol}"
if persist.exists(key, "html"):
cached = persist.load(key, "html")
if cached is not False:
print(f"[{dt.now().strftime('%Y-%m-%d %H:%M:%S')}] Using cached annual for {symbol}")
return cached
try:
df = result(symbol)
if df.empty:
return wrap_html(f"<h1>No annual results for {symbol}</h1>")
if b2_save:
b2.upload_file("eshanhf", f"intraday/{symbol}.csv", df)
df_display = df.copy()
for col in df_display.columns:
df_display[col] = df_display[col].apply(
lambda x: format_large_number(x) if isinstance(x, (int, float)) else x
)
df_display.reset_index(inplace=True)
html = wrap_html(make_table(df_display), title=f"{symbol} Annual Results")
persist.save(key, html, "html")
return html
except Exception as e:
print(f"[{dt.now().strftime('%Y-%m-%d %H:%M:%S')}] Error fetch_result: {e}")
return wrap_html(html_error(f"Annual Error: {e}"))
# ================================================================
# BALANCE SHEET
# ================================================================
def fetch_balance(symbol,b2_save=False):
key = f"balance_{symbol}"
if persist.exists(key, "html"):
cached = persist.load(key, "html")
if cached is not False:
print(f"[{dt.now().strftime('%Y-%m-%d %H:%M:%S')}] Using cached balance for {symbol}")
return cached
try:
df = balance(symbol)
if df.empty:
return wrap_html(f"<h1>No balance sheet for {symbol}</h1>")
if b2_save:
b2.upload_file("eshanhf", f"intraday/{symbol}.csv", df)
df_display = df.copy()
for col in df_display.columns:
df_display[col] = df_display[col].apply(
lambda x: format_large_number(x) if isinstance(x, (int, float)) else x
)
df_display.reset_index(inplace=True)
html = wrap_html(make_table(df_display), title=f"{symbol} Balance Sheet")
persist.save(key, html, "html")
return html
except Exception as e:
print(f"[{dt.now().strftime('%Y-%m-%d %H:%M:%S')}] Error fetch_balance: {e}")
return wrap_html(html_error(f"Balance Error: {e}"))
# ================================================================
# CASHFLOW
# ================================================================
def fetch_cashflow(symbol,b2_save=False):
key = f"cashflow_{symbol}"
if persist.exists(key, "html"):
cached = persist.load(key, "html")
if cached is not False:
print(f"[{dt.now().strftime('%Y-%m-%d %H:%M:%S')}] Using cached cashflow for {symbol}")
return cached
try:
df = cashflow(symbol)
if df.empty:
return wrap_html(f"<h1>No cashflow for {symbol}</h1>")
if b2_save:
b2.upload_file("eshanhf", f"intraday/{symbol}.csv", df)
df_display = df.copy()
for col in df_display.columns:
df_display[col] = df_display[col].apply(
lambda x: format_large_number(x) if isinstance(x, (int, float)) else x
)
df_display.reset_index(inplace=True)
html = wrap_html(make_table(df_display), title=f"{symbol} Cash Flow")
persist.save(key, html, "html")
return html
except Exception as e:
print(f"[{dt.now().strftime('%Y-%m-%d %H:%M:%S')}] Error fetch_cashflow: {e}")
return wrap_html(html_error(f"Cash Flow Error: {e}"))
# ================================================================
# DIVIDEND
# ================================================================
def fetch_dividend(symbol,b2_save=False):
key = f"dividend_{symbol}"
if persist.exists(key, "html"):
cached = persist.load(key, "html")
if cached is not False:
print(f"[{dt.now().strftime('%Y-%m-%d %H:%M:%S')}] Using cached dividend for {symbol}")
return cached
try:
df = dividend(symbol)
if df.empty:
return wrap_html(f"<h1>No dividend history for {symbol}</h1>")
df_display = df.copy()
df_display.reset_index(inplace=True)
if b2_save:
b2.upload_file("eshanhf", f"intraday/{symbol}.csv", df)
html = wrap_html(make_table(df_display), title=f"{symbol} Dividends")
persist.save(key, html, "html")
return html
except Exception as e:
print(f"[{dt.now().strftime('%Y-%m-%d %H:%M:%S')}] Error fetch_dividend: {e}")
return wrap_html(html_error(f"Dividend Error: {e}"))
# ================================================================
# SPLIT
# ================================================================
def fetch_split(symbol,b2_save=False):
key = f"split_{symbol}"
if persist.exists(key, "html"):
cached = persist.load(key, "html")
if cached is not False:
print(f"[{dt.now().strftime('%Y-%m-%d %H:%M:%S')}] Using cached split for {symbol}")
return cached
try:
df = split(symbol)
if df.empty:
return wrap_html(f"<h1>No splits for {symbol}</h1>")
df_display = df.copy()
df_display.reset_index(inplace=True)
if b2_save:
b2.upload_file("eshanhf", f"intraday/{symbol}.csv", df)
html = wrap_html(make_table(df_display), title=f"{symbol} Splits")
persist.save(key, html, "html")
return html
except Exception as e:
print(f"[{dt.now().strftime('%Y-%m-%d %H:%M:%S')}] Error fetch_split: {e}")
return wrap_html(html_error(f"Split Error: {e}"))
# ================================================================
# EARNINGS
# ================================================================
def fetch_other(symbol,b2_save=False):
key = f"other_{symbol}"
if persist.exists(key, "html"):
cached = persist.load(key, "html")
if cached is not False:
print(f"[{dt.now().strftime('%Y-%m-%d %H:%M:%S')}] Using cached earnings for {symbol}")
return cached
try:
ticker = yf.Ticker(symbol + ".NS")
df = ticker.earnings
if df.empty:
return wrap_html(f"<h1>No earnings data for {symbol}</h1>")
df_display = df.copy()
df_display.reset_index(inplace=True)
if b2_save:
b2.upload_file("eshanhf", f"intraday/{symbol}.csv", df)
html = wrap_html(make_table(df_display), title=f"{symbol} Earnings")
persist.save(key, html, "html")
return html
except Exception as e:
print(f"[{dt.now().strftime('%Y-%m-%d %H:%M:%S')}] Error fetch_other: {e}")
return wrap_html(html_error(f"Earnings Error: {e}")) |