"""
简单移动平均线交叉策略示例

策略逻辑：
- 当短期均线(50日)上穿长期均线(200日)时买入
- 当短期均线下穿长期均线时卖出

这是一个经典的趋势跟踪策略，适合学习 Lean 的基本功能。
"""

from AlgorithmImports import *

class SimpleMovingAverageCrossAlgorithm(QCAlgorithm):
    """
    简单移动平均线交叉策略

    属性:
        fast: 快速移动平均线(50日)
        slow: 慢速移动平均线(200日)
        spy: SPY 的 Symbol 对象
    """

    def Initialize(self):
        """
        初始化算法

        设置：
        - 回测时间范围
        - 初始资金
        - 添加证券
        - 创建技术指标
        - 设置预热期
        """
        # ========== 时间和资金设置 ==========
        self.SetStartDate(2018, 1, 1)    # 开始日期
        self.SetEndDate(2023, 12, 31)    # 结束日期
        self.SetCash(100000)             # 初始资金 $100,000

        # ========== 添加证券 ==========
        # 添加 SPY（标普500 ETF）
        # Resolution.Daily 表示使用日线数据
        spy_security = self.AddEquity("SPY", Resolution.Daily)

        # 保存 Symbol 对象供后续使用
        self.spy = spy_security.Symbol

        # ========== 创建技术指标 ==========
        # SMA(简单移动平均线)
        # 参数: Symbol, Period, Resolution
        self.fast = self.SMA(self.spy, 50, Resolution.Daily)   # 快线: 50日
        self.slow = self.SMA(self.spy, 200, Resolution.Daily)  # 慢线: 200日

        # ========== 设置指标预热 ==========
        # 预热200天，这样慢线一开始就有数据
        # 避免等待200天后才开始交易
        self.SetWarmUp(TimeSpan.FromDays(200))

        # ========== 设置 benchmark ==========
        self.SetBenchmark("SPY")

        # ========== 注册指标用于绘图 ==========
        # 这样可以在回测结果中看到均线
        self.PlotIndicator("Strategy", self.fast)
        self.PlotIndicator("Strategy", self.slow)

        # ========== 保存初始资金与订单统计 ==========
        self.starting_cash = self.Portfolio.TotalPortfolioValue
        self.filledOrders = 0

        # ========== 输出初始化信息 ==========
        self.Debug("=" * 50)
        self.Debug("Simple Moving Average Crossover Strategy")
        self.Debug(f"Fast MA: 50 days")
        self.Debug(f"Slow MA: 200 days")
        self.Debug(f"Start Date: {self.StartDate}")
        self.Debug(f"End Date: {self.EndDate}")
        self.Debug(f"Initial Capital: ${self.Portfolio.Cash}")
        self.Debug("=" * 50)

    def OnData(self, data):
        """
        主数据处理函数

        每个新的数据点都会触发此函数。
        在这里实现交易逻辑。
        """
        # 如果数据中没有 SPY，跳过
        if not data.ContainsKey(self.spy) or data[self.spy] is None:
            return

        # 等待指标准备就绪
        # 虽然设置了预热，但这是个好习惯
        if not self.fast.IsReady or not self.slow.IsReady:
            return

        # 获取当前值
        fastValue = self.fast.Current.Value
        slowValue = self.slow.Current.Value
        currentPrice = data[self.spy].Price

        # 获取当前持仓信息
        holdings = self.Portfolio[self.spy]

        # ========== 交易逻辑 ==========

        # 金叉：快线上穿慢线 -> 买入信号
        if fastValue > slowValue and not holdings.IsLong:
            self.SetHoldings(self.spy, 1)  # 使用100%资金买入
            self.Debug(f"[BUY] {self.Time.date()} | "
                      f"Price: ${currentPrice:.2f} | "
                      f"Fast: {fastValue:.2f} | "
                      f"Slow: {slowValue:.2f}")

        # 死叉：快线下穿慢线 -> 卖出信号
        elif fastValue < slowValue and holdings.IsLong:
            self.Liquidate(self.spy)  # 清空持仓
            self.Debug(f"[SELL] {self.Time.date()} | "
                      f"Price: ${currentPrice:.2f} | "
                      f"Fast: {fastValue:.2f} | "
                      f"Slow: {slowValue:.2f}")

        # 绘制价格和指标
        self.Plot("Strategy", "Price", currentPrice)
        self.Plot("Strategy", "Fast MA", fastValue)
        self.Plot("Strategy", "Slow MA", slowValue)

    def OnOrderEvent(self, orderEvent):
        """
        订单事件处理函数

        当订单状态发生变化时触发。
        用于监控订单执行情况。
        """
        # 只处理已成交的订单
        if orderEvent.Status == OrderStatus.Filled:
            self.filledOrders += 1
            self.Debug(f"[ORDER FILLED] {self.Time.date()} | "
                      f"OrderId: {orderEvent.OrderId} | "
                      f"Symbol: {orderEvent.Symbol} | "
                      f"FillQuantity: {orderEvent.FillQuantity} | "
                      f"Price: ${orderEvent.FillPrice:.2f} | "
                      f"Commission: ${orderEvent.OrderFee.Value.Amount:.2f}")

    def OnEndOfDay(self, symbol):
        """
        每日收盘时触发

        用于每日统计和日志记录。
        """
        if symbol == self.spy:
            portfolioValue = self.Portfolio.TotalPortfolioValue
            cash = self.Portfolio.Cash
            holdings = self.Portfolio[self.spy]

            self.Debug(f"[EOD] {self.Time.date()} | "
                      f"Portfolio Value: ${portfolioValue:,.2f} | "
                      f"Cash: ${cash:,.2f} | "
                      f"SPY Holdings: {holdings.Quantity} | "
                      f"Fast MA: {self.fast.Current.Value:.2f} | "
                      f"Slow MA: {self.slow.Current.Value:.2f}")

    def OnEndOfAlgorithm(self):
        """
        算法结束时调用

        用于输出最终的统计信息。
        """
        self.Debug("=" * 50)
        self.Debug("BACKTEST COMPLETED")
        self.Debug(f"Final Portfolio Value: ${self.Portfolio.TotalPortfolioValue:,.2f}")
        self.Debug(f"Total Return: {(self.Portfolio.TotalPortfolioValue / self.starting_cash - 1) * 100:.2f}%")
        self.Debug(f"Total Trades: {self.filledOrders}")
        self.Debug("=" * 50)


# ========== 变体：带止损的移动平均线策略 ==========

class SMAWithStopLossAlgorithm(QCAlgorithm):
    """
    带止损的移动平均线策略

    在基本策略基础上增加了：
    - 追踪止损
    - 固定止损
    """

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

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

        self.fast = self.SMA(self.spy, 50, Resolution.Daily)
        self.slow = self.SMA(self.spy, 200, Resolution.Daily)

        self.SetWarmUp(TimeSpan.FromDays(200))

        # 追踪止损百分比：5%
        self.trailingStopPercent = 0.05
        # 记录入场价格
        self.entryPrice = None
        # 记录最高价
        self.highestPrice = None

    def OnData(self, data):
        if not data.ContainsKey(self.spy) or data[self.spy] is None:
            return

        if not self.fast.IsReady or not self.slow.IsReady:
            return

        fastValue = self.fast.Current.Value
        slowValue = self.slow.Current.Value
        currentPrice = data[self.spy].Price

        holdings = self.Portfolio[self.spy]

        # 金叉买入
        if fastValue > slowValue and not holdings.IsLong:
            self.SetHoldings(self.spy, 1)
            self.entryPrice = currentPrice
            self.highestPrice = currentPrice
            self.Debug(f"[BUY with Stop Loss] {self.Time.date()} | "
                      f"Entry: ${currentPrice:.2f} | "
                      f"Stop: ${currentPrice * (1 - self.trailingStopPercent):.2f}")

        # 已有持仓的情况
        elif holdings.Invested:
            # 更新最高价
            if currentPrice > self.highestPrice:
                self.highestPrice = currentPrice

            # 计算止损价格
            stopLossPrice = self.highestPrice * (1 - self.trailingStopPercent)

            # 检查止损
            if currentPrice < stopLossPrice:
                self.Liquidate(self.spy)
                self.Debug(f"[STOP LOSS TRIGGERED] {self.Time.date()} | "
                          f"Exit: ${currentPrice:.2f} | "
                          f"Highest: ${self.highestPrice:.2f} | "
                          f"Loss: {(currentPrice / self.entryPrice - 1) * 100:.2f}%")
                self.entryPrice = None
                self.highestPrice = None

            # 死叉平仓
            elif fastValue < slowValue:
                self.Liquidate(self.spy)
                self.Debug(f"[EXIT] {self.Time.date()} | "
                          f"Price: ${currentPrice:.2f} | "
                          f"Return: {(currentPrice / self.entryPrice - 1) * 100:.2f}%")
                self.entryPrice = None
                self.highestPrice = None
