import twstock
from twstock import BestFourPoint
import pandas as pd

def analyze_stock_full(stock_id):
    """完整分析（含基本面和國際局勢）"""
    
    print(f"\n{'='*70}")
    print(f"  {stock_id} 完整投資分析報告")
    print(f"{'='*70}\n")
    
    stock = twstock.Stock(stock_id)
    
    # ============================================
    # 一、技術面分析
    # ============================================
    print("📊 一、技術面分析")
    print("-" * 50)
    
    prices = stock.price[-30:]
    dates = stock.date[-30:]
    
    # 均線
    ma5 = stock.moving_average(prices, 5)
    ma20 = stock.moving_average(prices, 20)
    
    # 技術指標
    rsi = calc_RSI(prices)
    k, d = calc_KD(stock.high[-30:], stock.low[-30:], prices)
    macd, signal, hist = calc_MACD(prices)
    
    # 即時資訊
    rt = twstock.realtime.get(stock_id)
    current_price = float(rt['realtime']['latest_trade_price'])
    
    print(f"  現價：{current_price:.2f}")
    print(f"  5日均價：{ma5[-1]:.2f}")
    print(f"  20日均價：{ma20[-1]:.2f}")
    print(f"  RSI(14)：{rsi:.2f}")
    print(f"  KD：K={k:.2f}, D={d:.2f}")
    print(f"  MACD：{macd:.2f}")
    
    # 技術面評分
    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"\n  技術面評分：{tech_score}/100")
    
    # ============================================
    # 二、基本面分析（假設值，實際應從API取得）
    # ============================================
    print("\n💰 二、基本面分析")
    print("-" * 50)
    
    # 這些值應該從公開資訊觀測站取得
    # 目前用假設值
    fundamental_data = {
        '2313': {'eps': 5.51, 'pe': 44.4, 'pb': 1.8, 'roe': 12.5, 'revenue_growth': -5.2},
        '3714': {'eps': -0.2, 'pe': None, 'pb': 0.9, 'roe': -2.1, 'revenue_growth': -15.3}
    }
    
    if stock_id in fundamental_data:
        data = fundamental_data[stock_id]
        print(f"  EPS（每股盈餘）：{data['eps']:.2f} 元")
        if data['pe']:
            print(f"  本益比（P/E）：{data['pe']:.1f} 倍")
        else:
            print(f"  本益比（P/E）：虧損（無意義）")
        print(f"  股價淨值比（P/B）：{data['pb']:.1f} 倍")
        print(f"  股東權益報酬率（ROE）：{data['roe']:.1f}%")
        print(f"  營收成長率：{data['revenue_growth']:.1f}%")
    
    # 基本面評分
    fund_score = 50
    if stock_id in fundamental_data:
        data = fundamental_data[stock_id]
        if data['eps'] > 0:
            fund_score += 15
        if data['pe'] and data['pe'] < 20:
            fund_score += 10
        if data['roe'] > 15:
            fund_score += 10
        if data['revenue_growth'] > 10:
            fund_score += 10
    
    print(f"\n  基本面評分：{fund_score}/100")
    
    # ============================================
    # 三、產業面分析
    # ============================================
    print("\n🏭 三、產業面分析")
    print("-" * 50)
    
    industry_data = {
        '2313': {'industry': 'PCB', 'trend': 'AI + 低軌衛星', 'outlook': '成長'},
        '3714': {'industry': 'LED', 'trend': 'Micro LED', 'outlook': '轉機'}
    }
    
    if stock_id in industry_data:
        data = industry_data[stock_id]
        print(f"  產業：{data['industry']}")
        print(f"  主要題材：{data['trend']}")
        print(f"  產業展望：{data['outlook']}")
    
    # 產業面評分
    ind_score = 50
    if stock_id in industry_data:
        if industry_data[stock_id]['outlook'] == '成長':
            ind_score += 20
        elif industry_data[stock_id]['outlook'] == '轉機':
            ind_score += 10
    
    print(f"\n  產業面評分：{ind_score}/100")
    
    # ============================================
    # 四、國際局勢分析
    # ============================================
    print("\n🌍 四、國際局勢分析")
    print("-" * 50)
    print("  美國市場：道瓊逼近5萬點，費半強勢")
    print("  台美關稅：降至15%，出口利多")
    print("  產業趨勢：AI 伺服器持續成長")
    
    intl_score = 65  # 國際面中性偏多
    print(f"\n  國際面評分：{intl_score}/100")
    
    # ============================================
    # 五、綜合評分與建議
    # ============================================
    print("\n🎯 五、綜合評分與建議")
    print("-" * 50)
    
    total_score = (
        tech_score * 0.3 +
        fund_score * 0.3 +
        ind_score * 0.2 +
        intl_score * 0.2
    )
    
    print(f"  技術面（30%）：{tech_score}分")
    print(f"  基本面（30%）：{fund_score}分")
    print(f"  產業面（20%）：{ind_score}分")
    print(f"  國際面（20%）：{intl_score}分")
    print(f"  ──────────────────────")
    print(f"  綜合評分：{total_score:.1f}分")
    
    # 操作建議
    print(f"\n💡 操作建議：")
    if total_score >= 70:
        print("  ✅ 建議：買進")
        print(f"  📍 買進價位：{current_price:.2f}")
        print(f"  🎯 目標價位：{current_price * 1.15:.2f}（+15%）")
        print(f"  🛑 停損價位：{current_price * 0.9:.2f}（-10%）")
        print(f"  📊 風險報酬比：1:1.5")
    elif total_score >= 50:
        print("  ⚠️ 建議：觀望")
        print(f"  📍 買進條件：站回 {ma5[-1]:.2f} 之上")
        print(f"  📍 觀望區間：{ma20[-1]:.2f} - {ma5[-1]:.2f}")
    else:
        print("  ❌ 建議：賣出/空手")
        print(f"  📍 賣出條件：跌破 {current_price * 0.95:.2f}")
        print(f"  🛑 停損價位：{current_price * 0.9:.2f}")
    
    # 風險提醒
    print(f"\n⚠️ 風險提醒：")
    print(f"  1. 以上分析僅供參考，投資有風險")
    print(f"  2. 建議分批進場，控制倉位在20%以內")
    print(f"  3. 設定停損，保護資本")
    
    print(f"\n{'='*70}\n")

def calc_RSI(prices, period=14):
    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):
    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):
    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()
    return macd.iloc[-1], signal_line.iloc[-1], (macd - signal_line).iloc[-1]

if __name__ == "__main__":
    analyze_stock_full('2313')
    analyze_stock_full('3714')
