import yfinance as yf
import pandas as pd
from pathlib import Path
from datetime import datetime

# =========================
# 設定
# =========================
TICKER = "7012.T"
CODE = "7012"
STOCK_NAME = "7012_川崎重工"

BASE_DIR = Path(r"C:\Users\machi\Market_Radar_7012")
OUT_DIR = BASE_DIR / "04_市場レーダー"
OUT_DIR.mkdir(parents=True, exist_ok=True)

OUT_FILE = OUT_DIR / "7012_川崎重工_morning_radar_log.xlsx"

TIME_WINDOWS = {
    "09:00-09:30": ("09:00", "09:30"),
    "09:30-10:00": ("09:30", "10:00"),
    "10:00-10:30": ("10:00", "10:30"),
    "10:30-11:00": ("10:30", "11:00"),
    "11:00-11:30": ("11:00", "11:30"),

    "13:00-13:30": ("13:00", "13:30"),
    "13:30-14:00": ("13:30", "14:00"),
    "14:00-14:30": ("14:00", "14:30"),
    "14:30-15:00": ("14:30", "15:00"),
    "15:00-15:30": ("15:00", "15:30"),
}

# =========================
# 判定関数
# =========================
def judge_candle(open_price, close_price):
    if close_price > open_price:
        return "陽線"
    elif close_price < open_price:
        return "陰線"
    else:
        return "同値"


def judge_direction(open_price, close_price):
    change_pct = (close_price - open_price) / open_price * 100

    if change_pct >= 1.0:
        return "強い上昇"
    elif change_pct >= 0.2:
        return "上昇寄り"
    elif change_pct <= -1.0:
        return "強い下落"
    elif change_pct <= -0.2:
        return "下落寄り"
    else:
        return "横ばい"


def judge_total(vol_ratio, candle):
    if vol_ratio >= 2.0 and candle == "陽線":
        return "強い買い初動"
    elif vol_ratio >= 1.5 and candle == "陽線":
        return "買い優勢"
    elif vol_ratio >= 1.5 and candle == "陰線":
        return "売り圧力注意"
    elif vol_ratio <= 0.8:
        return "出来高不足"
    else:
        return "通常範囲"


def judge_battle(vol_ratio, candle, direction):
    if vol_ratio >= 2.0 and candle == "陽線" and direction == "強い上昇":
        return "関ヶ原"

    elif 0.8 <= vol_ratio < 1.5 and candle == "陽線" and direction in ["上昇寄り", "強い上昇"]:
        return "桶狭間"

    elif vol_ratio >= 1.5 and candle == "陰線":
        return "敗走"

    elif vol_ratio < 0.8:
        return "休戦"

    else:
        return "膠着"


def judge_weather(battle):
    if battle == "関ヶ原":
        return "快晴"
    elif battle == "桶狭間":
        return "晴れ"
    elif battle == "敗走":
        return "雷雨"
    elif battle == "休戦":
        return "静寂"
    else:
        return "曇り"


def calc_window(df_today, start_time, end_time):
    target = df_today.between_time(start_time, end_time)

    if target.empty:
        return None

    open_price = float(target["Open"].iloc[0])
    high_price = float(target["High"].max())
    low_price = float(target["Low"].min())
    close_price = float(target["Close"].iloc[-1])
    volume = int(target["Volume"].sum())

    candle = judge_candle(open_price, close_price)
    direction = judge_direction(open_price, close_price)

    return {
        "始値": open_price,
        "高値": high_price,
        "安値": low_price,
        "終値": close_price,
        "出来高": volume,
        "ローソク": candle,
        "方向": direction,
    }


# =========================
# メイン処理
# =========================
def main():
    print(f"{STOCK_NAME} 朝レーダー完全版 開始")
    print("=" * 50)

    df = yf.download(
        TICKER,
        period="7d",
        interval="1m",
        auto_adjust=False,
        progress=True
    )

    if df.empty:
        print("データ取得失敗")
        return

    if isinstance(df.columns, pd.MultiIndex):
        df.columns = df.columns.get_level_values(0)

    df = df.dropna()

    if df.index.tz is not None:
        df.index = df.index.tz_convert("Asia/Tokyo").tz_localize(None)

    latest_date = df.index.date.max()
    df_today = df[df.index.date == latest_date]

    records = []

    for label, (start_time, end_time) in TIME_WINDOWS.items():
        result = calc_window(df_today, start_time, end_time)

        if result is None:
            print(f"{label} のデータがありません")
            continue

        past_dates = sorted(set(df.index.date))
        past_dates = [d for d in past_dates if d < latest_date][-5:]

        past_volumes = []

        for d in past_dates:
            df_past = df[df.index.date == d]
            past_window = df_past.between_time(start_time, end_time)

            if not past_window.empty:
                past_volumes.append(int(past_window["Volume"].sum()))

        avg_volume_5d = sum(past_volumes) / len(past_volumes) if past_volumes else 0
        vol_ratio = result["出来高"] / avg_volume_5d if avg_volume_5d > 0 else 0

        total_judge = judge_total(vol_ratio, result["ローソク"])
        battle = judge_battle(vol_ratio, result["ローソク"], result["方向"])
        weather = judge_weather(battle)

        record = {
            "日付": latest_date,
            "銘柄": STOCK_NAME,
            "コード": CODE,
            "時間帯": label,
            "始値": result["始値"],
            "高値": result["高値"],
            "安値": result["安値"],
            "終値": result["終値"],
            "出来高": result["出来高"],
            "過去5日平均出来高": round(avg_volume_5d),
            "出来高倍率": round(vol_ratio, 2),
            "ローソク": result["ローソク"],
            "方向": result["方向"],
            "総合判定": total_judge,
            "戦況": battle,
            "天気": weather,
            "記録日時": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        }

        records.append(record)

        print()
        print("=" * 50)
        print(f"{label} 判定")
        print("=" * 50)
        print(f"日付              : {latest_date}")
        print(f"始値              : {result['始値']}")
        print(f"高値              : {result['高値']}")
        print(f"安値              : {result['安値']}")
        print(f"終値              : {result['終値']}")
        print(f"出来高            : {result['出来高']:,} 株")
        print(f"過去5日平均出来高 : {avg_volume_5d:,.0f} 株")
        print(f"出来高倍率        : {vol_ratio:.2f} 倍")
        print(f"ローソク          : {result['ローソク']}")
        print(f"方向              : {result['方向']}")
        print(f"総合判定          : {total_judge}")
        print(f"戦況              : {battle}")
        print(f"天気              : {weather}")

    if not records:
        print("保存するデータがありません")
        return

    new_df = pd.DataFrame(records)

    if OUT_FILE.exists():
        old_df = pd.read_excel(OUT_FILE)
        all_df = pd.concat([old_df, new_df], ignore_index=True)
        all_df = all_df.drop_duplicates(
            subset=["日付", "コード", "時間帯"],
            keep="last"
        )
    else:
        all_df = new_df

    all_df.to_excel(OUT_FILE, index=False)

    print()
    print("保存完了")
    print(OUT_FILE)


if __name__ == "__main__":
    main()