import twstock
from twstock import BestFourPoint
import pandas as pd
import numpy as np

def calc_RSI(prices, period=14):
    """計算 RSI"""
    delta = pd.Series(prices).diff()
    gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
    loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
    rs = gain / loss
    rsi = 100 - (100 / (1 + rs))
    return rsi.iloc[-1]

def calc_KD(high, low, close, n=9):
    """計算 KD"""
    high = pd.Series(high)
    low = pd.Series(low)
    close = pd.Series(close)
    
    lowest_low = low.rolling(window=n).min()
    highest_high = high.rolling(window=n).max()
    rsv = (close - lowest_low) / (highest_high - lowest_low) * 100
    
    k = rsv.ewm(com=2).mean()
    d = k.ewm(com=2).mean()
    return k.iloc[-1], d.iloc[-1]

def calc_MACD(prices, fast=12, slow=26, signal=9):
    """計算 MACD"""
    prices = pd.Series(prices)
    ema_fast = prices.ewm(span=fast).mean()
    ema_slow = prices.ewm(span=slow).mean()
    macd = ema_fast - ema_slow
    signal_line = macd.ewm(span=signal).mean()
    histogram = macd - signal_line
    return macd.iloc[-1], signal_line.iloc[-1], histogram.iloc[-1]

def calc_Bollinger(prices, period=20, std=2):
    """計算布林通道"""
    prices = pd.Series(prices)
    mid = prices.rolling(window=period).mean()
    upper = mid + std * prices.rolling(window=period).std()
    lower = mid - std * prices.rolling(window=period).std()
    return upper.iloc[-1], mid.iloc[-1], lower.iloc[-1]

def analyze_stock(stock_id):
    """完整股票分析"""
    print(f"\n{'='*60}")
    print(f"  {stock_id} 完整分析報告")
    print(f"{'='*60}\n")
    
    stock = twstock.Stock(stock_id)
    
    # 基本資訊
    print("📊 【技術面分析】")
    print("-" * 40)
    
    # 最近價格
    prices = stock.price[-30:]
    dates = stock.date[-30:]
    
    print("最近5天收盤價：")
    for i in range(-5, 0):
        print(f"  {dates[i].strftime('%m-%d')}: {prices[i]:.2f}")
    
    # 均線
    ma5 = stock.moving_average(prices, 5)
    ma20 = stock.moving_average(prices, 20)
    ma60 = stock.moving_average(prices, 60) if len(prices) >= 60 else None
    
    print(f"\n均線系統：")
    print(f"  5日均價：{ma5[-1]:.2f}")
    print(f"  20日均價：{ma20[-1]:.2f}")
    if ma60:
        print(f"  60日均價：{ma60[-1]:.2f}")
    
    # 技術指標
    rsi = calc_RSI(prices)
    k, d = calc_KD(stock.high[-30:], stock.low[-30:], prices)
    macd, signal, hist = calc_MACD(prices)
    upper, mid, lower = calc_Bollinger(prices)
    
    print(f"\n技術指標：")
    print(f"  RSI(14)：{rsi:.2f}")
    print(f"  KD：K={k:.2f}, D={d:.2f}")
    print(f"  MACD：{macd:.2f}, Signal={signal:.2f}, Hist={hist:.2f}")
    print(f"  布林通道：上={upper:.2f}, 中={mid:.2f}, 下={lower:.2f}")
    
    # 即時資訊
    rt = twstock.realtime.get(stock_id)
    current_price = float(rt['realtime']['latest_trade_price'])
    open_price = float(rt['realtime']['open'])
    change = current_price - open_price
    
    print(f"\n即時資訊：")
    print(f"  現價：{current_price:.2f}")
    print(f"  開盤：{open_price:.2f}")
    print(f"  漲跌：{change:+.2f} ({change/open_price*100:+.2f}%)")
    print(f"  成交量：{rt['realtime']['accumulate_trade_volume']}")
    
    # 四大買賣點
    bfp = BestFourPoint(stock)
    result = bfp.best_four_point()
    print(f"\n四大買賣點：{result[1]}")
    
    # 支撐壓力
    recent_high = max(prices[-20:])
    recent_low = min(prices[-20:])
    
    print(f"\n關鍵價位：")
    print(f"  近期高點：{recent_high:.2f}")
    print(f"  近期低點：{recent_low:.2f}")
    
    # 買賣建議
    print(f"\n💡 【買賣建議】")
    print("-" * 40)
    
    # 技術面評分
    tech_score = 50
    if current_price > ma5[-1]:
        tech_score += 10
    if current_price > ma20[-1]:
        tech_score += 10
    if rsi < 30:
        tech_score += 15
    elif rsi > 70:
        tech_score -= 15
    if k > d:
        tech_score += 10
    if macd > signal:
        tech_score += 10
    
    print(f"技術面評分：{tech_score}/100")
    
    # 操作建議
    if tech_score >= 70:
        print("建議：買進")
        print(f"買進價位：{current_price:.2f}")
        print(f"目標價位：{recent_high:.2f}")
        print(f"停損價位：{recent_low:.2f}")
    elif tech_score <= 30:
        print("建議：賣出")
        print(f"賣出價位：{current_price:.2f}")
        print(f"目標價位：{recent_low:.2f}")
    else:
        print("建議：觀望")
        print(f"買進條件：站回 {ma5[-1]:.2f} 之上")
        print(f"觀望條件：在 {ma20[-1]:.2f} 附近震盪")
    
    # 風險報酬比
    if tech_score >= 70:
        risk = current_price - recent_low
        reward = recent_high - current_price
        rr_ratio = reward / risk if risk > 0 else 0
        print(f"\n風險報酬比：1:{rr_ratio:.1f}")
    
    print(f"\n{'='*60}\n")
    
    return {
        'stock_id': stock_id,
        'current_price': current_price,
        'ma5': ma5[-1],
        'ma20': ma20[-1],
        'rsi': rsi,
        'kd_k': k,
        'kd_d': d,
        'macd': macd,
        'tech_score': tech_score
    }

if __name__ == "__main__":
    # 分析華通
    analyze_stock('2313')
    
    # 分析富采
    analyze_stock('3714')
