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())