Spaces:
Sleeping

File size: 2,206 Bytes
c68f3b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
将本地 .day 文件导入 Supabase stock_daily_prices 表
用法: python import_to_supabase.py [数量限制]
"""
import sys
import os
import glob

sys.path.insert(0, os.path.dirname(__file__))

import config
from data_loader import load_day_file
from supabase import create_client


def import_day_files(data_dir: str, limit: int = 10):
    client = create_client(config.SUPABASE_URL, config.SUPABASE_KEY)

    # 收集所有 .day 文件(sh/lday + sz/lday)
    patterns = [
        os.path.join(data_dir, "sh", "lday", "*.day"),
        os.path.join(data_dir, "sz", "lday", "*.day"),
    ]

    all_files = []
    for p in patterns:
        all_files.extend(glob.glob(p))

    all_files = all_files[:limit]
    print(f"共找到文件,取前 {len(all_files)} 个导入")

    total_rows = 0

    for filepath in all_files:
        fname = os.path.basename(filepath)
        code = fname[:-4]  # e.g. sh000001

        df = load_day_file(filepath)
        if df.empty:
            print(f"  {code}: 空文件,跳过")
            continue

        # 转为 Supabase 可插入的 dict 列表
        records = []
        for date, row in df.iterrows():
            records.append({
                "code": code,
                "date": date.strftime("%Y-%m-%d"),
                "open": round(row["open"], 4),
                "high": round(row["high"], 4),
                "low": round(row["low"], 4),
                "close": round(row["close"], 4),
                "amount": round(row["amount"], 2),
                "volume": round(row["volume"], 2),
            })

        # 分批插入(Supabase 单次建议不超过 1000 行)
        batch_size = 500
        for i in range(0, len(records), batch_size):
            batch = records[i:i + batch_size]
            client.table("stock_daily_prices").upsert(
                batch, on_conflict="code,date"
            ).execute()

        total_rows += len(records)
        print(f"  {code}: {len(records)} 行已导入")

    print(f"\n导入完成!共 {total_rows} 行")


if __name__ == "__main__":
    limit = int(sys.argv[1]) if len(sys.argv) > 1 else 10
    data_dir = "D:/new_tdx2/vipdoc"
    import_day_files(data_dir, limit)