#===LoadCandidateCSV###  ←★検索用キーワード
"""
asaichi_YYYYMMDD.csv（1 列目 = 証券コード）を読み込み
数値4桁            → 4桁ゼロ埋め（ 925 → 0925 ）
数値3桁＋英字1文字 → 3桁そのまま  （290A）
"""
from pathlib import Path
import re
import pandas as pd

# --- 設定 ------------------------------------------------------------
CSV_DIR = Path(r"E:\Daytrade\output")          # ★フォルダ
CSV_PATTERN = "asaichi_*.csv"                  # ★パターン
CODE_REGEX = re.compile(r"^(\d{1,4})([A-Za-z]?)$")  # 3〜4桁＋英字0〜1
# ---------------------------------------------------------------------

def find_latest_csv(directory: Path, pattern: str) -> Path | None:
    files = list(directory.glob(pattern))
    return max(files, key=lambda p: p.stat().st_mtime) if files else None

def normalize_code(raw: str) -> str | None:
    m = CODE_REGEX.match(raw.strip())
    if not m:
        return None
    num, suffix = m.groups()
    if suffix:                       # 3桁＋英字 ⇒ 3桁で固定
        num = num.zfill(3)
    else:                            # 純数字 ⇒ 4桁ゼロ埋め
        num = num.zfill(4)
    return num + suffix.upper()

def load_codes(csv_path: Path) -> list[str]:
    df = pd.read_csv(csv_path, header=None, usecols=[0], dtype=str)
    return (
        df.iloc[:, 0]
        .map(normalize_code)
        .dropna()
        .tolist()
    )

def main():
    csv_file = find_latest_csv(CSV_DIR, CSV_PATTERN)
    if csv_file is None:
        print(f"{CSV_DIR} に {CSV_PATTERN} が見つかりません。")
        return
    codes = load_codes(csv_file)
    print(f"{csv_file.name} から {len(codes)} 銘柄を読み込みました：")
    print(", ".join(codes))

if __name__ == "__main__":
    main()
#===LoadCandidateCSV###  ←★検索用キーワード（終）
