"""
技术指标完整示例

本示例演示了 Lean 中各种技术指标的使用：
1. 趋势指标：SMA, EMA, MACD
2. 动量指标：RSI, Stochastic, ROC
3. 波动率指标：ATR, Bollinger Bands
4. 成交量指标：VWAP, OBV
5. 自定义指标
6. 指标预热
7. 多指标组合策略
"""

from AlgorithmImports import *
from datetime import timedelta

# ========== 自定义指标 ==========

class MomentumIndicator(PythonIndicator):
    """
    自定义动量指标

    计算价格相对于 N 期前的变化百分比
    """

    def __init__(self, period):
        super().__init__()
        self.Period = period
        self.Value = 0.0
        self._prices = RollingWindow[float](period)

    @property
    def IsReady(self):
        """指标是否就绪"""
        return self._prices.IsReady

    @property
    def WarmUpPeriod(self):
        """预热期长度"""
        return self.Period

    def Update(self, input):
        """
        更新指标

        Args:
            input: IBaseData 对象
        """
        # 添加新价格
        self._prices.Add(input.Value)

        # 窗口未满
        if not self._prices.IsReady:
            return False

        # 计算动量百分比
        current_price = self._prices[0]                      # 最新价格
        past_price = self._prices[self.Period - 1]           # N 期前价格

        if past_price != 0:
            self.Value = (current_price / past_price - 1) * 100

        return True


class RangeExpansionIndicator(PythonIndicator):
    """
    自定义区间扩张指标

    用于识别价格的突破信号
    """

    def __init__(self, period=20):
        super().__init__()
        self.Period = period
        self.Value = 0.0
        self._highs = RollingWindow[float](period)
        self._lows = RollingWindow[float](period)
        self._is_ready = False

    @property
    def IsReady(self):
        return self._is_ready

    @property
    def WarmUpPeriod(self):
        return self.Period

    def Update(self, input):
        """更新指标"""
        # input 应该是 TradeBar 类型
        if not hasattr(input, 'High') or not hasattr(input, 'Low'):
            return False

        self._highs.Add(input.High)
        self._lows.Add(input.Low)

        if not self._highs.IsReady:
            return False

        self._is_ready = True

        # 计算价格区间位置
        high_range = max(self._highs)
        low_range = min(self._lows)
        range_size = high_range - low_range

        if range_size == 0:
            self.Value = 50  # 中性
        else:
            # 当前价格在区间中的位置 (0-100)
            self.Value = ((input.Value - low_range) / range_size) * 100

        return True


# ========== 主策略类 ==========

class TechnicalIndicatorsDemoAlgorithm(QCAlgorithm):
    """
    技术指标演示策略

    演示各种指标的使用方法
    """

    def Initialize(self):
        """初始化算法"""
        # ========== 基本设置 ==========
        self.SetStartDate(2020, 1, 1)
        self.SetEndDate(2023, 12, 31)
        self.SetCash(100000)

        # 记录初始资金
        # 注意：Portfolio 没有 StartingCash 属性，需要在 Initialize 里自行保存
        self.starting_cash = self.Portfolio.TotalPortfolioValue

        # ========== 添加证券 ==========
        self.spy = self.AddEquity("SPY", Resolution.Daily).Symbol
        self.aapl = self.AddEquity("AAPL", Resolution.Daily).Symbol

        # ========== 趋势指标 ==========

        # 1. 简单移动平均线 (SMA)
        self.sma_20 = self.SMA(self.spy, 20, Resolution.Daily)
        self.sma_50 = self.SMA(self.spy, 50, Resolution.Daily)
        self.sma_200 = self.SMA(self.spy, 200, Resolution.Daily)

        # 2. 指数移动平均线 (EMA)
        self.ema_12 = self.EMA(self.spy, 12, Resolution.Daily)
        self.ema_26 = self.EMA(self.spy, 26, Resolution.Daily)

        # 3. 线性加权移动平均线 (LWMA)
        # 注意：Lean 中的加权移动平均指标名为 LWMA（LinearWeightedMovingAverage），
        # 并没有 WMA 这个辅助方法名
        self.lwma_20 = self.LWMA(self.spy, 20, Resolution.Daily)

        # 4. MACD (12, 26, 9)
        self.macd = self.MACD(
            self.spy,
            12,                                # 快线周期
            26,                                # 慢线周期
            9,                                 # 信号线周期
            MovingAverageType.Exponential
        )

        # ========== 动量指标 ==========

        # 5. RSI (相对强弱指标)
        self.rsi_14 = self.RSI(self.spy, 14, MovingAverageType.Simple)
        self.rsi_7 = self.RSI(self.spy, 7, MovingAverageType.Simple)

        # 6. 随机指标 (Stochastic)
        # 注意：随机指标的辅助方法名为 STO（不是 STOCH），
        # 结果通过 StochK / StochD 属性读取
        self.stoch = self.STO(
            self.spy,
            14,    # K 周期
            3,     # K 平滑
            3,     # D 周期
            Resolution.Daily
        )

        # 7. ROC (变化率)
        self.roc = self.ROC(self.spy, 10, Resolution.Daily)

        # 8. Williams %R
        # 注意：Williams %R 的辅助方法名为 WILR（不是 WILLR）
        self.wilr = self.WILR(self.spy, 14, Resolution.Daily)

        # ========== 波动率指标 ==========

        # 9. ATR (平均真实波幅)
        self.atr_14 = self.ATR(self.spy, 14, MovingAverageType.Simple)
        self.atr_7 = self.ATR(self.spy, 7, MovingAverageType.Simple)

        # 10. 布林带 (Bollinger Bands)
        self.bb_20_2 = self.BB(self.spy, 20, 2, MovingAverageType.Simple)
        self.bb_20_1 = self.BB(self.spy, 20, 1, MovingAverageType.Simple)

        # 11. 标准差
        self.std = self.STD(self.spy, 20, Resolution.Daily)

        # ========== 成交量指标 ==========

        # 12. VWAP (成交量加权平均价)
        self.vwap = self.VWAP(self.spy)

        # 13. OBV (能量潮)
        self.obv = self.OBV(self.spy)

        # 14. MFI (资金流量指数)
        self.mfi = self.MFI(self.spy, 14)

        # ========== 自定义指标 ==========

        # 15. 自定义动量指标
        self.custom_momentum = MomentumIndicator(20)
        self.RegisterIndicator(self.spy, self.custom_momentum, Resolution.Daily)

        # 16. 自定义区间扩张指标
        self.range_expansion = RangeExpansionIndicator(20)
        self.RegisterIndicator(self.spy, self.range_expansion, Resolution.Daily)

        # ========== 指标预热 ==========
        self.SetWarmUp(TimeSpan.FromDays(200))

        # ========== 图表 ==========
        # 说明：PlotIndicator 只接受指标对象（没有"序列名"字符串参数的重载）。
        # 要自定义序列名或绘制常量线，应使用
        # self.Plot(图表名, 序列名, 数值)，本示例在 OnData 中逐 bar 绘制

        # ========== 交易参数 ==========
        self.stop_loss_pct = 0.02      # 2% 止损
        self.take_profit_pct = 0.05    # 5% 止盈

        self.Debug("=" * 60)
        self.Debug("Technical Indicators Demo - Initialized")
        self.Debug("=" * 60)


    def PlotIndicatorValues(self):
        """绘制指标当前值（每个数据点调用一次）"""
        price = self.Securities[self.spy].Price

        # 价格和均线
        self.Plot("Price & MA", "Price", price)
        self.Plot("Price & MA", "SMA20", self.sma_20.Current.Value)
        self.Plot("Price & MA", "SMA50", self.sma_50.Current.Value)
        self.Plot("Price & MA", "EMA12", self.ema_12.Current.Value)

        # RSI
        self.Plot("RSI", "RSI14", self.rsi_14.Current.Value)
        self.Plot("RSI", "Overbought", 70)
        self.Plot("RSI", "Oversold", 30)

        # MACD
        self.Plot("MACD", "MACD", self.macd.Current.Value)
        self.Plot("MACD", "Signal", self.macd.Signal.Current.Value)
        self.Plot("MACD", "Histogram", self.macd.Histogram.Current.Value)

        # 布林带
        self.Plot("Bollinger Bands", "BB Middle", self.bb_20_2.MiddleBand.Current.Value)
        self.Plot("Bollinger Bands", "BB Upper", self.bb_20_2.UpperBand.Current.Value)
        self.Plot("Bollinger Bands", "BB Lower", self.bb_20_2.LowerBand.Current.Value)


    def OnData(self, data):
        """
        主数据处理函数
        """
        # 等待所有指标准备
        if not self.AreIndicatorsReady():
            return

        # 绘制指标当前值
        self.PlotIndicatorValues()

        # 获取当前价格
        current_price = self.Securities[self.spy].Price

        # ========== 交易逻辑：多指标组合 ==========

        # 检查买入条件
        if self.CheckBuySignal(current_price):
            if not self.Portfolio[self.spy].IsLong:
                self.EnterLong(current_price)

        # 检查卖出条件
        elif self.CheckSellSignal(current_price):
            if self.Portfolio[self.spy].IsLong:
                self.ExitLong("Sell Signal")

        # 检查止损止盈
        elif self.Portfolio[self.spy].IsLong:
            self.CheckStopLossTakeProfit(current_price)


    def AreIndicatorsReady(self):
        """检查所有指标是否就绪"""
        indicators = [
            self.sma_20, self.sma_50,
            self.rsi_14, self.macd,
            self.bb_20_2, self.atr_14,
            self.custom_momentum
        ]
        return all(ind.IsReady for ind in indicators)


    def CheckBuySignal(self, price):
        """
        检查买入信号

        条件（全部满足）：
        1. 短期均线上穿长期均线（金叉）
        2. RSI 不超买 (< 70)
        3. 价格在布林带中轨之上
        4. MACD 柱状图为正
        5. ATR 在正常范围
        """
        conditions = {
            'Golden Cross': self.sma_20.Current.Value > self.sma_50.Current.Value,
            'RSI OK': self.rsi_14.Current.Value < 70,
            'Above BB Middle': price > self.bb_20_2.MiddleBand.Current.Value,
            'MACD Positive': self.macd.Histogram.Current.Value > 0,
            'ATR Normal': self.atr_14.Current.Value < price * 0.05  # ATR < 5%
        }

        # 记录信号
        if all(conditions.values()):
            self.Debug(f"[BUY SIGNAL] {self.Time.date()} | Conditions: {conditions}")
            return True

        return False


    def CheckSellSignal(self, price):
        """
        检查卖出信号

        条件（任一满足）：
        1. 短期均线下穿长期均线（死叉）
        2. RSI 超买 (> 75)
        3. 价格跌破布林带下轨
        4. MACD 柱状图为负且死叉
        """
        conditions = {
            'Death Cross': self.sma_20.Current.Value < self.sma_50.Current.Value,
            'RSI Overbought': self.rsi_14.Current.Value > 75,
            'Below BB Lower': price < self.bb_20_2.LowerBand.Current.Value,
            'MACD Death Cross': (self.macd.Histogram.Current.Value < 0 and
                               self.macd.Current.Value < self.macd.Signal.Current.Value)
        }

        for name, triggered in conditions.items():
            if triggered:
                self.Debug(f"[SELL SIGNAL] {self.Time.date()} | Reason: {name}")
                return True

        return False


    def EnterLong(self, price):
        """开多仓"""
        # 使用 80% 资金
        self.SetHoldings(self.spy, 0.8)

        # 记录入场信息
        self.entry_price = price
        self.highest_price = price

        # 输出详细信号
        self.Debug(f"\n{'='*60}")
        self.Debug(f"[ENTER LONG] {self.Time.date()}")
        self.Debug(f"  Entry Price: ${price:.2f}")
        self.Debug(f"  SMA20: {self.sma_20.Current.Value:.2f}")
        self.Debug(f"  SMA50: {self.sma_50.Current.Value:.2f}")
        self.Debug(f"  RSI: {self.rsi_14.Current.Value:.2f}")
        self.Debug(f"  MACD Hist: {self.macd.Histogram.Current.Value:.2f}")
        bb_pos = ((price - self.bb_20_2.LowerBand.Current.Value) /
                  (self.bb_20_2.UpperBand.Current.Value - self.bb_20_2.LowerBand.Current.Value)) * 100
        self.Debug(f"  BB Position: {bb_pos:.1f}%")
        self.Debug(f"{'='*60}\n")


    def ExitLong(self, reason):
        """平多仓"""
        self.Liquidate(self.spy)

        pnl_pct = (self.Securities[self.spy].Price / self.entry_price - 1) * 100

        self.Debug(f"\n{'='*60}")
        self.Debug(f"[EXIT LONG] {self.Time.date()}")
        self.Debug(f"  Reason: {reason}")
        self.Debug(f"  Exit Price: ${self.Securities[self.spy].Price:.2f}")
        self.Debug(f"  P&L: {pnl_pct:.2f}%")
        self.Debug(f"{'='*60}\n")


    def CheckStopLossTakeProfit(self, price):
        """检查止损止盈"""
        # 更新最高价
        if price > self.highest_price:
            self.highest_price = price

        # 计算收益率
        return_pct = (price / self.entry_price - 1) * 100

        # 止损
        if return_pct < -self.stop_loss_pct * 100:
            self.ExitLong(f"Stop Loss ({return_pct:.2f}%)")

        # 止盈
        elif return_pct > self.take_profit_pct * 100:
            self.ExitLong(f"Take Profit ({return_pct:.2f}%)")


    def OnEndOfDay(self, symbol):
        """每日收盘处理"""
        if symbol == self.spy:
            # 输出每日指标摘要
            self.DailyIndicatorSummary()


    def DailyIndicatorSummary(self):
        """输出每日指标摘要"""
        if not self.AreIndicatorsReady():
            return

        price = self.Securities[self.spy].Price
        portfolio = self.Portfolio

        self.Debug(f"\n{'─'*60}")
        self.Debug(f"[DAILY SUMMARY] {self.Time.date()}")
        self.Debug(f"{'─'*60}")

        # 价格信息
        self.Debug(f"Price: ${price:.2f}")

        # 趋势指标
        self.Debug(f"\n[Trend]")
        self.Debug(f"  SMA20: {self.sma_20.Current.Value:.2f}")
        self.Debug(f"  SMA50: {self.sma_50.Current.Value:.2f}")
        self.Debug(f"  SMA200: {self.sma_200.Current.Value:.2f}")
        self.Debug(f"  EMA12: {self.ema_12.Current.Value:.2f}")

        # MACD
        self.Debug(f"\n[Momentum]")
        self.Debug(f"  RSI14: {self.rsi_14.Current.Value:.2f}")
        self.Debug(f"  MACD: {self.macd.Current.Value:.2f}")
        self.Debug(f"  MACD Signal: {self.macd.Signal.Current.Value:.2f}")
        self.Debug(f"  MACD Histogram: {self.macd.Histogram.Current.Value:.2f}")
        self.Debug(f"  Stoch K: {self.stoch.StochK.Value:.2f}")
        self.Debug(f"  Stoch D: {self.stoch.StochD.Current.Value:.2f}")

        # 波动率指标
        self.Debug(f"\n[Volatility]")
        self.Debug(f"  ATR14: {self.atr_14.Current.Value:.2f}")
        self.Debug(f"  ATR%: {(self.atr_14.Current.Value / price * 100):.2f}%")
        self.Debug(f"  BB Upper: {self.bb_20_2.UpperBand.Current.Value:.2f}")
        self.Debug(f"  BB Middle: {self.bb_20_2.MiddleBand.Current.Value:.2f}")
        self.Debug(f"  BB Lower: {self.bb_20_2.LowerBand.Current.Value:.2f}")
        self.Debug(f"  BB Width: {self.bb_20_2.BandWidth.Current.Value:.2f}")

        # 自定义指标
        self.Debug(f"\n[Custom]")
        self.Debug(f"  Momentum (20): {self.custom_momentum.Value:.2f}%")
        self.Debug(f"  Range Expansion: {self.range_expansion.Value:.2f}")

        # 组合信息
        self.Debug(f"\n[Portfolio]")
        self.Debug(f"  Total Value: ${portfolio.TotalPortfolioValue:,.2f}")
        self.Debug(f"  Cash: ${portfolio.Cash:,.2f}")
        if portfolio[self.spy].Invested:
            self.Debug(f"  Position: {portfolio[self.spy].Quantity}")
            self.Debug(f"  Unrealized P&L: ${portfolio[self.spy].UnrealizedProfit:.2f}")

        self.Debug(f"{'─'*60}\n")


    def OnEndOfAlgorithm(self):
        """算法结束"""
        self.Debug("\n" + "="*60)
        self.Debug("BACKTEST COMPLETED")
        self.Debug("="*60)
        self.Debug(f"Final Portfolio Value: ${self.Portfolio.TotalPortfolioValue:,.2f}")
        total_return = (self.Portfolio.TotalPortfolioValue / self.starting_cash - 1) * 100
        self.Debug(f"Total Return: {total_return:.2f}%")
        # 注意：self.Statistics 只有 TotalPerformance / RollingPerformances / Summary 三个成员，
        # 数值指标要从 TotalPerformance.PortfolioStatistics 下取
        stats = self.Statistics.TotalPerformance.PortfolioStatistics
        self.Debug(f"Sharpe Ratio: {stats.SharpeRatio:.2f}")
        self.Debug(f"Max Drawdown: {stats.Drawdown * 100:.2f}%")
        self.Debug(f"Win Rate: {stats.WinRate * 100:.2f}%")
        self.Debug("="*60)


# ========== 简化的多指标策略示例 ==========

class SimpleMultiIndicatorStrategy(QCAlgorithm):
    """
    简化的多指标策略

    只使用最常用的几个指标：MA, RSI, MACD
    """

    def Initialize(self):
        self.SetStartDate(2020, 1, 1)
        self.SetEndDate(2023, 12, 31)
        self.SetCash(100000)

        self.spy = self.AddEquity("SPY", Resolution.Daily).Symbol

        # 只使用三个指标
        self.sma_fast = self.SMA(self.spy, 20)
        self.sma_slow = self.SMA(self.spy, 50)
        self.rsi = self.RSI(self.spy, 14)

        self.SetWarmUp(TimeSpan.FromDays(60))

    def OnData(self, data):
        if not self.sma_fast.IsReady:
            return

        # 简单的信号
        ma_cross = self.sma_fast.Current.Value > self.sma_slow.Current.Value
        rsi_ok = 30 < self.rsi.Current.Value < 70

        if ma_cross and rsi_ok and not self.Portfolio[self.spy].IsLong:
            self.SetHoldings(self.spy, 1)
        elif not ma_cross and self.Portfolio[self.spy].IsLong:
            self.Liquidate(self.spy)
