Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse files- pipeline/fetcher.py +838 -759
pipeline/fetcher.py
CHANGED
|
@@ -1,759 +1,838 @@
|
|
| 1 |
-
"""
|
| 2 |
-
pipeline/fetcher.py β Fetch 5-year financials.
|
| 3 |
-
Priority: yfinance (free, Indian stocks)
|
| 4 |
-
"""
|
| 5 |
-
from __future__ import annotations
|
| 6 |
-
import sys, re, json, datetime
|
| 7 |
-
from pathlib import Path
|
| 8 |
-
from typing import Optional, List, Dict, Any
|
| 9 |
-
|
| 10 |
-
import requests
|
| 11 |
-
from bs4 import BeautifulSoup
|
| 12 |
-
|
| 13 |
-
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 14 |
-
from config import FMP_API_KEY, FMP_BASE, REQUEST_TIMEOUT, DEFAULT_YEARS
|
| 15 |
-
from storage.cache import get_cached, set_cache
|
| 16 |
-
from pipeline.resolver import CompanyMeta
|
| 17 |
-
|
| 18 |
-
HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
# ββ Helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 22 |
-
|
| 23 |
-
def _s(v, default=None):
|
| 24 |
-
if v is None or (isinstance(v, float) and v != v): return default
|
| 25 |
-
return v
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
def _row(df, *keys):
|
| 29 |
-
"""Get a row from a yfinance DataFrame by trying multiple key names."""
|
| 30 |
-
for k in keys:
|
| 31 |
-
if k in df.index:
|
| 32 |
-
return df.loc[k].tolist()
|
| 33 |
-
return [None] * len(df.columns)
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
# ββ
|
| 37 |
-
|
| 38 |
-
def
|
| 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 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
"
|
| 433 |
-
"
|
| 434 |
-
"
|
| 435 |
-
"
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
"
|
| 447 |
-
"
|
| 448 |
-
"
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
"
|
| 562 |
-
"
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
return
|
| 673 |
-
|
| 674 |
-
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
|
| 678 |
-
|
| 679 |
-
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
|
| 692 |
-
|
| 693 |
-
|
| 694 |
-
|
| 695 |
-
|
| 696 |
-
|
| 697 |
-
|
| 698 |
-
|
| 699 |
-
|
| 700 |
-
|
| 701 |
-
|
| 702 |
-
|
| 703 |
-
|
| 704 |
-
|
| 705 |
-
|
| 706 |
-
|
| 707 |
-
|
| 708 |
-
|
| 709 |
-
|
| 710 |
-
|
| 711 |
-
|
| 712 |
-
|
| 713 |
-
|
| 714 |
-
|
| 715 |
-
|
| 716 |
-
|
| 717 |
-
|
| 718 |
-
|
| 719 |
-
|
| 720 |
-
|
| 721 |
-
|
| 722 |
-
|
| 723 |
-
|
| 724 |
-
|
| 725 |
-
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
|
| 730 |
-
|
| 731 |
-
|
| 732 |
-
|
| 733 |
-
|
| 734 |
-
|
| 735 |
-
|
| 736 |
-
|
| 737 |
-
|
| 738 |
-
|
| 739 |
-
|
| 740 |
-
|
| 741 |
-
|
| 742 |
-
|
| 743 |
-
|
| 744 |
-
|
| 745 |
-
|
| 746 |
-
|
| 747 |
-
|
| 748 |
-
|
| 749 |
-
|
| 750 |
-
|
| 751 |
-
|
| 752 |
-
|
| 753 |
-
|
| 754 |
-
|
| 755 |
-
|
| 756 |
-
|
| 757 |
-
|
| 758 |
-
|
| 759 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
pipeline/fetcher.py β Fetch 5-year financials.
|
| 3 |
+
Priority: yfinance (free, Indian stocks) -> FMP -> screener.in
|
| 4 |
+
"""
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
import sys, re, json, datetime
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Optional, List, Dict, Any
|
| 9 |
+
|
| 10 |
+
import requests
|
| 11 |
+
from bs4 import BeautifulSoup
|
| 12 |
+
|
| 13 |
+
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 14 |
+
from config import FMP_API_KEY, FMP_BASE, REQUEST_TIMEOUT, DEFAULT_YEARS
|
| 15 |
+
from storage.cache import get_cached, set_cache
|
| 16 |
+
from pipeline.resolver import CompanyMeta
|
| 17 |
+
|
| 18 |
+
HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# ββ Helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 22 |
+
|
| 23 |
+
def _s(v, default=None):
|
| 24 |
+
if v is None or (isinstance(v, float) and v != v): return default
|
| 25 |
+
return v
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _row(df, *keys):
|
| 29 |
+
"""Get a row from a yfinance DataFrame by trying multiple key names."""
|
| 30 |
+
for k in keys:
|
| 31 |
+
if k in df.index:
|
| 32 |
+
return df.loc[k].tolist()
|
| 33 |
+
return [None] * len(df.columns)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# ββ yahooquery fetcher (primary for Indian + global) βββββββββββββββββββββββββ
|
| 37 |
+
|
| 38 |
+
def _fetch_yahooquery(ticker: str, years: int, log_fn=None) -> Optional[Dict]:
|
| 39 |
+
"""Fetch financial statements via yahooquery. Returns normalized dict or None."""
|
| 40 |
+
def log(m):
|
| 41 |
+
if log_fn: log_fn(m)
|
| 42 |
+
try:
|
| 43 |
+
import yahooquery as yq
|
| 44 |
+
import pandas as pd
|
| 45 |
+
import math
|
| 46 |
+
|
| 47 |
+
log(f" -> yahooquery: fetching {ticker} ...")
|
| 48 |
+
t = yq.Ticker(ticker)
|
| 49 |
+
|
| 50 |
+
inc_df = t.income_statement(frequency='annual')
|
| 51 |
+
bs_df = t.balance_sheet(frequency='annual')
|
| 52 |
+
cf_df = t.cash_flow(frequency='annual')
|
| 53 |
+
|
| 54 |
+
if inc_df is None or isinstance(inc_df, str) or inc_df.empty:
|
| 55 |
+
log(" [ERR] yahooquery returned empty income statement")
|
| 56 |
+
return None
|
| 57 |
+
|
| 58 |
+
# ββ Filter to clean annual rows only (periodType == '12M') ββ
|
| 59 |
+
def clean_df(df):
|
| 60 |
+
if df is None or isinstance(df, str) or df.empty:
|
| 61 |
+
return pd.DataFrame()
|
| 62 |
+
df = df.reset_index()
|
| 63 |
+
if 'asOfDate' not in df.columns:
|
| 64 |
+
return df
|
| 65 |
+
df = df.dropna(subset=['asOfDate'])
|
| 66 |
+
df['asOfDate'] = pd.to_datetime(df['asOfDate'])
|
| 67 |
+
# Keep only 12M (full annual) rows, not TTM or quarterly
|
| 68 |
+
if 'periodType' in df.columns:
|
| 69 |
+
annual = df[df['periodType'] == '12M']
|
| 70 |
+
if not annual.empty:
|
| 71 |
+
df = annual
|
| 72 |
+
df = df.sort_values('asOfDate')
|
| 73 |
+
# Deduplicate: keep last row per year-month (safety net)
|
| 74 |
+
df['ym'] = df['asOfDate'].dt.to_period('M')
|
| 75 |
+
df = df.drop_duplicates(subset=['ym'], keep='last').drop(columns=['ym'])
|
| 76 |
+
return df.reset_index(drop=True)
|
| 77 |
+
|
| 78 |
+
inc = clean_df(inc_df)
|
| 79 |
+
bs = clean_df(bs_df)
|
| 80 |
+
cf = clean_df(cf_df)
|
| 81 |
+
|
| 82 |
+
if inc.empty:
|
| 83 |
+
log(" [ERR] yahooquery: no usable annual rows after filtering")
|
| 84 |
+
return None
|
| 85 |
+
|
| 86 |
+
# Take the most recent `years` rows (oldestβnewest)
|
| 87 |
+
inc = inc.tail(years)
|
| 88 |
+
bs = bs.tail(years) if not bs.empty else pd.DataFrame()
|
| 89 |
+
cf = cf.tail(years) if not cf.empty else pd.DataFrame()
|
| 90 |
+
|
| 91 |
+
# Year labels
|
| 92 |
+
year_labels = [d.strftime('%Y/%m') for d in inc['asOfDate']]
|
| 93 |
+
n = len(year_labels)
|
| 94 |
+
|
| 95 |
+
# Determine currency and scaling
|
| 96 |
+
currency = "INR"
|
| 97 |
+
if 'currencyCode' in inc.columns:
|
| 98 |
+
cur_vals = inc['currencyCode'].dropna().unique()
|
| 99 |
+
if len(cur_vals) > 0:
|
| 100 |
+
currency = str(cur_vals[-1])
|
| 101 |
+
|
| 102 |
+
if currency == "INR":
|
| 103 |
+
scale = 1e7 # raw INR -> Crores
|
| 104 |
+
units = "Crores"
|
| 105 |
+
units_label = "INR Crores (βΉ Cr)"
|
| 106 |
+
else:
|
| 107 |
+
scale = 1e6
|
| 108 |
+
units = "Millions"
|
| 109 |
+
units_label = f"{currency} Millions"
|
| 110 |
+
|
| 111 |
+
def gcol(df, *keys):
|
| 112 |
+
"""Get column values (oldestβnewest list of length n), scaled."""
|
| 113 |
+
for k in keys:
|
| 114 |
+
if k in df.columns:
|
| 115 |
+
vals = df[k].tolist()
|
| 116 |
+
result = []
|
| 117 |
+
for v in vals:
|
| 118 |
+
if v is None or (isinstance(v, float) and math.isnan(v)):
|
| 119 |
+
result.append(None)
|
| 120 |
+
else:
|
| 121 |
+
result.append(round(float(v) / scale, 2))
|
| 122 |
+
# Pad or trim to n
|
| 123 |
+
while len(result) < n: result.append(None)
|
| 124 |
+
return result[:n]
|
| 125 |
+
return [None] * n
|
| 126 |
+
|
| 127 |
+
def gcol_raw(df, *keys):
|
| 128 |
+
"""Get column values without scaling."""
|
| 129 |
+
for k in keys:
|
| 130 |
+
if k in df.columns:
|
| 131 |
+
vals = df[k].tolist()
|
| 132 |
+
result = []
|
| 133 |
+
for v in vals:
|
| 134 |
+
if v is None or (isinstance(v, float) and math.isnan(v)):
|
| 135 |
+
result.append(None)
|
| 136 |
+
else:
|
| 137 |
+
result.append(float(v))
|
| 138 |
+
while len(result) < n: result.append(None)
|
| 139 |
+
return result[:n]
|
| 140 |
+
return [None] * n
|
| 141 |
+
|
| 142 |
+
income = {
|
| 143 |
+
"revenue": gcol(inc, "TotalRevenue", "OperatingRevenue"),
|
| 144 |
+
"cost_of_revenue": gcol(inc, "CostOfRevenue", "ReconciledCostOfRevenue"),
|
| 145 |
+
"gross_profit": gcol(inc, "GrossProfit"),
|
| 146 |
+
"operating_expenses": gcol(inc, "OperatingExpense", "TotalExpenses"),
|
| 147 |
+
"operating_income": gcol(inc, "OperatingIncome", "EBIT"),
|
| 148 |
+
"ebitda": gcol(inc, "EBITDA", "NormalizedEBITDA"),
|
| 149 |
+
"depreciation_amort": gcol(inc, "ReconciledDepreciation", "DepreciationAndAmortizationInIncomeStatement"),
|
| 150 |
+
"interest_expense": gcol(inc, "InterestExpenseNonOperating", "InterestExpense"),
|
| 151 |
+
"pretax_income": gcol(inc, "PretaxIncome"),
|
| 152 |
+
"tax_expense": gcol(inc, "TaxProvision"),
|
| 153 |
+
"net_income": gcol(inc, "NetIncome", "NetIncomeCommonStockholders"),
|
| 154 |
+
"diluted_eps": gcol_raw(inc, "DilutedEPS", "BasicEPS"),
|
| 155 |
+
"diluted_shares": gcol_raw(inc, "DilutedAverageShares", "BasicAverageShares"),
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
balance = {
|
| 159 |
+
"cash_and_equivalents": gcol(bs, "CashAndCashEquivalents", "CashFinancial"),
|
| 160 |
+
"short_term_investments": gcol(bs, "OtherShortTermInvestments", "InvestmentsAndAdvances"),
|
| 161 |
+
"receivables": gcol(bs, "AccountsReceivable", "Receivables"),
|
| 162 |
+
"inventory": gcol(bs, "Inventory"),
|
| 163 |
+
"other_current_assets": gcol(bs, "OtherCurrentAssets"),
|
| 164 |
+
"total_current_assets": gcol(bs, "CurrentAssets"),
|
| 165 |
+
"ppe_net": gcol(bs, "NetPPE"),
|
| 166 |
+
"goodwill": gcol(bs, "Goodwill"),
|
| 167 |
+
"intangibles": gcol(bs, "OtherIntangibleAssets"),
|
| 168 |
+
"other_long_term_assets": gcol(bs, "OtherNonCurrentAssets"),
|
| 169 |
+
"total_assets": gcol(bs, "TotalAssets"),
|
| 170 |
+
"accounts_payable": gcol(bs, "AccountsPayable", "Payables"),
|
| 171 |
+
"short_term_debt": gcol(bs, "CurrentDebt", "CurrentDebtAndCapitalLeaseObligation"),
|
| 172 |
+
"other_current_liabilities": gcol(bs, "OtherCurrentLiabilities"),
|
| 173 |
+
"total_current_liabilities": gcol(bs, "CurrentLiabilities"),
|
| 174 |
+
"long_term_debt": gcol(bs, "LongTermDebt", "LongTermDebtAndCapitalLeaseObligation"),
|
| 175 |
+
"other_long_term_liabilities":gcol(bs, "OtherNonCurrentLiabilities"),
|
| 176 |
+
"total_liabilities": gcol(bs, "TotalLiabilitiesNetMinorityInterest", "TotalLiabilities"),
|
| 177 |
+
"total_equity": gcol(bs, "StockholdersEquity", "CommonStockEquity"),
|
| 178 |
+
"total_liab_and_equity": gcol(bs, "TotalAssets"),
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
cfo = gcol(cf, "OperatingCashFlow", "CashFlowFromContinuingOperatingActivities")
|
| 182 |
+
cap = gcol(cf, "CapitalExpenditure")
|
| 183 |
+
fcf = gcol(cf, "FreeCashFlow")
|
| 184 |
+
# Compute FCF from CFO - CapEx if missing
|
| 185 |
+
for i in range(n):
|
| 186 |
+
if fcf[i] is None and cfo[i] is not None and cap[i] is not None:
|
| 187 |
+
fcf[i] = round(cfo[i] + cap[i], 2) # CapEx is negative in yahooquery
|
| 188 |
+
|
| 189 |
+
cashflow = {
|
| 190 |
+
"net_income": gcol(cf, "NetIncomeFromContinuingOperations", "NetIncome"),
|
| 191 |
+
"depreciation_amort": gcol(cf, "DepreciationAndAmortization", "Depreciation"),
|
| 192 |
+
"stock_based_comp": gcol(cf, "StockBasedCompensation"),
|
| 193 |
+
"working_capital_changes": gcol(cf, "ChangeInWorkingCapital"),
|
| 194 |
+
"other_operating": [None] * n,
|
| 195 |
+
"cash_from_operations": cfo,
|
| 196 |
+
"capex": cap,
|
| 197 |
+
"acquisitions": gcol(cf, "PurchaseOfBusiness", "AcquisitionOfBusiness"),
|
| 198 |
+
"cash_from_investing": gcol(cf, "InvestingCashFlow", "CashFlowFromContinuingInvestingActivities"),
|
| 199 |
+
"debt_issuance_repayment": gcol(cf, "NetLongTermDebtIssuance", "NetIssuancePaymentsOfDebt"),
|
| 200 |
+
"stock_buybacks": gcol(cf, "NetCommonStockIssuance", "RepurchaseOfCapitalStock"),
|
| 201 |
+
"dividends_paid": gcol(cf, "CashDividendsPaid", "DividendsPaid"),
|
| 202 |
+
"cash_from_financing": gcol(cf, "FinancingCashFlow", "CashFlowFromContinuingFinancingActivities"),
|
| 203 |
+
"net_change_in_cash": gcol(cf, "ChangesInCash", "ChangeInCashSupplementalAsReported"),
|
| 204 |
+
"free_cash_flow": fcf,
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
# Valuation snapshot
|
| 208 |
+
val_snap = {}
|
| 209 |
+
try:
|
| 210 |
+
fd = t.financial_data.get(ticker, {})
|
| 211 |
+
if isinstance(fd, dict):
|
| 212 |
+
val_snap["target_mean_price"] = fd.get("targetMeanPrice")
|
| 213 |
+
val_snap["target_high_price"] = fd.get("targetHighPrice")
|
| 214 |
+
val_snap["target_low_price"] = fd.get("targetLowPrice")
|
| 215 |
+
val_snap["wacc_estimate"] = 0.10
|
| 216 |
+
|
| 217 |
+
sd = t.summary_detail.get(ticker, {})
|
| 218 |
+
if isinstance(sd, dict):
|
| 219 |
+
val_snap["pe_ttm"] = sd.get("trailingPE")
|
| 220 |
+
val_snap["dividend_yield"] = sd.get("dividendYield")
|
| 221 |
+
except Exception:
|
| 222 |
+
pass
|
| 223 |
+
|
| 224 |
+
log(f" [OK] yahooquery data ready ({n} years, {currency}, in {units})")
|
| 225 |
+
|
| 226 |
+
return {
|
| 227 |
+
"years": year_labels,
|
| 228 |
+
"income_statement": income,
|
| 229 |
+
"balance_sheet": balance,
|
| 230 |
+
"cash_flow": cashflow,
|
| 231 |
+
"currency": currency,
|
| 232 |
+
"units": units,
|
| 233 |
+
"units_label": units_label,
|
| 234 |
+
"scale": scale,
|
| 235 |
+
"source": "Yahoo Finance (yahooquery)",
|
| 236 |
+
"valuation_snapshot": val_snap,
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
except Exception as e:
|
| 240 |
+
import traceback
|
| 241 |
+
log(f" [ERR] yahooquery error: {e}\n{traceback.format_exc()}")
|
| 242 |
+
return None
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
# Keep a stub for backward compatibility (if anything still calls _fetch_yfinance)
|
| 246 |
+
def _fetch_yfinance(ticker: str, years: int, log_fn=None) -> Optional[Dict]:
|
| 247 |
+
return _fetch_yahooquery(ticker, years, log_fn)
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
# ββ FMP fetcher (secondary for global) βββββββββββββββββββββββββββββββββββββββ
|
| 251 |
+
|
| 252 |
+
def _fmp_get(path, params=None):
|
| 253 |
+
if not FMP_API_KEY: return None
|
| 254 |
+
p = {"apikey": FMP_API_KEY}
|
| 255 |
+
if params: p.update(params)
|
| 256 |
+
try:
|
| 257 |
+
r = requests.get(f"{FMP_BASE}{path}", params=p, timeout=REQUEST_TIMEOUT, headers=HEADERS)
|
| 258 |
+
r.raise_for_status()
|
| 259 |
+
return r.json()
|
| 260 |
+
except Exception:
|
| 261 |
+
return None
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def _normalise_fmp(raw, years):
|
| 265 |
+
inc = list(reversed(raw.get("income", [])))[:years]
|
| 266 |
+
bal = list(reversed(raw.get("balance", [])))[:years]
|
| 267 |
+
cf = list(reversed(raw.get("cashflow", [])))[:years]
|
| 268 |
+
|
| 269 |
+
def col(lst, key):
|
| 270 |
+
return [_s(d.get(key)) for d in lst]
|
| 271 |
+
|
| 272 |
+
year_labels = [d.get("calendarYear", str(d.get("date",""))[:4]) for d in inc]
|
| 273 |
+
income = {
|
| 274 |
+
"revenue": col(inc, "revenue"),
|
| 275 |
+
"cost_of_revenue": col(inc, "costOfRevenue"),
|
| 276 |
+
"gross_profit": col(inc, "grossProfit"),
|
| 277 |
+
"operating_expenses": col(inc, "operatingExpenses"),
|
| 278 |
+
"operating_income": col(inc, "operatingIncome"),
|
| 279 |
+
"ebitda": col(inc, "ebitda"),
|
| 280 |
+
"depreciation_amort": col(inc, "depreciationAndAmortization"),
|
| 281 |
+
"interest_expense": col(inc, "interestExpense"),
|
| 282 |
+
"pretax_income": col(inc, "incomeBeforeTax"),
|
| 283 |
+
"tax_expense": col(inc, "incomeTaxExpense"),
|
| 284 |
+
"net_income": col(inc, "netIncome"),
|
| 285 |
+
"diluted_eps": col(inc, "epsdiluted"),
|
| 286 |
+
"diluted_shares": col(inc, "weightedAverageShsOutDil"),
|
| 287 |
+
}
|
| 288 |
+
balance = {
|
| 289 |
+
"cash_and_equivalents": col(bal, "cashAndCashEquivalents"),
|
| 290 |
+
"short_term_investments": col(bal, "shortTermInvestments"),
|
| 291 |
+
"receivables": col(bal, "netReceivables"),
|
| 292 |
+
"inventory": col(bal, "inventory"),
|
| 293 |
+
"other_current_assets": col(bal, "otherCurrentAssets"),
|
| 294 |
+
"total_current_assets": col(bal, "totalCurrentAssets"),
|
| 295 |
+
"ppe_net": col(bal, "propertyPlantEquipmentNet"),
|
| 296 |
+
"goodwill": col(bal, "goodwill"),
|
| 297 |
+
"intangibles": col(bal, "intangibleAssets"),
|
| 298 |
+
"other_long_term_assets": col(bal, "otherNonCurrentAssets"),
|
| 299 |
+
"total_assets": col(bal, "totalAssets"),
|
| 300 |
+
"accounts_payable": col(bal, "accountPayables"),
|
| 301 |
+
"short_term_debt": col(bal, "shortTermDebt"),
|
| 302 |
+
"other_current_liabilities": col(bal, "otherCurrentLiabilities"),
|
| 303 |
+
"total_current_liabilities": col(bal, "totalCurrentLiabilities"),
|
| 304 |
+
"long_term_debt": col(bal, "longTermDebt"),
|
| 305 |
+
"other_long_term_liabilities":col(bal, "otherNonCurrentLiabilities"),
|
| 306 |
+
"total_liabilities": col(bal, "totalLiabilities"),
|
| 307 |
+
"total_equity": col(bal, "totalStockholdersEquity"),
|
| 308 |
+
"total_liab_and_equity": col(bal, "totalLiabilitiesAndStockholdersEquity"),
|
| 309 |
+
}
|
| 310 |
+
cashflow = {
|
| 311 |
+
"net_income": col(cf, "netIncome"),
|
| 312 |
+
"depreciation_amort": col(cf, "depreciationAndAmortization"),
|
| 313 |
+
"stock_based_comp": col(cf, "stockBasedCompensation"),
|
| 314 |
+
"working_capital_changes": col(cf, "changeInWorkingCapital"),
|
| 315 |
+
"other_operating": col(cf, "otherWorkingCapital"),
|
| 316 |
+
"cash_from_operations": col(cf, "netCashProvidedByOperatingActivities"),
|
| 317 |
+
"capex": col(cf, "capitalExpenditure"),
|
| 318 |
+
"acquisitions": col(cf, "acquisitionsNet"),
|
| 319 |
+
"cash_from_investing": col(cf, "netCashUsedForInvestingActivites"),
|
| 320 |
+
"debt_issuance_repayment": col(cf, "debtRepayment"),
|
| 321 |
+
"stock_buybacks": col(cf, "commonStockRepurchased"),
|
| 322 |
+
"dividends_paid": col(cf, "dividendsPaid"),
|
| 323 |
+
"cash_from_financing": col(cf, "netCashUsedProvidedByFinancingActivities"),
|
| 324 |
+
"net_change_in_cash": col(cf, "netChangeInCash"),
|
| 325 |
+
"free_cash_flow": col(cf, "freeCashFlow"),
|
| 326 |
+
}
|
| 327 |
+
return {
|
| 328 |
+
"years": year_labels, "income_statement": income,
|
| 329 |
+
"balance_sheet": balance, "cash_flow": cashflow,
|
| 330 |
+
"currency": "USD", "units": "millions",
|
| 331 |
+
"source": "FMP API",
|
| 332 |
+
"valuation_snapshot": {},
|
| 333 |
+
}
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def _fetch_fmp(ticker, years, log_fn=None):
|
| 337 |
+
def log(m):
|
| 338 |
+
if log_fn: log_fn(m)
|
| 339 |
+
if not FMP_API_KEY:
|
| 340 |
+
return None
|
| 341 |
+
log(" -> FMP: fetching statements ...")
|
| 342 |
+
lim = years + 1
|
| 343 |
+
raw = {
|
| 344 |
+
"income": _fmp_get(f"/v3/income-statement/{ticker}", {"limit": lim, "period": "annual"}) or [],
|
| 345 |
+
"balance": _fmp_get(f"/v3/balance-sheet-statement/{ticker}", {"limit": lim, "period": "annual"}) or [],
|
| 346 |
+
"cashflow": _fmp_get(f"/v3/cash-flow-statement/{ticker}", {"limit": lim, "period": "annual"}) or [],
|
| 347 |
+
}
|
| 348 |
+
if not raw["income"]:
|
| 349 |
+
log(" [ERR] FMP returned no data")
|
| 350 |
+
return None
|
| 351 |
+
log(" [OK] FMP data ready")
|
| 352 |
+
data = _normalise_fmp(raw, years)
|
| 353 |
+
# Add valuation
|
| 354 |
+
rtm = (_fmp_get(f"/v3/ratios-ttm/{ticker}") or [{}])[0]
|
| 355 |
+
km = (_fmp_get(f"/v3/key-metrics-ttm/{ticker}") or [{}])[0]
|
| 356 |
+
data["valuation_snapshot"] = {
|
| 357 |
+
"pe_ttm": _s(rtm.get("peRatioTTM")),
|
| 358 |
+
"pb": _s(rtm.get("priceToBookRatioTTM")),
|
| 359 |
+
"ps": _s(rtm.get("priceToSalesRatioTTM")),
|
| 360 |
+
"ev_ebitda": _s(km.get("enterpriseValueOverEBITDATTM")),
|
| 361 |
+
"ev_revenue": _s(km.get("evToSalesTTM")),
|
| 362 |
+
"fcf_yield": _s(km.get("freeCashFlowYieldTTM")),
|
| 363 |
+
"dividend_yield": _s(rtm.get("dividendYieldTTM")),
|
| 364 |
+
}
|
| 365 |
+
return data
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
# ββ screener.in (Indian fallback) ββββββββββββββββββββββββββββββββββββββββββββ
|
| 369 |
+
|
| 370 |
+
def _scrape_screener(ticker: str, log_fn=None) -> Optional[Dict]:
|
| 371 |
+
def log(m):
|
| 372 |
+
if log_fn: log_fn(m)
|
| 373 |
+
# Ticker usually like RELIANCE.NS, extract RELIANCE
|
| 374 |
+
base_ticker = ticker.split(".")[0].upper()
|
| 375 |
+
for url in [f"https://www.screener.in/company/{base_ticker}/consolidated/",
|
| 376 |
+
f"https://www.screener.in/company/{base_ticker}/"]:
|
| 377 |
+
try:
|
| 378 |
+
log(f" -> screener.in: {url}")
|
| 379 |
+
r = requests.get(url, timeout=REQUEST_TIMEOUT, headers=HEADERS)
|
| 380 |
+
if r.status_code == 200:
|
| 381 |
+
soup = BeautifulSoup(r.text, "lxml")
|
| 382 |
+
sections = {}
|
| 383 |
+
for sec_id, key in [("profit-loss","income"),("balance-sheet","balance"),
|
| 384 |
+
("cash-flow","cashflow")]:
|
| 385 |
+
sec = soup.find("section", {"id": sec_id})
|
| 386 |
+
if sec:
|
| 387 |
+
table = sec.find("table")
|
| 388 |
+
if table:
|
| 389 |
+
result = {}
|
| 390 |
+
for row in table.find_all("tr"):
|
| 391 |
+
cells = row.find_all(["td","th"])
|
| 392 |
+
if len(cells) < 2: continue
|
| 393 |
+
label = cells[0].get_text(strip=True)
|
| 394 |
+
vals = []
|
| 395 |
+
for c in cells[1:]:
|
| 396 |
+
t2 = c.get_text(strip=True).replace(",","").replace("+","")
|
| 397 |
+
try: vals.append(float(t2))
|
| 398 |
+
except: vals.append(None)
|
| 399 |
+
if label: result[label] = vals
|
| 400 |
+
sections[key] = result
|
| 401 |
+
if "years" not in sections:
|
| 402 |
+
hdr = table.find("tr")
|
| 403 |
+
if hdr:
|
| 404 |
+
sections["years"] = [c.get_text(strip=True)
|
| 405 |
+
for c in hdr.find_all(["th","td"])[1:]]
|
| 406 |
+
if sections:
|
| 407 |
+
sections["source_url"] = url
|
| 408 |
+
log(" [OK] screener.in scraped")
|
| 409 |
+
return sections
|
| 410 |
+
except Exception as e:
|
| 411 |
+
log(f" [ERR] screener.in error: {e}")
|
| 412 |
+
return None
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
def _normalise_screener(raw, years):
|
| 416 |
+
yr = raw.get("years", [])[:years]
|
| 417 |
+
n = len(yr)
|
| 418 |
+
inc = raw.get("income", {})
|
| 419 |
+
bal = raw.get("balance", {})
|
| 420 |
+
cf = raw.get("cashflow", {})
|
| 421 |
+
|
| 422 |
+
def row(*keys):
|
| 423 |
+
for k in keys:
|
| 424 |
+
if k in inc: return inc[k][:n]
|
| 425 |
+
if k in bal: return bal[k][:n]
|
| 426 |
+
if k in cf: return cf[k][:n]
|
| 427 |
+
return [None]*n
|
| 428 |
+
|
| 429 |
+
income = {
|
| 430 |
+
"revenue": row("Revenue","Net Sales","Sales"),
|
| 431 |
+
"cost_of_revenue": row("Expenses","Cost of Goods Sold"),
|
| 432 |
+
"gross_profit": row("Gross Profit"),
|
| 433 |
+
"operating_expenses": [None]*n,
|
| 434 |
+
"operating_income": row("Operating Profit","EBIT","PBDIT"),
|
| 435 |
+
"ebitda": row("PBDIT","EBITDA"),
|
| 436 |
+
"depreciation_amort": row("Depreciation"),
|
| 437 |
+
"interest_expense": row("Interest"),
|
| 438 |
+
"pretax_income": row("Profit before tax","PBT"),
|
| 439 |
+
"tax_expense": row("Tax"),
|
| 440 |
+
"net_income": row("Net Profit","PAT"),
|
| 441 |
+
"diluted_eps": row("EPS in Rs"),
|
| 442 |
+
"diluted_shares": [None]*n,
|
| 443 |
+
}
|
| 444 |
+
balance = {
|
| 445 |
+
"cash_and_equivalents": row("Cash Equivalents"),
|
| 446 |
+
"short_term_investments": [None]*n,
|
| 447 |
+
"receivables": [None]*n,
|
| 448 |
+
"inventory": [None]*n,
|
| 449 |
+
"other_current_assets": [None]*n,
|
| 450 |
+
"total_current_assets": row("Current Assets"),
|
| 451 |
+
"ppe_net": row("Fixed Assets"),
|
| 452 |
+
"goodwill": [None]*n,
|
| 453 |
+
"intangibles": [None]*n,
|
| 454 |
+
"other_long_term_assets": [None]*n,
|
| 455 |
+
"total_assets": row("Total Assets","Balance Sheet Size"),
|
| 456 |
+
"accounts_payable": [None]*n,
|
| 457 |
+
"short_term_debt": row("Short Term Borrowing"),
|
| 458 |
+
"other_current_liabilities": [None]*n,
|
| 459 |
+
"total_current_liabilities": row("Current Liabilities"),
|
| 460 |
+
"long_term_debt": row("Borrowings","Long Term Borrowing"),
|
| 461 |
+
"other_long_term_liabilities":[None]*n,
|
| 462 |
+
"total_liabilities": row("Total Liabilities"),
|
| 463 |
+
"total_equity": row("Equity Capital","Total Equity"),
|
| 464 |
+
"total_liab_and_equity": row("Total Assets","Balance Sheet Size"),
|
| 465 |
+
}
|
| 466 |
+
cfo_vals = row("Cash from Operating Activity","Cash from Operations")
|
| 467 |
+
cap_vals = row("Fixed Assets Purchased","Capital Expenditure")
|
| 468 |
+
fcf_vals = [(c - abs(x)) if c is not None and x is not None else None
|
| 469 |
+
for c, x in zip(cfo_vals, cap_vals)]
|
| 470 |
+
cashflow = {
|
| 471 |
+
"net_income": income["net_income"],
|
| 472 |
+
"depreciation_amort": income["depreciation_amort"],
|
| 473 |
+
"stock_based_comp": [None]*n,
|
| 474 |
+
"working_capital_changes": [None]*n,
|
| 475 |
+
"other_operating": [None]*n,
|
| 476 |
+
"cash_from_operations": cfo_vals,
|
| 477 |
+
"capex": cap_vals,
|
| 478 |
+
"acquisitions": [None]*n,
|
| 479 |
+
"cash_from_investing": row("Cash from Investing Activity"),
|
| 480 |
+
"debt_issuance_repayment": [None]*n,
|
| 481 |
+
"stock_buybacks": [None]*n,
|
| 482 |
+
"dividends_paid": row("Dividend Amount"),
|
| 483 |
+
"cash_from_financing": row("Cash from Financing Activity"),
|
| 484 |
+
"net_change_in_cash": row("Net Cash Flow"),
|
| 485 |
+
"free_cash_flow": fcf_vals,
|
| 486 |
+
}
|
| 487 |
+
return {
|
| 488 |
+
"years": yr, "income_statement": income, "balance_sheet": balance, "cash_flow": cashflow,
|
| 489 |
+
"currency": "INR", "units": "crores",
|
| 490 |
+
"source": f"screener.in ({raw.get('source_url','')})",
|
| 491 |
+
"valuation_snapshot": {},
|
| 492 |
+
}
|
| 493 |
+
|
| 494 |
+
# ββ stockanalysis.com (Global fallback for >4 years) ββββββββββββββββββββββββββ
|
| 495 |
+
|
| 496 |
+
def _scrape_stockanalysis(ticker: str, years: int, log_fn=None) -> Optional[Dict]:
|
| 497 |
+
def log(m):
|
| 498 |
+
if log_fn: log_fn(m)
|
| 499 |
+
base_ticker = ticker.split(".")[0].lower()
|
| 500 |
+
|
| 501 |
+
urls = {
|
| 502 |
+
"income": f"https://stockanalysis.com/stocks/{base_ticker}/financials/",
|
| 503 |
+
"balance": f"https://stockanalysis.com/stocks/{base_ticker}/financials/balance-sheet/",
|
| 504 |
+
"cashflow": f"https://stockanalysis.com/stocks/{base_ticker}/financials/cash-flow-statement/"
|
| 505 |
+
}
|
| 506 |
+
|
| 507 |
+
raw = {}
|
| 508 |
+
try:
|
| 509 |
+
for key, url in urls.items():
|
| 510 |
+
log(f" -> stockanalysis.com: {url}")
|
| 511 |
+
r = requests.get(url, timeout=REQUEST_TIMEOUT, headers=HEADERS)
|
| 512 |
+
if r.status_code != 200:
|
| 513 |
+
log(f" [ERR] stockanalysis.com returned {r.status_code} for {key}")
|
| 514 |
+
return None
|
| 515 |
+
soup = BeautifulSoup(r.text, "lxml")
|
| 516 |
+
table = soup.find("table")
|
| 517 |
+
if not table: return None
|
| 518 |
+
|
| 519 |
+
# Parse headers (Skip TTM, take `years` count)
|
| 520 |
+
thead = table.find("thead")
|
| 521 |
+
ths = thead.find("tr").find_all("th")
|
| 522 |
+
# Index 0 is "Fiscal Year", Index 1 is "TTM" (usually). Index 2+ are the years.
|
| 523 |
+
if len(ths) < 3: return None
|
| 524 |
+
|
| 525 |
+
# Only need to extract year labels once
|
| 526 |
+
if "years" not in raw:
|
| 527 |
+
# Get the years newest to oldest, then reverse to oldest to newest
|
| 528 |
+
year_labels = [th.get_text(strip=True) for th in ths[2:2+years]]
|
| 529 |
+
raw["years"] = list(reversed(year_labels))
|
| 530 |
+
|
| 531 |
+
data_rows = {}
|
| 532 |
+
tbody = table.find("tbody")
|
| 533 |
+
for tr in tbody.find_all("tr"):
|
| 534 |
+
tds = tr.find_all("td")
|
| 535 |
+
if len(tds) < 3: continue
|
| 536 |
+
label = tds[0].get_text(strip=True)
|
| 537 |
+
vals = []
|
| 538 |
+
for td in tds[2:2+years]:
|
| 539 |
+
text = td.get_text(strip=True).replace(",", "")
|
| 540 |
+
if text == "-" or text == "":
|
| 541 |
+
vals.append(None)
|
| 542 |
+
else:
|
| 543 |
+
try: vals.append(float(text))
|
| 544 |
+
except: vals.append(None)
|
| 545 |
+
data_rows[label] = list(reversed(vals))
|
| 546 |
+
raw[key] = data_rows
|
| 547 |
+
|
| 548 |
+
except Exception as e:
|
| 549 |
+
log(f" [ERR] stockanalysis error: {e}")
|
| 550 |
+
return None
|
| 551 |
+
|
| 552 |
+
n = len(raw.get("years", []))
|
| 553 |
+
if n == 0: return None
|
| 554 |
+
|
| 555 |
+
def row(sec, *keys):
|
| 556 |
+
for k in keys:
|
| 557 |
+
if k in raw[sec]: return raw[sec][k]
|
| 558 |
+
return [None]*n
|
| 559 |
+
|
| 560 |
+
income = {
|
| 561 |
+
"revenue": row("income", "Revenue"),
|
| 562 |
+
"cost_of_revenue": row("income", "Cost of Revenue"),
|
| 563 |
+
"gross_profit": row("income", "Gross Profit"),
|
| 564 |
+
"operating_expenses": row("income", "Operating Expenses"),
|
| 565 |
+
"operating_income": row("income", "Operating Income"),
|
| 566 |
+
"ebitda": row("income", "EBITDA"),
|
| 567 |
+
"depreciation_amort": row("income", "Depreciation & Amortization"),
|
| 568 |
+
"interest_expense": row("income", "Interest Expense / Income"),
|
| 569 |
+
"pretax_income": row("income", "Pretax Income"),
|
| 570 |
+
"tax_expense": row("income", "Income Tax"),
|
| 571 |
+
"net_income": row("income", "Net Income"),
|
| 572 |
+
"diluted_eps": row("income", "EPS (Diluted)"),
|
| 573 |
+
"diluted_shares": row("income", "Shares Outstanding (Diluted)"),
|
| 574 |
+
}
|
| 575 |
+
balance = {
|
| 576 |
+
"cash_and_equivalents": row("balance", "Cash & Equivalents"),
|
| 577 |
+
"short_term_investments": row("balance", "Short-Term Investments"),
|
| 578 |
+
"receivables": row("balance", "Accounts Receivable"),
|
| 579 |
+
"inventory": row("balance", "Inventory"),
|
| 580 |
+
"other_current_assets": row("balance", "Other Current Assets"),
|
| 581 |
+
"total_current_assets": row("balance", "Total Current Assets"),
|
| 582 |
+
"ppe_net": row("balance", "Property, Plant & Equipment"),
|
| 583 |
+
"goodwill": row("balance", "Goodwill and Intangibles", "Goodwill"),
|
| 584 |
+
"intangibles": [None]*n,
|
| 585 |
+
"other_long_term_assets": row("balance", "Other Long-Term Assets"),
|
| 586 |
+
"total_assets": row("balance", "Total Assets"),
|
| 587 |
+
"accounts_payable": row("balance", "Accounts Payable"),
|
| 588 |
+
"short_term_debt": row("balance", "Current Debt"),
|
| 589 |
+
"other_current_liabilities": row("balance", "Other Current Liabilities"),
|
| 590 |
+
"total_current_liabilities": row("balance", "Total Current Liabilities"),
|
| 591 |
+
"long_term_debt": row("balance", "Long-Term Debt"),
|
| 592 |
+
"other_long_term_liabilities":row("balance", "Other Long-Term Liabilities"),
|
| 593 |
+
"total_liabilities": row("balance", "Total Liabilities"),
|
| 594 |
+
"total_equity": row("balance", "Shareholders' Equity"),
|
| 595 |
+
"total_liab_and_equity": row("balance", "Total Liabilities and Equity"),
|
| 596 |
+
}
|
| 597 |
+
cashflow = {
|
| 598 |
+
"net_income": row("cashflow", "Net Income"),
|
| 599 |
+
"depreciation_amort": row("cashflow", "Depreciation & Amortization"),
|
| 600 |
+
"stock_based_comp": row("cashflow", "Share-Based Compensation"),
|
| 601 |
+
"working_capital_changes": [None]*n,
|
| 602 |
+
"other_operating": row("cashflow", "Other Operating Activities"),
|
| 603 |
+
"cash_from_operations": row("cashflow", "Operating Cash Flow"),
|
| 604 |
+
"capex": row("cashflow", "Capital Expenditures"),
|
| 605 |
+
"acquisitions": row("cashflow", "Acquisitions"),
|
| 606 |
+
"cash_from_investing": row("cashflow", "Investing Cash Flow"),
|
| 607 |
+
"debt_issuance_repayment": row("cashflow", "Net Debt Issued/Paid"),
|
| 608 |
+
"stock_buybacks": row("cashflow", "Common Stock Issued/Repurchased", "Stock Repurchases"),
|
| 609 |
+
"dividends_paid": row("cashflow", "Dividends Paid"),
|
| 610 |
+
"cash_from_financing": row("cashflow", "Financing Cash Flow"),
|
| 611 |
+
"net_change_in_cash": row("cashflow", "Net Change in Cash"),
|
| 612 |
+
"free_cash_flow": row("cashflow", "Free Cash Flow"),
|
| 613 |
+
}
|
| 614 |
+
return {
|
| 615 |
+
"years": raw["years"], "income_statement": income, "balance_sheet": balance, "cash_flow": cashflow,
|
| 616 |
+
"currency": "USD", "units": "millions",
|
| 617 |
+
"source": "stockanalysis.com",
|
| 618 |
+
"valuation_snapshot": {},
|
| 619 |
+
}
|
| 620 |
+
|
| 621 |
+
# ββ Peer snapshot βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 622 |
+
|
| 623 |
+
def fetch_peer_snapshot(ticker: str) -> Optional[Dict]:
|
| 624 |
+
try:
|
| 625 |
+
import yahooquery as yq
|
| 626 |
+
t = yq.Ticker(ticker)
|
| 627 |
+
price_data = t.price.get(ticker, {})
|
| 628 |
+
profile_data = t.summary_profile.get(ticker, {})
|
| 629 |
+
key_stats = t.key_stats.get(ticker, {})
|
| 630 |
+
fin_data = t.financial_data.get(ticker, {})
|
| 631 |
+
summary_det = t.summary_detail.get(ticker, {})
|
| 632 |
+
|
| 633 |
+
name = price_data.get("longName") or price_data.get("shortName", "")
|
| 634 |
+
if not name:
|
| 635 |
+
return None
|
| 636 |
+
|
| 637 |
+
# Try to get latest revenue from income statement
|
| 638 |
+
rev = None
|
| 639 |
+
try:
|
| 640 |
+
inc = t.income_statement(frequency='annual')
|
| 641 |
+
if inc is not None and not isinstance(inc, str) and not inc.empty:
|
| 642 |
+
annual_inc = inc[inc.get('periodType', '') == '12M'] if 'periodType' in inc.columns else inc
|
| 643 |
+
rev_col = annual_inc['TotalRevenue'].dropna() if 'TotalRevenue' in annual_inc.columns else None
|
| 644 |
+
if rev_col is not None and not rev_col.empty:
|
| 645 |
+
rev = float(rev_col.iloc[-1])
|
| 646 |
+
except Exception:
|
| 647 |
+
pass
|
| 648 |
+
|
| 649 |
+
ratios_ttm = (_fmp_get(f"/v3/ratios-ttm/{ticker}") or [{}])[0]
|
| 650 |
+
|
| 651 |
+
return {
|
| 652 |
+
"name": name,
|
| 653 |
+
"ticker": ticker,
|
| 654 |
+
"rationale": f"Industry peer ({profile_data.get('industry', '')})",
|
| 655 |
+
"latest_year": "",
|
| 656 |
+
"currency": price_data.get("currency", "INR"),
|
| 657 |
+
"units": "actuals",
|
| 658 |
+
"revenue": _s(rev),
|
| 659 |
+
"gross_margin": _s(fin_data.get("grossMargins")),
|
| 660 |
+
"operating_margin": _s(fin_data.get("operatingMargins")),
|
| 661 |
+
"net_margin": _s(fin_data.get("profitMargins")),
|
| 662 |
+
"roe": _s(fin_data.get("returnOnEquity")),
|
| 663 |
+
"roic": _s(ratios_ttm.get("returnOnCapitalEmployedTTM")),
|
| 664 |
+
"debt_to_equity": _s(key_stats.get("debtToEquity")),
|
| 665 |
+
"current_ratio": _s(fin_data.get("currentRatio")),
|
| 666 |
+
"fcf_margin": None,
|
| 667 |
+
"revenue_growth_3y_cagr": _s(fin_data.get("revenueGrowth")),
|
| 668 |
+
"pe_ttm": _s(summary_det.get("trailingPE")),
|
| 669 |
+
"ev_ebitda": _s(key_stats.get("enterpriseToEbitda")),
|
| 670 |
+
}
|
| 671 |
+
except Exception:
|
| 672 |
+
return None
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
def fetch_valuation(ticker: str) -> Dict:
|
| 676 |
+
try:
|
| 677 |
+
import yahooquery as yq
|
| 678 |
+
t = yq.Ticker(ticker)
|
| 679 |
+
key_stats = t.key_stats.get(ticker, {})
|
| 680 |
+
summary_det = t.summary_detail.get(ticker, {})
|
| 681 |
+
fin_data = t.financial_data.get(ticker, {})
|
| 682 |
+
return {
|
| 683 |
+
"pe_ttm": _s(summary_det.get("trailingPE")),
|
| 684 |
+
"pb": _s(key_stats.get("priceToBook")),
|
| 685 |
+
"ps": _s(key_stats.get("priceToSalesTrailing12Months")),
|
| 686 |
+
"ev_ebitda": _s(key_stats.get("enterpriseToEbitda")),
|
| 687 |
+
"ev_revenue": _s(key_stats.get("enterpriseToRevenue")),
|
| 688 |
+
"fcf_yield": None,
|
| 689 |
+
"dividend_yield": _s(summary_det.get("dividendYield")),
|
| 690 |
+
}
|
| 691 |
+
except Exception:
|
| 692 |
+
return {}
|
| 693 |
+
|
| 694 |
+
def _scrape_edgar_10k(ticker: str, log_fn=None) -> str:
|
| 695 |
+
"""Fetch the latest 10-K for a US company from SEC EDGAR and extract a chunk of text."""
|
| 696 |
+
headers = {"User-Agent": "FinancialAnalyzer/1.0 (contact@example.com)"}
|
| 697 |
+
try:
|
| 698 |
+
if log_fn: log_fn(f" -> Looking up SEC CIK for {ticker}...")
|
| 699 |
+
r = requests.get("https://www.sec.gov/files/company_tickers.json", headers=headers, timeout=10)
|
| 700 |
+
tickers = r.json()
|
| 701 |
+
cik = None
|
| 702 |
+
for k, v in tickers.items():
|
| 703 |
+
if v["ticker"].upper() == ticker.upper():
|
| 704 |
+
cik = str(v["cik_str"]).zfill(10)
|
| 705 |
+
break
|
| 706 |
+
|
| 707 |
+
if not cik:
|
| 708 |
+
if log_fn: log_fn(" [ERR] CIK not found in SEC database.")
|
| 709 |
+
return ""
|
| 710 |
+
|
| 711 |
+
if log_fn: log_fn(f" -> Found CIK {cik}. Fetching recent filings...")
|
| 712 |
+
sub_r = requests.get(f"https://data.sec.gov/submissions/CIK{cik}.json", headers=headers, timeout=10)
|
| 713 |
+
data = sub_r.json()
|
| 714 |
+
filings = data.get("filings", {}).get("recent", {})
|
| 715 |
+
|
| 716 |
+
form_types = filings.get("form", [])
|
| 717 |
+
accessions = filings.get("accessionNumber", [])
|
| 718 |
+
primary_docs = filings.get("primaryDocument", [])
|
| 719 |
+
|
| 720 |
+
idx = -1
|
| 721 |
+
for i, form in enumerate(form_types):
|
| 722 |
+
if form == "10-K":
|
| 723 |
+
idx = i
|
| 724 |
+
break
|
| 725 |
+
|
| 726 |
+
if idx == -1:
|
| 727 |
+
if log_fn: log_fn(" [ERR] No 10-K found in recent filings.")
|
| 728 |
+
return ""
|
| 729 |
+
|
| 730 |
+
acc_num = accessions[idx]
|
| 731 |
+
acc_num_no_dash = acc_num.replace("-", "")
|
| 732 |
+
doc = primary_docs[idx]
|
| 733 |
+
|
| 734 |
+
url = f"https://www.sec.gov/Archives/edgar/data/{int(cik)}/{acc_num_no_dash}/{doc}"
|
| 735 |
+
if log_fn: log_fn(f" -> Downloading 10-K from {url}...")
|
| 736 |
+
|
| 737 |
+
doc_r = requests.get(url, headers=headers, timeout=20)
|
| 738 |
+
from bs4 import BeautifulSoup
|
| 739 |
+
soup = BeautifulSoup(doc_r.content, "lxml")
|
| 740 |
+
|
| 741 |
+
text = soup.get_text(separator="\n", strip=True)
|
| 742 |
+
import re
|
| 743 |
+
match = re.search(r'(?i)Item\s+7\.\s*Management[β\']s\s+Discussion', text)
|
| 744 |
+
if match:
|
| 745 |
+
start = match.start()
|
| 746 |
+
extract = text[start:start+40000]
|
| 747 |
+
else:
|
| 748 |
+
extract = text[len(text)//4 : len(text)//4 + 40000]
|
| 749 |
+
|
| 750 |
+
if log_fn: log_fn(" [OK] 10-K text extracted successfully.")
|
| 751 |
+
return extract
|
| 752 |
+
except Exception as e:
|
| 753 |
+
if log_fn: log_fn(f" [ERR] Failed to scrape EDGAR: {str(e)[:80]}")
|
| 754 |
+
return ""
|
| 755 |
+
|
| 756 |
+
|
| 757 |
+
# ββ Main Fetcher ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 758 |
+
|
| 759 |
+
def fetch_all(meta: CompanyMeta, years: int = DEFAULT_YEARS,
|
| 760 |
+
force_refresh: bool = False, log_fn=None) -> Dict:
|
| 761 |
+
def log(m):
|
| 762 |
+
if log_fn: log_fn(m)
|
| 763 |
+
|
| 764 |
+
if not meta.is_listed:
|
| 765 |
+
msg = (f"'{meta.name}' is unlisted/private. Public data not available. "
|
| 766 |
+
"Try the exact BSE/NSE ticker.")
|
| 767 |
+
log(f" β {msg}")
|
| 768 |
+
return {"warnings": [msg], "years": [], "income_statement": {},
|
| 769 |
+
"balance_sheet": {}, "cash_flow": {}}
|
| 770 |
+
|
| 771 |
+
ticker = meta.ticker
|
| 772 |
+
cache_key = f"full_{years}yr"
|
| 773 |
+
if not force_refresh:
|
| 774 |
+
cached = get_cached(ticker, cache_key)
|
| 775 |
+
if cached:
|
| 776 |
+
log(f" [OK] Loaded cached data for {ticker}")
|
| 777 |
+
return cached
|
| 778 |
+
|
| 779 |
+
warnings = []
|
| 780 |
+
result = None
|
| 781 |
+
|
| 782 |
+
# Re-prioritized Fetching Logic:
|
| 783 |
+
|
| 784 |
+
# 1. Indian Stocks: Try screener.in first (up to 10+ years of data)
|
| 785 |
+
if meta.currency == "INR":
|
| 786 |
+
log(" -> Indian Stock detected. Prioritizing screener.in ...")
|
| 787 |
+
scraped = _scrape_screener(ticker, log_fn)
|
| 788 |
+
if scraped:
|
| 789 |
+
result = _normalise_screener(scraped, years)
|
| 790 |
+
warnings.append("Data sourced from screener.in. Verify against company filings.")
|
| 791 |
+
|
| 792 |
+
# Fallback to yfinance if screener fails or yields nothing
|
| 793 |
+
if not result or not result.get("years"):
|
| 794 |
+
log(" -> screener.in failed. Falling back to yahooquery ...")
|
| 795 |
+
result = _fetch_yahooquery(ticker, years, log_fn)
|
| 796 |
+
if result and len(result.get("years", [])) < years:
|
| 797 |
+
warnings.append(f"yahooquery only provides {len(result['years'])} years of historical data.")
|
| 798 |
+
|
| 799 |
+
# 2. Global/US Stocks
|
| 800 |
+
else:
|
| 801 |
+
# If requesting > 4 years, try stockanalysis.com first because yahooquery limits to 4 years
|
| 802 |
+
if years > 4:
|
| 803 |
+
log(" -> Horizon > 4 years requested. Prioritizing stockanalysis.com for global stock ...")
|
| 804 |
+
result = _scrape_stockanalysis(ticker, years, log_fn)
|
| 805 |
+
if result:
|
| 806 |
+
warnings.append("Data sourced from stockanalysis.com. Verify against company filings.")
|
| 807 |
+
|
| 808 |
+
# Fallback to yahooquery
|
| 809 |
+
if not result or not result.get("years"):
|
| 810 |
+
log(" -> Trying yahooquery ...")
|
| 811 |
+
result = _fetch_yahooquery(ticker, years, log_fn)
|
| 812 |
+
if result and len(result.get("years", [])) < years:
|
| 813 |
+
warnings.append(f"yahooquery only provides {len(result['years'])} years of historical data.")
|
| 814 |
+
|
| 815 |
+
# Fallback to FMP
|
| 816 |
+
if (not result or not result.get("years")) and FMP_API_KEY:
|
| 817 |
+
result = _fetch_fmp(ticker, years, log_fn)
|
| 818 |
+
|
| 819 |
+
# 3. Final validation
|
| 820 |
+
if not result or not result.get("years"):
|
| 821 |
+
msg = (f"Could not fetch data for '{meta.name}' ({ticker}). "
|
| 822 |
+
"Check ticker, or the company may have limited public data coverage.")
|
| 823 |
+
log(f" β {msg}")
|
| 824 |
+
return {"warnings": [msg], "years": [], "income_statement": {},
|
| 825 |
+
"balance_sheet": {}, "cash_flow": {}}
|
| 826 |
+
|
| 827 |
+
# 4. Optional Annual Report Scrape (for context)
|
| 828 |
+
if meta.currency != "INR":
|
| 829 |
+
ar_context = _scrape_edgar_10k(ticker, log_fn)
|
| 830 |
+
if ar_context:
|
| 831 |
+
result["annual_report_context"] = ar_context
|
| 832 |
+
warnings.append("AI analysis enhanced with raw MD&A excerpts from SEC EDGAR 10-K.")
|
| 833 |
+
|
| 834 |
+
result["warnings"] = warnings
|
| 835 |
+
result.setdefault("currency", meta.currency)
|
| 836 |
+
set_cache(ticker, cache_key, result)
|
| 837 |
+
log(" [OK] Data cached for 7 days")
|
| 838 |
+
return result
|