Spaces:
Sleeping
Sleeping
File size: 38,587 Bytes
8c085f5 046fcfe 86f67c9 8c085f5 86f67c9 9b2ea10 93ac31f dd5d980 86f67c9 8c085f5 d4de14e 1d2414a 8c085f5 86f67c9 da22ddb 1411904 da22ddb bd87807 1411904 bd87807 1411904 06bce79 1411904 bd87807 1411904 da22ddb 1411904 8e9b019 1411904 8e9b019 da22ddb 8c085f5 1411904 bd87807 8c085f5 b1a801d 8c085f5 b1a801d 8c085f5 25e73ac 8c085f5 b1a801d 25e73ac 8c085f5 046fcfe 8c085f5 25e73ac 8c085f5 9b2ea10 8c085f5 25e73ac 8c085f5 25e73ac 8c085f5 25e73ac 8c085f5 1d2414a 8c085f5 dd5d980 8c085f5 b1a801d c90b031 8c085f5 9b2ea10 1d2414a 9b2ea10 dd5d980 9b2ea10 d4de14e 9b2ea10 93ac31f dd5d980 93ac31f dd5d980 93ac31f dd5d980 93ac31f dd5d980 93ac31f dd5d980 93ac31f 9b2ea10 c90b031 9b2ea10 c90b031 9b2ea10 c90b031 93ac31f 9b2ea10 c90b031 dd5d980 c90b031 93ac31f c90b031 dd5d980 93ac31f dd5d980 c90b031 1d2414a c90b031 93ac31f c90b031 93ac31f 9b2ea10 93ac31f 9b2ea10 c90b031 9b2ea10 c90b031 9b2ea10 93ac31f 9b2ea10 93ac31f 9b2ea10 dd5d980 93ac31f dd5d980 9b2ea10 8c085f5 9b2ea10 8c085f5 9b2ea10 8c085f5 da22ddb 8c085f5 d4de14e 8c085f5 da22ddb 8c085f5 69caad1 8c085f5 b1a801d 8c085f5 b1a801d c90b031 8c085f5 86f67c9 8c085f5 69caad1 8c085f5 b1a801d c90b031 8c085f5 86f67c9 8c085f5 69caad1 | 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 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 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 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 | """
λμ€λ₯ & λ΄μμ¦κΆκ±°λμ μ£Όμ λ°μ΄ν° μμ§ λ° νκΉ
νμ΄μ€ λ°μ΄ν°μ
μμ±
- μμ§: λμ€λ₯/λ΄μ μ 체 ν°μ»€λ₯Ό μΌν νμ΄λΈμ€λ‘ μΌλ³ λ°μ΄ν° μ‘°ν (μ 체기κ°)
- λ°μ΄ν°μ
μμ±: all λ°μ΄ν°μ
+ μ΅κ·Ό 30μΌ λ°μ΄ν°μ
μλ μμ±
"""
import gradio as gr
import yfinance as yf
import pandas as pd
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
from datasets import Dataset, load_dataset
from huggingface_hub import HfApi
import os
import time
import logging
import json
import traceback
import gc
import tempfile
import uuid
from urllib.request import Request, urlopen
# λ‘κΉ
μ€μ
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logging.getLogger("yfinance").setLevel(logging.ERROR)
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("httpcore").setLevel(logging.WARNING)
# νκΉ
νμ΄μ€ ν ν° (Spaces μν¬λ¦Ώμμ κ°μ Έμ΄)
HF_TOKEN = os.environ.get("HF_TOKEN", "")
def get_ny_today_str():
"""λ΄μ νμ§ λ μ§(YYYY-MM-DD) λ°ν"""
ny_tz = ZoneInfo("America/New_York")
return datetime.now(ny_tz).strftime("%Y-%m-%d")
def is_us_market_open_now():
"""λ―Έκ΅ μ κ·μ₯(λ΄μμκ° 09:30~16:00) μ₯μ€ μ¬λΆ λ°ν"""
ny_tz = ZoneInfo("America/New_York")
now_ny = datetime.now(ny_tz)
# μ(0)~κΈ(4)λ§ μ κ·μ₯
if now_ny.weekday() >= 5:
return False, now_ny
minutes = now_ny.hour * 60 + now_ny.minute
market_open = 9 * 60 + 30
market_close = 16 * 60
return market_open <= minutes < market_close, now_ny
def fetch_tradingview_realtime(tickers, batch_size=400):
"""TradingView Screener APIλ‘ ν°μ»€λ³ μ€λ OHLCV μ‘°ν"""
if not tickers:
return []
results = {}
today_str = get_ny_today_str()
for i in range(0, len(tickers), batch_size):
batch = tickers[i:i + batch_size]
payload = {
"symbols": {
"tickers": [
*[f"NASDAQ:{t}" for t in batch],
*[f"NYSE:{t}" for t in batch],
*[f"AMEX:{t}" for t in batch],
]
},
"columns": ["close", "open", "high", "low", "volume", "exchange"],
"options": {"lang": "en"},
"markets": ["america"],
"range": [0, max(50, len(batch) * 3)]
}
req = Request(
"https://scanner.tradingview.com/america/scan",
data=json.dumps(payload).encode("utf-8"),
headers={
"Content-Type": "application/json",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
},
method="POST"
)
with urlopen(req, timeout=30) as resp:
body = resp.read().decode("utf-8")
parsed = json.loads(body)
for item in parsed.get("data", []):
symbol = item.get("s", "")
if ":" not in symbol:
continue
_, ticker = symbol.split(":", 1)
if ticker in results:
continue
data = item.get("d", [])
if len(data) < 5:
continue
close_val, open_val, high_val, low_val, volume_val = data[:5]
if close_val is None:
continue
results[ticker] = {
"Ticker": ticker,
"Date": today_str,
"Open": round(float(open_val), 4) if open_val is not None else None,
"High": round(float(high_val), 4) if high_val is not None else None,
"Low": round(float(low_val), 4) if low_val is not None else None,
"Close": round(float(close_val), 4) if close_val is not None else None,
"Volume": int(volume_val) if volume_val is not None else None
}
time.sleep(0.2)
return list(results.values())
def load_hf_dataset_as_df(repo_name, hf_token):
"""HF Hub λ°μ΄ν°μ
μ pandas DataFrameμΌλ‘ λ‘λ"""
ds = load_dataset(repo_name, split="train", token=hf_token)
df = ds.to_pandas()
# μ»¬λΌ νμ€ν
required_cols = ["Ticker", "Date", "Open", "High", "Low", "Close", "Volume"]
for col in required_cols:
if col not in df.columns:
df[col] = None
df = df[required_cols]
df["Ticker"] = df["Ticker"].astype(str).str.upper()
df["Date"] = df["Date"].astype(str)
return df
def run_realtime_update(
hf_token,
all_dataset_name,
recent_dataset_name,
progress=gr.Progress()
):
"""
μ€μκ°(μ₯μ€) λ°μ΄ν° μ
λ°μ΄νΈ
- μ₯μ€ μ¬λΆ λ©μμ§ μΆλ ₯(μΈλ¨Ένμ μλ λ°μ)
- TradingView Screenerλ‘ λ°μ΄ν°μ
ν°μ»€ μΌκ΄ μ‘°ν
- all: μ€λ λ°μ΄ν° μΆκ°(append-only)
- 30d: μ€λλ λ°μ΄ν° μ κ±° ν μ€λ λ°μ΄ν° λ°μ
"""
if not hf_token:
return "β νκΉ
νμ΄μ€ ν ν°μ΄ νμν©λλ€. HF_TOKEN νκ²½λ³μ λλ μ
λ ₯μ°½μ ν ν°μ λ£μ΄μ£ΌμΈμ."
logs = []
logs.append("=" * 60)
logs.append("β‘ μ€μκ° λ°μ΄ν° μ
λ°μ΄νΈ μμ")
logs.append(f"β° μμ μκ°: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
logs.append("=" * 60)
# 0) μ₯μ€ μν νμΈ (DST μλ λ°μ)
progress(0.05, desc="μ₯μ€ μ¬λΆ νμΈ μ€...")
is_open, now_ny = is_us_market_open_now()
if is_open:
logs.append(f"π’ μ₯μ€μ
λλ€. (λ΄μμκ° {now_ny.strftime('%Y-%m-%d %H:%M:%S')})")
else:
logs.append(f"π‘ μ₯μ€μ΄ μλλλ€. (λ΄μμκ° {now_ny.strftime('%Y-%m-%d %H:%M:%S')})")
today_str = get_ny_today_str()
# 1) λ°μ΄ν°μ
λ‘λ
progress(0.15, desc="κΈ°μ‘΄ λ°μ΄ν°μ
λ‘λ μ€...")
logs.append("\nπ₯ [1λ¨κ³] κΈ°μ‘΄ λ°μ΄ν°μ
λ‘λ μ€...")
all_df = load_hf_dataset_as_df(all_dataset_name, hf_token)
recent_df = load_hf_dataset_as_df(recent_dataset_name, hf_token)
# μ‘°ν ν°μ»€λ λ°μ΄ν°μ
μ μλ ν°μ»€ κΈ°μ€
tickers = sorted(recent_df["Ticker"].dropna().astype(str).str.upper().unique().tolist())
if not tickers:
tickers = sorted(all_df["Ticker"].dropna().astype(str).str.upper().unique().tolist())
if not tickers:
return "\n".join(logs) + "\n\nβ λ°μ΄ν°μ
μ ν°μ»€κ° μμ΄ μ€μκ° μ‘°νλ₯Ό μ§νν μ μμ΅λλ€."
logs.append(f" - μ‘°ν λμ ν°μ»€ μ: {len(tickers)}")
# 2) μ€λ λ°μ΄ν° μ΄λ―Έ μλμ§ νμΈ
progress(0.25, desc="μ€λ λ°μ΄ν° μ‘΄μ¬ μ¬λΆ νμΈ μ€...")
today_rows = all_df[all_df["Date"] == today_str]
today_tickers = set(today_rows["Ticker"].astype(str).str.upper().tolist())
if set(tickers).issubset(today_tickers):
logs.append("\nβ
μ΄λ―Έ μμ§νμ΅λλ€")
return "\n".join(logs)
# 3) TradingView μ€μκ° μ‘°ν
progress(0.45, desc="TradingView μ€μκ° μ‘°ν μ€...")
logs.append("\nπ‘ [2λ¨κ³] TradingView Screener μ‘°ν μ€...")
realtime_rows = fetch_tradingview_realtime(tickers)
if not realtime_rows:
return "\n".join(logs) + "\n\nβ TradingViewμμ μ€μκ° λ°μ΄ν°λ₯Ό κ°μ Έμ€μ§ λͺ»νμ΅λλ€."
realtime_df = pd.DataFrame(realtime_rows)
realtime_df["Ticker"] = realtime_df["Ticker"].astype(str).str.upper()
realtime_df["Date"] = realtime_df["Date"].astype(str)
logs.append(f" - μμ μ±κ³΅ ν°μ»€ μ: {realtime_df['Ticker'].nunique()}")
# 4) all λ°μ΄ν°μ
μ
λ°μ΄νΈ (μΆκ°λ§)
progress(0.65, desc="all λ°μ΄ν°μ
μ
λ°μ΄νΈ μ€...")
logs.append("\nπ§© [3λ¨κ³] all λ°μ΄ν°μ
μ
λ°μ΄νΈ(μΆκ°λ§)...")
existing_today = set(all_df.loc[all_df["Date"] == today_str, "Ticker"].astype(str).str.upper().tolist())
add_all_df = realtime_df[~realtime_df["Ticker"].isin(existing_today)].copy()
if not add_all_df.empty:
all_updated_df = pd.concat([all_df, add_all_df], ignore_index=True)
else:
all_updated_df = all_df
logs.append(f" - all μΆκ° 건μ: {len(add_all_df)}")
# 5) 30d λ°μ΄ν°μ
μ
λ°μ΄νΈ (μ€λλ λ μ§ μ κ±° + μΆκ°/κ°±μ )
progress(0.78, desc="30d λ°μ΄ν°μ
μ
λ°μ΄νΈ μ€...")
logs.append("\nποΈ [4λ¨κ³] 30d λ°μ΄ν°μ
μ
λ°μ΄νΈ(μ€λλ λ°μ΄ν° μ κ±° + μΆκ°)...")
# κ°μ ν°μ»€/μ€λ λ μ§κ° κΈ°μ‘΄μ μμΌλ©΄ κ΅μ²΄λ₯Ό μν΄ μ κ±°
update_tickers = set(realtime_df["Ticker"].tolist())
recent_df_wo_today = recent_df[
~((recent_df["Date"] == today_str) & (recent_df["Ticker"].isin(update_tickers)))
].copy()
recent_merged = pd.concat([recent_df_wo_today, realtime_df], ignore_index=True)
recent_updated_df = filter_last_30_days(recent_merged)
# 6) μ
λ‘λ
progress(0.9, desc="νκΉ
νμ΄μ€ μ
λ‘λ μ€...")
logs.append("\nπ [5λ¨κ³] νκΉ
νμ΄μ€ μ
λ‘λ μ€...")
result_all = upload_dataset_to_hf(all_updated_df, all_dataset_name, hf_token)
result_30d = upload_dataset_to_hf(recent_updated_df, recent_dataset_name, hf_token)
logs.append(f" {result_all}")
logs.append(f" {result_30d}")
progress(1.0, desc="μλ£!")
logs.append("\n" + "=" * 60)
logs.append("β
μ€μκ° λ°μ΄ν° μ
λ°μ΄νΈ μλ£")
logs.append(f"π
λ°μ λ μ§(λ΄μ κΈ°μ€): {today_str}")
logs.append("=" * 60)
return "\n".join(logs)
def get_all_us_tickers():
"""
μΌν νμ΄λΈμ€ μ€ν¬λ¦¬λ(yf.screen)λ₯Ό μ¬μ©νμ¬ λμ€λ₯ + λ΄μμ¦κΆκ±°λμ ν°μ»€ λͺ©λ‘μ κ°μ Έμ΄.
- λμ€λ₯μ 3κ° λ§μΌμΌλ‘ ꡬμ±: NMS(κΈλ‘λ²μ
λ νΈ), NGM(κΈλ‘λ²λ§μΌ), NCM(μΊνΌνΈλ§μΌ)
- λ΄μμ¦κΆκ±°λμ: NYQ
- yfinance λ΄μ₯ κΈ°λ₯μ΄λΌ λ³λ λ°μ΄ν° μμ€ λΆνμ, HF Spacesμμλ λμ
λ°ν: (nasdaq_tickers, nyse_tickers, all_tickers)
"""
def _fetch_exchange_tickers(exchange_code):
"""μΌν μ€ν¬λ¦¬λμμ νΉμ κ±°λμμ μ 체 ν°μ»€λ₯Ό νμ΄μ§μΌλ‘ κ°μ Έμ€κΈ°"""
query = yf.EquityQuery("eq", ["exchange", exchange_code])
symbols = []
offset = 0
while True:
result = yf.screen(query, size=250, offset=offset)
quotes = result.get("quotes", [])
if not quotes:
break
for quote in quotes:
sym = quote.get("symbol", "")
if sym:
# [νν°]
# 1. '-', '.', '$'κ° ν¬ν¨λ ν°μ»€ (μ°μ μ£Ό, μ λ λ±) μ μΈ
# 2. ν°μ»€κ° 5μμ΄λ©΄μ λ§μ§λ§μ΄ W(Warrant), R(Right), U(Unit)μΈ νμ μ’
λͺ© μ μΈ
is_special = any(c in sym for c in ["-", ".", "$"])
is_derivative = len(sym) == 5 and sym[-1] in ["W", "R", "U"]
if not (is_special or is_derivative):
symbols.append(sym)
offset += len(quotes)
total = result.get("total", 0)
if offset >= total:
break
return sorted(list(set(symbols)))
try:
# λμ€λ₯: 3κ° λ§μΌ ν©μ°
# NMS = NASDAQ Global Select Market
# NGM = NASDAQ Global Market
# NCM = NASDAQ Capital Market
nasdaq_tickers = []
for market_code in ["NMS", "NGM", "NCM"]:
tickers = _fetch_exchange_tickers(market_code)
logger.info(f" λμ€λ₯ {market_code}: {len(tickers)}κ° λ‘λ")
nasdaq_tickers.extend(tickers)
nasdaq_tickers = sorted(list(set(nasdaq_tickers)))
# λ΄μμ¦κΆκ±°λμ(NYSE): NYQ
nyse_tickers = _fetch_exchange_tickers("NYQ")
logger.info(f" λ΄μ NYQ: {len(nyse_tickers)}κ° λ‘λ")
all_tickers = sorted(list(set(nasdaq_tickers + nyse_tickers)))
logger.info(f"λμ€λ₯: {len(nasdaq_tickers)}κ°, λ΄μ: {len(nyse_tickers)}κ°, μ 체: {len(all_tickers)}κ° λ‘λ μλ£")
return nasdaq_tickers, nyse_tickers, all_tickers
except Exception as e:
logger.error(f"μΌν μ€ν¬λ¦¬λ ν°μ»€ λ‘λ μ€ν¨: {e}")
return [], [], []
def fetch_ticker_data(ticker, period="max", max_retries=3):
"""
κ°λ³ ν°μ»€μ κΈ°κ°λ³ μΌλ³ λ°μ΄ν°λ₯Ό μΌν νμ΄λΈμ€μμ μ‘°ν
- period: yfinance history κΈ°κ° νλΌλ―Έν° (μ: max, 10y, 5y, 1y, 6mo, 3mo)
- interval="1d" : μΌλ³ λ°μ΄ν°
"""
def _parse_valid_periods(error_message):
marker = "must be one of:"
if marker not in error_message:
return []
raw = error_message.split(marker, 1)[1]
return [p.strip().strip("'").strip('"') for p in raw.split(",") if p.strip()]
def _choose_fallback_period(requested_period, valid_periods):
if not valid_periods:
return None
preferred_order = ["max", "10y", "5y", "2y", "1y", "6mo", "3mo", "1mo", "5d", "1d"]
for candidate in preferred_order:
if candidate in valid_periods:
return candidate
if requested_period in valid_periods:
return requested_period
return valid_periods[0]
effective_period = period
for attempt in range(max_retries):
try:
stock = yf.Ticker(ticker)
# κΈ°κ°λ³, μΌλ³ λ°μ΄ν° μ‘°ν
hist = stock.history(period=effective_period, interval="1d")
if hist.empty:
logger.warning(f"[{ticker}] λ°μ΄ν° μμ (λΉ κ²°κ³Ό)")
return None
# μΈλ±μ€(λ μ§)λ₯Ό 컬λΌμΌλ‘ λ³ν
hist = hist.reset_index()
# ticker μ»¬λΌ μΆκ° (λμ€μ ν°μ»€λ³ ꡬλΆμ©)
hist["Ticker"] = ticker
# λ μ§ μ»¬λΌμ λ¬Έμμ΄λ‘ λ³ν (λ°μ΄ν°μ
νΈνμ±)
if "Date" in hist.columns:
hist["Date"] = hist["Date"].dt.strftime("%Y-%m-%d")
elif "Datetime" in hist.columns:
hist.rename(columns={"Datetime": "Date"}, inplace=True)
hist["Date"] = pd.to_datetime(hist["Date"]).dt.strftime("%Y-%m-%d")
# νμν 컬λΌλ§ μ ν
columns_to_keep = ["Ticker", "Date", "Open", "High", "Low", "Close", "Volume"]
available_cols = [c for c in columns_to_keep if c in hist.columns]
hist = hist[available_cols]
# μ«μ μ»¬λΌ μμμ μ 리
numeric_cols = ["Open", "High", "Low", "Close"]
for col in numeric_cols:
if col in hist.columns:
hist[col] = hist[col].round(4)
# --- μ₯μ€ λ°μ΄ν°(λ―Ένμ μ’
κ°) μ μΈ λ‘μ§ ---
# zoneinfoλ Python λ΄μ₯μ΄λΌ λ³λ μ€μΉ λΆνμ, μΈλ¨Ένμ(EDT/EST) μλ μ²λ¦¬
ny_tz = ZoneInfo("America/New_York")
now_ny = datetime.now(ny_tz)
today_ny = now_ny.strftime("%Y-%m-%d")
# μ κ·μ₯ λ§κ°: λ΄μ νμ§ μκ° 16:00 (μΈλ¨Ένμμ΄λ μλλ λμΌ)
# μ¬μ λ₯Ό λκ³ 16:30 μ΄νλ©΄ μ’
κ° νμ μΌλ‘ νλ¨
market_closed = now_ny.hour >= 17 or (now_ny.hour == 16 and now_ny.minute >= 30)
if not hist.empty and hist.iloc[-1]["Date"] == today_ny:
if not market_closed:
# μμ§ μ₯μ€μ΄κ±°λ λ§κ° μ§ν β μ€λ λ°μ΄ν° μ μΈ (μ’
κ° λ―Ένμ )
logger.info(f"[{ticker}] μ₯μ€ λ°μ΄ν°({today_ny}) μ μΈ (νμ¬ λ΄μμκ°: {now_ny.strftime('%H:%M')})")
hist = hist.iloc[:-1]
else:
# μ₯ λ§κ° ν β μ€λ μ’
κ° νμ , ν¬ν¨
logger.info(f"[{ticker}] μ₯ λ§κ° ν λ°μ΄ν°({today_ny}) ν¬ν¨")
# -----------------------------------------------
return hist
except Exception as e:
error_message = str(e)
if "must be one of:" in error_message:
valid_periods = _parse_valid_periods(error_message)
fallback_period = _choose_fallback_period(effective_period, valid_periods)
if fallback_period and fallback_period != effective_period:
logger.info(
f"[{ticker}] period '{effective_period}' λ―Έμ§μ, '{fallback_period}'λ‘ μλ μ ν ν μ¬μλ"
)
effective_period = fallback_period
continue
logger.warning(f"[{ticker}] μ‘°ν μ€ν¨ (μλ {attempt + 1}/{max_retries}): {e}")
if attempt < max_retries - 1:
time.sleep(1) # μ¬μλ μ λκΈ°
continue
return None
def filter_last_30_days(df):
"""μ 체 λ°μ΄ν°μμ ν°μ»€λ³ μ΅κ·Ό 30μΌ λ°μ΄ν°λ§ νν°λ§"""
if df.empty:
return df
df_copy = df.copy()
df_copy["_date_parsed"] = pd.to_datetime(df_copy["Date"], errors="coerce")
invalid_date_count = int(df_copy["_date_parsed"].isna().sum())
if invalid_date_count > 0:
logger.warning(f"Date νμ± μ€ν¨ ν {invalid_date_count}κ°λ 30μΌ νν°μμ μ μΈλ©λλ€.")
df_copy = df_copy[df_copy["_date_parsed"].notna()].copy()
if df_copy.empty:
return pd.DataFrame(columns=df.columns)
max_date_by_ticker = df_copy.groupby("Ticker")["_date_parsed"].transform("max")
cutoff_by_ticker = max_date_by_ticker - pd.Timedelta(days=30)
result = df_copy[df_copy["_date_parsed"] >= cutoff_by_ticker].copy()
if result.empty:
return pd.DataFrame(columns=df.columns)
result = result.reset_index(drop=True)
result.drop(columns=["_date_parsed"], inplace=True)
return result
def upload_dataset_to_hf(df, repo_name, hf_token, max_retries=3, retry_wait_sec=2):
"""λ°μ΄ν°νλ μμ νκΉ
νμ΄μ€ λ°μ΄ν°μ
μΌλ‘ μ
λ‘λ(μ¬μλ/μ§λ¨ μ 보 ν¬ν¨)"""
if df is None or df.empty:
return {
"ok": False,
"repo": repo_name,
"rows": 0,
"attempts": 0,
"elapsed_sec": 0.0,
"error": "μ
λ‘λν λ°μ΄ν°κ° μμ΅λλ€.",
"traceback": "",
}
last_error = ""
last_traceback = ""
start_ts = time.time()
for attempt in range(1, max_retries + 1):
try:
dataset = Dataset.from_pandas(df, preserve_index=False)
dataset.push_to_hub(
repo_name,
token=hf_token,
private=False # κ³΅κ° λ°μ΄ν°μ
)
return {
"ok": True,
"repo": repo_name,
"rows": len(df),
"attempts": attempt,
"elapsed_sec": time.time() - start_ts,
"error": "",
"traceback": "",
}
except Exception as e:
last_error = str(e)
last_traceback = traceback.format_exc()
logger.warning(f"[{repo_name}] μ
λ‘λ μ€ν¨ (μλ {attempt}/{max_retries}): {last_error}")
if attempt < max_retries:
time.sleep(retry_wait_sec * attempt)
return {
"ok": False,
"repo": repo_name,
"rows": len(df),
"attempts": max_retries,
"elapsed_sec": time.time() - start_ts,
"error": last_error,
"traceback": last_traceback,
}
def append_parquet_chunk_to_hf(df, repo_name, hf_token, subdir="data/chunks", max_retries=3, retry_wait_sec=2):
"""λ°μ΄ν°νλ μμ Parquet μ²ν¬ νμΌλ‘ νκΉ
νμ΄μ€ λ°μ΄ν°μ
μ μ₯μμ μΆκ° μ
λ‘λ"""
if df is None or df.empty:
return {
"ok": False,
"repo": repo_name,
"rows": 0,
"attempts": 0,
"elapsed_sec": 0.0,
"error": "μ
λ‘λν λ°μ΄ν°κ° μμ΅λλ€.",
"traceback": "",
}
api = HfApi()
last_error = ""
last_traceback = ""
start_ts = time.time()
for attempt in range(1, max_retries + 1):
temp_path = None
try:
api.create_repo(
repo_id=repo_name,
repo_type="dataset",
token=hf_token,
private=False,
exist_ok=True,
)
chunk_name = f"chunk-{datetime.now().strftime('%Y%m%d-%H%M%S')}-{uuid.uuid4().hex[:8]}.parquet"
with tempfile.NamedTemporaryFile(suffix=".parquet", delete=False) as tmp:
temp_path = tmp.name
df.to_parquet(temp_path, index=False)
path_in_repo = f"{subdir}/{chunk_name}"
api.upload_file(
path_or_fileobj=temp_path,
path_in_repo=path_in_repo,
repo_id=repo_name,
repo_type="dataset",
token=hf_token,
)
return {
"ok": True,
"repo": repo_name,
"rows": len(df),
"attempts": attempt,
"elapsed_sec": time.time() - start_ts,
"error": "",
"traceback": "",
}
except Exception as e:
last_error = str(e)
last_traceback = traceback.format_exc()
logger.warning(f"[{repo_name}] μ²ν¬ μ
λ‘λ μ€ν¨ (μλ {attempt}/{max_retries}): {last_error}")
if attempt < max_retries:
time.sleep(retry_wait_sec * attempt)
finally:
if temp_path and os.path.exists(temp_path):
try:
os.remove(temp_path)
except Exception:
pass
return {
"ok": False,
"repo": repo_name,
"rows": len(df),
"attempts": max_retries,
"elapsed_sec": time.time() - start_ts,
"error": last_error,
"traceback": last_traceback,
}
def run_pipeline(
hf_token,
all_dataset_name,
recent_dataset_name,
batch_size,
period,
checkpoint_batch_size,
progress=gr.Progress()
):
"""
μ 체 νμ΄νλΌμΈ μ€ν
1. λμ€λ₯ & λ΄μ ν°μ»€ λͺ©λ‘ κ°μ Έμ€κΈ°
2. ν°μ»€λ³ μΌν νμ΄λΈμ€ μΌλ³ λ°μ΄ν° μμ§
3. μ μ²΄κΈ°κ° λ°μ΄ν°μ
(all) μμ±
4. μ΅κ·Ό 30μΌ λ°μ΄ν°μ
μμ±
"""
if not hf_token:
return "β νκΉ
νμ΄μ€ ν ν°μ΄ νμν©λλ€. HF_TOKEN νκ²½λ³μ λλ μ
λ ₯μ°½μ ν ν°μ λ£μ΄μ£ΌμΈμ."
logs = []
try:
def _df_stats(df, label):
if df is None or df.empty:
return f"{label}: 0ν"
mem_mb = df.memory_usage(deep=True).sum() / (1024 * 1024)
return f"{label}: {len(df)}ν x {len(df.columns)}μ΄, λ©λͺ¨λ¦¬ μ½ {mem_mb:.2f}MB"
def _append_upload_result(log_prefix, result):
status_icon = "β
" if result["ok"] else "β"
logs.append(
f" - {log_prefix}: {status_icon} {result['repo']} | "
f"rows={result['rows']} | attempts={result['attempts']} | elapsed={result['elapsed_sec']:.1f}s"
)
if not result["ok"]:
logs.append(f" μ€λ₯: {result['error']}")
if result["traceback"]:
logs.append(" Traceback:")
logs.append(result["traceback"])
logs.append("=" * 60)
logs.append("π μ£Όμ λ°μ΄ν° μμ§ νμ΄νλΌμΈ μμ")
logs.append(f"β° μμ μκ°: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
logs.append("=" * 60)
logs.append("βΉοΈ λ©λͺ¨λ¦¬ μ μ½ λͺ¨λ: 100κ° λ¨μ λ± μ²ν¬ μ
λ‘λ ν λ²νΌλ₯Ό μ¦μ λΉμλλ€.")
# ========== 1λ¨κ³: ν°μ»€ λͺ©λ‘ μμ§ ==========
progress(0, desc="λμ€λ₯ & λ΄μ ν°μ»€ λͺ©λ‘ μμ§ μ€...")
logs.append("\nπ [1λ¨κ³] λμ€λ₯ & λ΄μμ¦κΆκ±°λμ ν°μ»€ λͺ©λ‘ μμ§ μ€...")
nasdaq_tickers, nyse_tickers, all_tickers = get_all_us_tickers()
logs.append(f" - λμ€λ₯: {len(nasdaq_tickers)}κ°")
logs.append(f" - λ΄μμ¦κΆκ±°λμ: {len(nyse_tickers)}κ°")
logs.append(f" - μ 체: {len(all_tickers)}κ°")
if not all_tickers:
logs.append("\nβ οΈ Yahoo Screenerμμ ν°μ»€λ₯Ό κ°μ Έμ€μ§ λͺ»νμ΅λλ€. HF λ°μ΄ν°μ
κΈ°λ° ν΄λ°±μ μλν©λλ€.")
fallback_tickers = []
fallback_errors = []
try:
recent_df = load_hf_dataset_as_df(recent_dataset_name, hf_token)
fallback_tickers = sorted(
recent_df["Ticker"].dropna().astype(str).str.upper().unique().tolist()
)
if fallback_tickers:
logs.append(f" - ν΄λ°± μμ€: recent λ°μ΄ν°μ
({recent_dataset_name})")
except Exception as e:
fallback_errors.append(f"recent λ‘λ μ€ν¨: {e}")
if not fallback_tickers:
try:
all_existing_df = load_hf_dataset_as_df(all_dataset_name, hf_token)
fallback_tickers = sorted(
all_existing_df["Ticker"].dropna().astype(str).str.upper().unique().tolist()
)
if fallback_tickers:
logs.append(f" - ν΄λ°± μμ€: all λ°μ΄ν°μ
({all_dataset_name})")
except Exception as e:
fallback_errors.append(f"all λ‘λ μ€ν¨: {e}")
if fallback_tickers:
all_tickers = fallback_tickers
logs.append(f" - ν΄λ°± ν°μ»€ μ: {len(all_tickers)}κ°")
else:
if fallback_errors:
logs.append(" - ν΄λ°± μ€ν¨ μμΈ:")
for err in fallback_errors:
logs.append(f" * {err}")
logs.append("\nκ°λ₯ν μμΈ:")
logs.append(" 1) Yahoo Screener μΌμ μ₯μ /μ°¨λ¨")
logs.append(" 2) λ€νΈμν¬/μ§μ μ ν")
logs.append(" 3) yfinance API λ³κ²½")
return "\n".join(logs) + "\n\nβ ν°μ»€ λͺ©λ‘μ κ°μ Έμ¬ μ μμ΅λλ€."
# ========== 2λ¨κ³: κΈ°μ‘΄ λ°μ΄ν°μ
λ‘λ + μ¬κ° λμ κ³μ° ==========
progress(0.08, desc="κΈ°μ‘΄ λ°μ΄ν°μ
λ‘λ μ€...")
logs.append("\nπ [2λ¨κ³] κΈ°μ‘΄ λ°μ΄ν°μ
λ‘λ λ° μ¬κ° λμ κ³μ°...")
recent_for_resume = pd.DataFrame(columns=["Ticker"])
try:
recent_for_resume = load_hf_dataset_as_df(recent_dataset_name, hf_token)
logs.append(f" - κΈ°μ‘΄ 30d λ°μ΄ν°: {len(recent_for_resume)}ν")
except Exception as e:
logs.append(f" - κΈ°μ‘΄ 30d λ°μ΄ν° λ‘λ μ€ν¨(μ κ· μμ§ κΈ°μ€μΌλ‘ μ§ν): {e}")
existing_tickers = set(recent_for_resume["Ticker"].dropna().astype(str).str.upper().tolist())
if not existing_tickers:
logs.append(" - κΈ°μ‘΄ ν°μ»€ μ λ³΄κ° λΉμ΄ μμ΄ μ 체 λμ κΈ°μ€μΌλ‘ μ§νν©λλ€.")
pending_tickers = [ticker for ticker in all_tickers if ticker not in existing_tickers]
logs.append(f" - κΈ°μ‘΄ μμ§ ν°μ»€: {len(existing_tickers)}κ°")
logs.append(f" - μ΄λ² μ€ν λμ ν°μ»€: {len(pending_tickers)}κ°")
if not pending_tickers:
progress(1.0, desc="μλ£!")
logs.append("\nβ
μ΄λ―Έ μμ§λ ν°μ»€μ
λλ€. μΆκ° μμ§ν λμμ΄ μμ΅λλ€.")
return "\n".join(logs)
# ========== 3λ¨κ³: μΌν νμ΄λΈμ€ λ°μ΄ν° μμ§ ==========
logs.append(f"\nπ₯ [3λ¨κ³] μΌν νμ΄λΈμ€ λ°μ΄ν° μμ§ μμ (μ΄ {len(pending_tickers)}κ° ν°μ»€)")
logs.append(f" - λ°°μΉ ν¬κΈ°: {batch_size}")
logs.append(f" - μ‘°ν κΈ°κ°(period): {period}")
logs.append(f" - 체ν¬ν¬μΈνΈ μ
λ‘λ κ°κ²©: {checkpoint_batch_size}κ° ν°μ»€")
logs.append(f" β οΈ λ°λ³΅λ¬Έμ΄λΌ μ€λ 걸립λλ€. μ 체 ν°μ»€ μμ λ°λΌ μ μκ° μμλ μ μμ΅λλ€.")
all_data_frames = []
recent_30d_frames = []
success_count = 0
fail_count = 0
last_checkpoint_success_index = 0
total = len(pending_tickers)
def _upload_checkpoint(end_index):
nonlocal last_checkpoint_success_index
if success_count <= last_checkpoint_success_index:
return
logs.append(
f"\nπΎ [체ν¬ν¬μΈνΈ] {end_index}/{total} μ²λ¦¬ μμ μ€κ° μ
λ‘λ μμ "
f"(λμ μ±κ³΅ {success_count}κ°)"
)
if not all_data_frames:
return
checkpoint_all_df = pd.concat(all_data_frames, ignore_index=True)
checkpoint_recent_df = pd.concat(recent_30d_frames, ignore_index=True)
logs.append(f" - {_df_stats(checkpoint_all_df, 'all μ²ν¬')}")
logs.append(f" - {_df_stats(checkpoint_recent_df, '30d μ²ν¬')}")
result_all_ckpt = append_parquet_chunk_to_hf(
checkpoint_all_df,
all_dataset_name,
hf_token,
subdir="data/chunks/all"
)
result_30d_ckpt = append_parquet_chunk_to_hf(
checkpoint_recent_df,
recent_dataset_name,
hf_token,
subdir="data/chunks/30d"
)
_append_upload_result("all 체ν¬ν¬μΈνΈ", result_all_ckpt)
_append_upload_result("30d 체ν¬ν¬μΈνΈ", result_30d_ckpt)
if not result_all_ckpt["ok"] or not result_30d_ckpt["ok"]:
raise RuntimeError("체ν¬ν¬μΈνΈ μ
λ‘λ μ€ν¨λ‘ νμ΄νλΌμΈμ μ€λ¨ν©λλ€.")
all_data_frames.clear()
recent_30d_frames.clear()
gc.collect()
last_checkpoint_success_index = success_count
for i, ticker in enumerate(pending_tickers):
# μ§νλ₯ μ
λ°μ΄νΈ
progress_pct = 0.1 + ((i + 1) / total) * 0.75
progress(progress_pct, desc=f"μμ§ μ€: {ticker} ({i + 1}/{total})")
ticker_df = fetch_ticker_data(ticker, period=period)
if ticker_df is not None and not ticker_df.empty:
all_data_frames.append(ticker_df)
recent_30d_frames.append(filter_last_30_days(ticker_df))
success_count += 1
else:
fail_count += 1
# λ°°μΉ λ¨μλ‘ λ‘κ·Έ μΆλ ₯
if (i + 1) % batch_size == 0 or (i + 1) == total:
logs.append(f" μ§ν: {i + 1}/{total} (μ±κ³΅: {success_count}, μ€ν¨: {fail_count})")
if checkpoint_batch_size > 0 and ((i + 1) % checkpoint_batch_size == 0):
checkpoint_progress = min(0.89, max(progress_pct, 0.82))
progress(checkpoint_progress, desc=f"μ€κ° μ
λ‘λ μ€... ({i + 1}/{total})")
_upload_checkpoint(i + 1)
# API νΈμΆ κ° μ§§μ λκΈ° (μΌν μ°¨λ¨ λ°©μ§)
if (i + 1) % 10 == 0:
time.sleep(0.5)
logs.append(f"\nπ μμ§ μλ£: μ±κ³΅ {success_count}κ° / μ€ν¨ {fail_count}κ°")
if success_count == 0:
return "\n".join(logs) + "\n\nβ μμ§λ λ°μ΄ν°κ° μμ΅λλ€."
# ========== 4λ¨κ³: λ§μ§λ§ λ―Έλ°μ 체ν¬ν¬μΈνΈ λ°μ ==========
progress(0.9, desc="λ§μ§λ§ 체ν¬ν¬μΈνΈ λ°μ μ€...")
logs.append("\nπ§ [4λ¨κ³] λ§μ§λ§ λ―Έλ°μ λ°μ΄ν° λ°μ μ€...")
if success_count > last_checkpoint_success_index:
logs.append("\nπΎ [μ΅μ’
λ°μ] μ€κ° μ
λ‘λ μμ΄ λμ λ λ°μ΄ν° λ°μ")
_upload_checkpoint(total)
progress(0.97, desc="μ²ν¬ μ
λ‘λ μν λ§λ¬΄λ¦¬ μ€...")
logs.append("\nπ [5λ¨κ³] μ²ν¬ μ
λ‘λ λͺ¨λ μλ£")
logs.append(" - all/30d λͺ¨λ μ²ν¬ νμΌ κΈ°μ€μΌλ‘ μ μ₯λμμ΅λλ€.")
logs.append(" - λ€μ μ€ν μ 30d ν°μ»€ λͺ©λ‘ κΈ°μ€μΌλ‘ μλ μ€ν΅/μ¬κ°λ©λλ€.")
# ========== μλ£ ==========
progress(1.0, desc="μλ£!")
logs.append("\n" + "=" * 60)
logs.append(f"β
νμ΄νλΌμΈ μλ£!")
logs.append(f"β° μ’
λ£ μκ°: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
logs.append("=" * 60)
return "\n".join(logs)
except Exception as e:
logger.exception("run_pipeline μ€ν μ€ μμΈ λ°μ")
logs.append("\n" + "=" * 60)
logs.append("β νμ΄νλΌμΈ μ€ν μ€ μμΈκ° λ°μνμ΅λλ€.")
logs.append(f"μ€λ₯ λ©μμ§: {e}")
logs.append("\n[Traceback]")
logs.append(traceback.format_exc())
logs.append("=" * 60)
return "\n".join(logs)
def preview_tickers():
"""ν°μ»€ λͺ©λ‘ 미리보기 (μμ§ μ νμΈμ©)"""
nasdaq, nyse, combined = get_all_us_tickers()
if not combined:
return """β ν°μ»€ λͺ©λ‘μ κ°μ Έμ€μ§ λͺ»νμ΅λλ€.
κ°λ₯ν μμΈ:
1) Yahoo Screener μΌμ μ₯μ /μ°¨λ¨
2) λ€νΈμν¬/μ§μ μ ν
3) yfinance API λ³κ²½
μ μ ν λ€μ μλνκ±°λ, νμ΄νλΌμΈ μ€ν μ HF λ°μ΄ν°μ
ν΄λ°±μ΄ λμνλμ§ νμΈν΄ μ£ΌμΈμ.
"""
info = f"""π ν°μ»€ λͺ©λ‘ 미리보기
βββββββββββββββββββββ
λμ€λ₯: {len(nasdaq)}κ°
λ΄μμ¦κΆκ±°λμ: {len(nyse)}κ°
μ 체: {len(combined)}κ°
λμ€λ₯ μ 20κ°: {', '.join(nasdaq[:20])}...
λ΄μ μ 20κ°: {', '.join(nyse[:20])}...
"""
return info
# ========== Gradio UI κ΅¬μ± ==========
with gr.Blocks(
title="μ£Όμ λ°μ΄ν°μ
μμ±κΈ°"
) as demo:
gr.Markdown("""
# π λμ€λ₯ & λ΄μμ¦κΆκ±°λμ μ£Όμ λ°μ΄ν°μ
μμ±κΈ°
**μΌν νμ΄λΈμ€μμ μ 체 ν°μ»€μ μΌλ³ λ°μ΄ν°λ₯Ό μμ§νμ¬ νκΉ
νμ΄μ€ λ°μ΄ν°μ
μΌλ‘ μλ μ
λ‘λν©λλ€.**
### νμ΄νλΌμΈ νλ¦
1. π λμ€λ₯ & λ΄μμ¦κΆκ±°λμ μ 체 ν°μ»€ λͺ©λ‘ μμ§
2. π₯ ν°μ»€λ³ μΌν νμ΄λΈμ€ μΌλ³ λ°μ΄ν° μ‘°ν (`period` μ€μ κ°λ₯)
3. π¦ **all λ°μ΄ν°μ
** μμ± (μ μ²΄κΈ°κ° λ°μ΄ν°)
4. ποΈ ν°μ»€λ³ μ΅κ·Ό 30μΌ νν°λ§ β **30μΌ λ°μ΄ν°μ
** μμ±
5. π νκΉ
νμ΄μ€ νλΈμ μ
λ‘λ
> β οΈ μ 체 ν°μ»€λ₯Ό λ°λ³΅ μ‘°ννλ―λ‘ **μ μκ°μ΄ μμ**λ μ μμ΅λλ€.
""")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### βοΈ μ€μ ")
hf_token_input = gr.Textbox(
label="νκΉ
νμ΄μ€ ν ν° (HF_TOKEN)",
value=HF_TOKEN,
type="password",
placeholder="hf_xxxxx...",
info="Spaces μν¬λ¦Ώμ HF_TOKENμ΄ μ€μ λμ΄ μμΌλ©΄ μλμΌλ‘ λΆλ¬μ΅λλ€."
)
all_dataset_input = gr.Textbox(
label="μ μ²΄κΈ°κ° λ°μ΄ν°μ
μ΄λ¦ (all)",
value="younginpiniti/us-stocks-daily-all",
placeholder="username/dataset-name",
info="μ μ²΄κΈ°κ° μΌλ³ λ°μ΄ν°κ° μ μ₯λ νκΉ
νμ΄μ€ λ°μ΄ν°μ
"
)
recent_dataset_input = gr.Textbox(
label="μ΅κ·Ό 30μΌ λ°μ΄ν°μ
μ΄λ¦ (30d)",
value="younginpiniti/us-stocks-daily-30d",
placeholder="username/dataset-name",
info="μ΅κ·Ό 30μΌ μΌλ³ λ°μ΄ν°κ° μ μ₯λ νκΉ
νμ΄μ€ λ°μ΄ν°μ
"
)
batch_size_input = gr.Slider(
label="λ‘κ·Έ μΆλ ₯ λ°°μΉ ν¬κΈ°",
minimum=10,
maximum=500,
value=100,
step=10,
info="λͺ κ° ν°μ»€λ§λ€ λ‘κ·Έλ₯Ό μΆλ ₯ν μ§ μ€μ "
)
period_input = gr.Dropdown(
label="μ‘°ν κΈ°κ° (Yahoo period)",
choices=["max", "10y", "5y", "2y", "1y", "6mo", "3mo", "1mo"],
value="max",
info="μ 체 μμ§ μκ°μ΄ κΈΈλ©΄ 10y/5y λ±μΌλ‘ μ€μ¬ μ€νν μ μμ΅λλ€."
)
checkpoint_batch_input = gr.Dropdown(
label="μ€κ° μ
λ‘λ κ°κ²© (ν°μ»€ μ)",
choices=[0, 50, 100, 200, 500],
value=100,
info="0μ΄λ©΄ μ€κ° μ
λ‘λ μμ΄ λ§μ§λ§μλ§ μ
λ‘λν©λλ€."
)
with gr.Row():
preview_btn = gr.Button("π ν°μ»€ λͺ©λ‘ 미리보기", variant="secondary")
start_btn = gr.Button("π νμ΄νλΌμΈ μμ", variant="primary")
realtime_btn = gr.Button("β‘ μ€μκ° μμ", variant="secondary")
with gr.Column(scale=2):
gr.Markdown("### π μ€ν λ‘κ·Έ")
output_log = gr.Textbox(
label="λ‘κ·Έ μΆλ ₯",
lines=30,
max_lines=50,
interactive=False
)
# μ΄λ²€νΈ μ°κ²°
preview_btn.click(
fn=preview_tickers,
inputs=[],
outputs=[output_log]
)
start_btn.click(
fn=run_pipeline,
inputs=[
hf_token_input,
all_dataset_input,
recent_dataset_input,
batch_size_input,
period_input,
checkpoint_batch_input
],
outputs=[output_log]
)
realtime_btn.click(
fn=run_realtime_update,
inputs=[
hf_token_input,
all_dataset_input,
recent_dataset_input
],
outputs=[output_log]
)
gr.Markdown("""
---
### π λ°μ΄ν°μ
ꡬ쑰
| μ»¬λΌ | μ€λͺ
| μμ |
|------|------|------|
| `Ticker` | μ’
λͺ© ν°μ»€ μ¬λ³Ό | AAPL, MSFT, TSLA |
| `Date` | κ±°λμΌ (YYYY-MM-DD) | 2024-01-15 |
| `Open` | μκ° | 185.3200 |
| `High` | κ³ κ° | 187.0400 |
| `Low` | μ κ° | 184.2100 |
| `Close` | μ’
κ° | 186.0000 |
| `Volume` | κ±°λλ | 45123456 |
> π‘ **ν**: ν°μ»€λ³λ‘ μ μ²λ¦¬ν λλ `Ticker` 컬λΌμΌλ‘ κ·Έλ£Ήννλ©΄ λ©λλ€.
> ```python
> from datasets import load_dataset
> ds = load_dataset("younginpiniti/us-stocks-daily-all")
> df = ds["train"].to_pandas()
> aapl = df[df["Ticker"] == "AAPL"]
> ```
""")
if __name__ == "__main__":
demo.launch(theme=gr.themes.Soft())
|