"""
高级功能完整示例

本示例演示 Lean 的高级功能：
1. 期权策略（Covered Call, Protective Put, Straddle）
2. 期货交易与连续合约
3. 自定义模型（手续费、滑点、填充）
4. 调度事件
"""

from AlgorithmImports import *
from datetime import timedelta, datetime

# ========== 自定义模型 ==========

class TieredFeeModel(FeeModel):
    """
    阶梯式手续费模型

    交易量越大，手续费率越低
    """

    def __init__(self):
        super().__init__()
        self.total_volume = 0
        self.fee_tiers = [
            (0, 100000, 0.001),      # 0.1%
            (100000, 1000000, 0.0005), # 0.05%
            (1000000, float('inf'), 0.0002)  # 0.02%
        ]

    def GetOrderFee(self, parameters):
        """
        计算手续费

        Args:
            parameters: OrderFeeParameters
        Returns:
            OrderFee
        """
        security = parameters.Security
        order = parameters.Order

        # 更新累计交易量
        self.total_volume += abs(order.AbsoluteQuantity)

        # 根据交易量确定手续费率
        fee_rate = 0.001  # 默认 0.1%
        for min_vol, max_vol, rate in self.fee_tiers:
            if min_vol <= self.total_volume < max_vol:
                fee_rate = rate
                break

        # 计算手续费
        fee = order.AbsoluteQuantity * security.Price * fee_rate

        # 最低手续费
        fee = max(fee, 1.0)

        return OrderFee(CashAmount(fee, "USD"))


class VolumeSlippageModel(SlippageModel):
    """
    基于交易量的滑点模型

    订单量占成交量比例越大，滑点越大
    """

    def GetSlippageApproximation(self, security, order):
        """
        计算滑点

        Args:
            security: Security
            order: Order
        Returns:
            float: 滑点率
        """
        # 获取平均成交量
        avg_volume = security.Volume

        if avg_volume == 0:
            return 0

        # 订单量占成交量的比例
        volume_ratio = abs(order.Quantity) / avg_volume

        # 滑点与订单量成正比，最多 0.5%
        slippage_rate = min(volume_ratio * 0.01, 0.005)

        return slippage_rate


class PercentageFeeModel(FeeModel):
    """
    固定百分比手续费模型

    简单的手续费计算方式
    """

    def __init__(self, fee_percentage=0.001):
        super().__init__()
        self.fee_percentage = fee_percentage

    def GetOrderFee(self, parameters):
        """计算手续费"""
        security = parameters.Security
        order = parameters.Order

        fee = abs(order.Quantity) * security.Price * self.fee_percentage

        return OrderFee(CashAmount(max(fee, 1.0), "USD"))


# ========== 期权策略示例 ==========

class CoveredCallStrategy(QCAlgorithm):
    """
    备兑看涨期权策略

    策略：
    1. 持有标的股票（SPY）
    2. 卖出虚值看涨期权获取权利金
    3. 定期滚动期权
    """

    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.spy_option = self.AddOption("SPY", Resolution.Daily).Symbol

        # 设置过滤器：选择30天后到期的虚值看涨期权
        option = self.Securities[self.spy_option]
        option.SetFilter(
            lambda universe: universe
            .CallsOnly()  # 只要看涨期权
            .Expiration(timedelta(days=25), timedelta(days=35))  # 25-35天后到期
            .Strikes(-3, 3)  # 平价上下3档
        )

        self.SetWarmUp(TimeSpan.FromDays(60))

        # 设置自定义手续费
        self.Securities[self.spy].FeeModel = PercentageFeeModel(0.001)

        # 调度：每月检查期权
        self.Schedule.On(
            self.DateRules.MonthStart(),
            self.TimeRules.AfterMarketOpen(self.spy, 30),
            self.CheckAndRollOptions
        )

        self.call_sold = False

    def OnData(self, data):
        """主数据处理"""
        # 如果没有标的持仓，买入
        if not self.Portfolio[self.spy].Invested:
            self.SetHoldings(self.spy, 1)
            self.Debug(f"[Bought SPY] {self.Time.date()}")

    def CheckAndRollOptions(self):
        """检查并滚动期权"""
        # 查看当前的期权持仓
        option_positions = [
            symbol for symbol in self.Portfolio.Keys
            if self.Portfolio[symbol].Invested and
            self.Securities[symbol].Type == SecurityType.Option
        ]

        # 如果没有期权持仓，卖出新的
        if not option_positions and not self.call_sold:
            self.SellNewCall()
        else:
            # 检查是否需要滚动
            for option_symbol in option_positions:
                days_to_expiry = (self.Securities[option_symbol].Expiry - self.Time).days

                # 如果少于7天到期，平仓并卖出新的
                if days_to_expiry < 7:
                    self.Liquidate(option_symbol)
                    self.Debug(f"[Closed Call] {option_symbol} - {days_to_expiry} days to expiry")
                    self.SellNewCall()

    def SellNewCall(self):
        """卖出新的看涨期权"""
        # self.OptionChain 是方法（无 ContainsKey/GetOptionChain），
        # 返回当前期权链，无数据时为空链，先筛出看涨合约再判空
        chain = self.OptionChain(self.spy_option)

        calls = [c for c in chain if c.Right == OptionRight.Call]
        if not calls:
            return

        underlying_price = chain.Underlying.Price

        # 找到虚值约3%的看涨期权
        target_strike = underlying_price * 1.03

        atm_call = min(calls, key=lambda x: abs(x.Strike - target_strike))

        # 卖出1手（100股）
        self.Sell(atm_call.Symbol, 1)
        self.call_sold = True

        self.Debug(f"[Sold Call] {self.Time.date()} | "
                  f"Strike: ${atm_call.Strike:.2f} | "
                  f"Expiry: {atm_call.Expiry.date()} | "
                  f"Premium: ${atm_call.BidPrice:.2f}")

    def OnOrderEvent(self, orderEvent):
        """订单事件"""
        if orderEvent.Status == OrderStatus.Filled:
            if self.Securities[orderEvent.Symbol].Type == SecurityType.Option:
                self.Debug(f"[Option Order] {orderEvent.Symbol} | "
                          f"Qty: {orderEvent.FillQuantity} | "
                          f"Price: ${orderEvent.FillPrice:.2f}")


class ProtectivePutStrategy(QCAlgorithm):
    """
    保护性看跌期权策略

    策略：
    1. 持有标的股票
    2. 买入虚值看跌期权作为保险
    3. 定期滚动期权
    """

    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.spy_option = self.AddOption("SPY", Resolution.Daily).Symbol

        # 选择虚值5%的看跌期权
        option = self.Securities[self.spy_option]
        option.SetFilter(
            lambda universe: universe
            .PutsOnly()
            .Expiration(timedelta(days=25), timedelta(days=35))  # 25-35天后到期
            .Strikes(-5, 5)  # 平价上下5档
        )

        self.SetWarmUp(TimeSpan.FromDays(60))

        self.Schedule.On(
            self.DateRules.MonthStart(),
            self.TimeRules.AfterMarketOpen(self.spy, 30),
            self.CheckAndRollPuts
        )

        self.put_bought = False

    def OnData(self, data):
        if not self.Portfolio[self.spy].Invested:
            self.SetHoldings(self.spy, 1)

    def CheckAndRollPuts(self):
        """检查并滚动看跌期权"""
        put_positions = [
            symbol for symbol in self.Portfolio.Keys
            if self.Portfolio[symbol].Invested and
            self.Securities[symbol].Type == SecurityType.Option
        ]

        if not put_positions and not self.put_bought:
            self.BuyNewPut()
        else:
            for put_symbol in put_positions:
                days_to_expiry = (self.Securities[put_symbol].Expiry - self.Time).days

                if days_to_expiry < 7:
                    self.Liquidate(put_symbol)
                    self.Debug(f"[Closed Put] {put_symbol}")
                    self.BuyNewPut()

    def BuyNewPut(self):
        """买入新的看跌期权"""
        # self.OptionChain 是方法（无 ContainsKey/GetOptionChain），
        # 返回当前期权链，无数据时为空链，先筛出看跌合约再判空
        chain = self.OptionChain(self.spy_option)

        puts = [c for c in chain if c.Right == OptionRight.Put]
        if not puts:
            return

        underlying_price = chain.Underlying.Price
        target_strike = underlying_price * 0.95  # 虚值5%

        otm_put = min(puts, key=lambda x: abs(x.Strike - target_strike))

        # 买入看跌期权（1手保护100股）
        self.Buy(otm_put.Symbol, 1)
        self.put_bought = True

        self.Debug(f"[Bought Put] {self.Time.date()} | "
                  f"Strike: ${otm_put.Strike:.2f} | "
                  f"Premium: ${otm_put.AskPrice:.2f}")


class StraddleStrategy(QCAlgorithm):
    """
    跨式策略

    同时买入相同行权价的看涨和看跌期权
    盈利方向：大幅波动（无论涨跌）
    """

    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.spy_option = self.AddOption("SPY", Resolution.Daily).Symbol

        # 选择平值期权，30天后到期
        option = self.Securities[self.spy_option]
        option.SetFilter(
            lambda universe: universe
            .Expiration(timedelta(days=25), timedelta(days=35))  # 25-35天后到期
            .Strikes(-1, 1)  # 平价上下1档
        )

        self.SetWarmUp(TimeSpan.FromDays(60))
        self.straddle_opened = False

    def OnData(self, data):
        if self.straddle_opened:
            return

        # OnData 里从 data.OptionChains 取链
        # （self.OptionChain 是方法，无 ContainsKey/GetOptionChain）
        if not data.OptionChains.ContainsKey(self.spy_option):
            return

        chain = data.OptionChains[self.spy_option]
        if chain is None:
            return

        # 找到平值期权
        underlying_price = chain.Underlying.Price
        atm_strike = min(chain, key=lambda x: abs(x.Strike - underlying_price)).Strike

        # 买入平值看涨和看跌期权
        for contract in chain:
            if contract.Strike == atm_strike:
                self.Buy(contract.Symbol, 1)

        self.straddle_opened = True

        total_premium = sum(
            self.Securities[contract.Symbol].Holdings.AveragePrice
            for contract in chain
            if contract.Strike == atm_strike
        )

        self.Debug(f"[Straddle Opened] Strike: ${atm_strike:.2f} | "
                  f"Total Premium: ${total_premium:.2f}")


# ========== 期货策略示例 ==========

class FutureRollStrategy(QCAlgorithm):
    """
    期货合约滚动策略

    演示如何处理期货合约的自动滚动
    """

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

        # 添加黄金期货
        self.gc = self.AddFuture("GC", Resolution.Daily).Symbol

        # 设置过滤器：选择前3个月到期的合约
        future = self.Securities[self.gc]
        future.SetFilter(0, 2)

        self.SetWarmUp(TimeSpan.FromDays(30))

        self.current_contract = None
        self.roll_days_before = 5  # 到期前5天滚动

    def OnData(self, data):
        # 处理期货链
        for chain in data.FutureChains:
            if chain.Symbol.Value != "GC":
                continue

            # .Values 是 .NET 属性，不加括号
            contracts = list(chain.Contracts.Values)
            if not contracts:
                continue

            # 按到期日排序
            contracts.sort(key=lambda x: x.Expiry)

            # 选择前端合约（最近月份）
            front_contract = contracts[0]

            # 检查是否需要滚动
            days_to_expiry = (front_contract.Expiry - self.Time).days

            if self.current_contract is None:
                # 首次开仓
                self.SetHoldings(front_contract.Symbol, 1)
                self.current_contract = front_contract.Symbol
                self.Debug(f"[Opened] {front_contract.Symbol} | "
                          f"Expiry: {front_contract.Expiry.date()} | "
                          f"Days to expiry: {days_to_expiry}")

            elif self.current_contract != front_contract.Symbol:
                # 滚动到新合约
                self.Liquidate(self.current_contract)
                self.SetHoldings(front_contract.Symbol, 1)

                old_contract = self.current_contract
                self.current_contract = front_contract.Symbol

                self.Debug(f"[Rolled] {old_contract} -> {front_contract.Symbol} | "
                          f"Days to expiry: {days_to_expiry}")

            elif days_to_expiry <= self.roll_days_before:
                # 到期前滚动到下一个合约
                if len(contracts) > 1:
                    next_contract = contracts[1]
                    self.Liquidate(self.current_contract)
                    self.SetHoldings(next_contract.Symbol, 1)

                    old_contract = self.current_contract
                    self.current_contract = next_contract.Symbol

                    self.Debug(f"[Roll Before Expiry] {old_contract} -> {next_contract.Symbol} | "
                              f"Days to expiry: {days_to_expiry}")


# ========== 综合示例：高级功能演示 ==========

class AdvancedFeaturesDemo(QCAlgorithm):
    """
    高级功能综合演示

    包含：
    1. 自定义模型（手续费、滑点）
    2. 调度事件
    3. 期权交易
    4. 多种订单类型
    """

    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.Securities[self.spy].FeeModel = TieredFeeModel()

        # 使用基于交易量的滑点模型
        self.Securities[self.spy].SetSlippageModel(VolumeSlippageModel())

        # ========== 指标 ==========
        self.sma_short = self.SMA(self.spy, 20, Resolution.Daily)
        self.sma_long = self.SMA(self.spy, 50, Resolution.Daily)
        self.rsi = self.RSI(self.spy, 14, Resolution.Daily)

        self.SetWarmUp(TimeSpan.FromDays(60))

        # ========== 调度事件 ==========
        # 每天开盘后30分钟检查
        self.Schedule.On(
            self.DateRules.EveryDay(self.spy),
            self.TimeRules.AfterMarketOpen(self.spy, 30),
            self.DailyCheck
        )

        # 每周一收盘前检查
        self.Schedule.On(
            self.DateRules.Every(DayOfWeek.Monday),
            self.TimeRules.BeforeMarketClose(self.spy, 30),
            self.WeeklyCheck
        )

        # 每月第一个交易日调仓
        self.Schedule.On(
            self.DateRules.MonthStart(),
            self.TimeRules.AfterMarketOpen(self.spy, 30),
            self.MonthlyRebalance
        )

        # 每15天执行一次
        self.Schedule.On(
            self.DateRules.EveryDay(),
            self.TimeRules.Every(TimeSpan.FromDays(15)),
            self.BiMonthlyAction
        )

        # ========== 自定义变量 ==========
        self.trade_count = 0
        self.last_rebalance = None

        self.Debug("=" * 60)
        self.Debug("Advanced Features Demo - Initialized")
        self.Debug("Custom Models: Tiered Fee, Volume Slippage")
        self.Debug("Scheduled: Daily, Weekly, Monthly, Bi-Monthly")
        self.Debug("=" * 60)

    def DailyCheck(self):
        """每天执行"""
        if not self.sma_short.IsReady:
            return

        price = self.Securities[self.spy].Price
        short_ma = self.sma_short.Current.Value
        long_ma = self.sma_long.Current.Value
        rsi_value = self.rsi.Current.Value

        self.Debug(f"[Daily Check] {self.Time.date()} | "
                  f"Price: ${price:.2f} | "
                  f"SMA20: {short_ma:.2f} | "
                  f"SMA50: {long_ma:.2f} | "
                  f"RSI: {rsi_value:.2f}")

    def WeeklyCheck(self):
        """每周一执行"""
        portfolio_value = self.Portfolio.TotalPortfolioValue
        total_return = (portfolio_value / self.starting_cash - 1) * 100

        self.Debug(f"[Weekly Check] {self.Time.date()} | "
                  f"Portfolio: ${portfolio_value:,.2f} | "
                  f"Return: {total_return:.2f}%")

    def MonthlyRebalance(self):
        """每月第一个交易日调仓"""
        self.Debug(f"[Monthly Rebalance] {self.Time.date()}")

        # 检查是否已经有持仓
        if not self.Portfolio[self.spy].Invested:
            # 检查买入条件
            if self.sma_short.Current.Value > self.sma_long.Current.Value:
                self.SetHoldings(self.spy, 1)
                self.Debug(f"  -> Bought SPY at ${self.Securities[self.spy].Price:.2f}")

        self.last_rebalance = self.Time

    def BiMonthlyAction(self):
        """每15天执行一次"""
        self.Debug(f"[Bi-Monthly Action] {self.Time.date()}")

        # 输出当前持仓信息
        if self.Portfolio[self.spy].Invested:
            holdings = self.Portfolio[self.spy]
            unreal_pnl = holdings.UnrealizedProfit
            unreal_pnl_pct = holdings.UnrealizedProfitPercent * 100

            self.Debug(f"  -> Position: {holdings.Quantity} | "
                      f"Unrealized P&L: ${unreal_pnl:.2f} ({unreal_pnl_pct:.2f}%)")

    def OnData(self, data):
        """主数据处理"""
        # 使用 RSI 进行简单的交易
        if not self.rsi.IsReady:
            return

        rsi_value = self.rsi.Current.Value

        # RSI 超卖买入
        if rsi_value < 30 and not self.Portfolio[self.spy].IsLong:
            self.SetHoldings(self.spy, 0.5)
            self.Debug(f"[RSI Buy] RSI: {rsi_value:.2f}")

        # RSI 超买卖出
        elif rsi_value > 70 and self.Portfolio[self.spy].IsLong:
            self.Liquidate(self.spy)
            self.Debug(f"[RSI Sell] RSI: {rsi_value:.2f}")

    def OnOrderEvent(self, orderEvent):
        """订单事件"""
        if orderEvent.Status == OrderStatus.Filled:
            self.trade_count += 1
            # OrderFee 是对象（其 Value 为 CashAmount，Amount 为金额），不能直接按数字格式化
            self.Debug(f"[Order #{self.trade_count}] {orderEvent.Symbol} | "
                      f"Qty: {orderEvent.FillQuantity} | "
                      f"Price: ${orderEvent.FillPrice:.2f} | "
                      f"Fee: ${orderEvent.OrderFee.Value.Amount:.2f}")

    def OnEndOfDay(self, symbol):
        """每日收盘"""
        if symbol == self.spy:
            portfolio = self.Portfolio

            self.Debug(f"\n[EOD {self.Time.date()}]")
            self.Debug(f"  Portfolio: ${portfolio.TotalPortfolioValue:,.2f}")
            self.Debug(f"  Cash: ${portfolio.Cash:,.2f}")
            self.Debug(f"  Total Trades: {self.trade_count}")

    def OnEndOfAlgorithm(self):
        """算法结束"""
        self.Debug("\n" + "="*60)
        self.Debug("BACKTEST COMPLETED")
        self.Debug(f"Total Trades: {self.trade_count}")
        final_return = (self.Portfolio.TotalPortfolioValue / self.starting_cash - 1) * 100
        self.Debug(f"Final Return: {final_return:.2f}%")
        self.Debug("="*60)
