"""
QCAlgorithm 基础示例

本示例演示了 QCAlgorithm 的核心功能：
1. 算法生命周期
2. 证券添加与配置
3. 不同数据分辨率的使用
4. 事件处理
5. Portfolio 和 Securities 对象的使用
"""

from AlgorithmImports import *
from datetime import timedelta, datetime

class QCAlgorithmBasicsAlgorithm(QCAlgorithm):
    """
    QCAlgorithm 基础教学示例

    演示内容：
    - Initialize 方法中的各种设置
    - OnData 方法中的数据处理
    - Portfolio 和 Securities 的使用
    - 各种事件处理
    """

    def Initialize(self):
        """
        初始化方法 - 算法启动时只调用一次

        在这里设置：
        - 回测时间范围
        - 初始资金
        - 添加证券
        - 创建指标
        - 设置定时任务
        """

        # ========== 1. 时间和资金设置 ==========

        # 设置回测时间范围
        self.SetStartDate(2023, 1, 1)      # 开始日期
        self.SetEndDate(2023, 6, 30)       # 结束日期

        # 设置初始资金
        self.SetCash(100000)               # $100,000

        # 设置账户货币
        self.SetAccountCurrency("USD")

        # 设置基准
        self.SetBenchmark("SPY")


        # ========== 2. 添加不同类型的证券 ==========

        # 股票
        self.spy = self.AddEquity("SPY", Resolution.Daily, fillForward=True).Symbol
        self.aapl = self.AddEquity("AAPL", Resolution.Daily).Symbol

        # 配置证券属性
        spy_security = self.Securities[self.spy]
        spy_security.SetDataNormalizationMode(DataNormalizationMode.Adjusted)
        # 注意：数据前向填充等选项通过 AddEquity 的参数设置（如 fillForward=True），
        # Security 对象没有 SetFillDataForward 这类方法

        # 外汇
        self.eurusd = self.AddForex("EURUSD", Resolution.Hour).Symbol

        # 加密货币
        # self.btcusd = self.AddCrypto("BTCUSD", Resolution.Hour).Symbol


        # ========== 3. 创建技术指标 ==========

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

        # RSI 指标
        self.rsi = self.RSI(self.spy, 14, MovingAverageType.Simple, Resolution.Daily)

        # ATR 指标
        self.atr = self.ATR(self.spy, 14, MovingAverageType.Simple, Resolution.Daily)


        # ========== 4. 设置定时任务 ==========

        # 每天开盘后30分钟执行
        self.Schedule.On(
            self.DateRules.EveryDay(self.spy),
            self.TimeRules.AfterMarketOpen(self.spy, 30),
            self.EveryDayAfterOpen
        )

        # 每周五收盘前执行
        self.Schedule.On(
            self.DateRules.Every(DayOfWeek.Friday),
            self.TimeRules.BeforeMarketClose(self.spy, 30),
            self.FridayBeforeClose
        )


        # ========== 5. 自定义变量 ==========

        self.trade_count = 0           # 交易计数
        self.total_fees = 0            # 总手续费
        self.last_rsi = None           # 上次RSI值
        self.starting_cash = self.Portfolio.TotalPortfolioValue  # 记录初始资金


        # ========== 6. 输出初始化信息 ==========

        self.Debug("=" * 60)
        self.Debug("QCAlgorithm Basics - Initialization Complete")
        self.Debug("=" * 60)
        self.Debug(f"Start Date: {self.StartDate}")
        self.Debug(f"End Date: {self.EndDate}")
        self.Debug(f"Initial Cash: ${self.Portfolio.Cash:,.2f}")
        self.Debug(f"Securities Added: {len(self.Securities)}")
        self.Debug(f"Indicators Created: SMA(20), SMA(50), RSI(14), ATR(14)")
        self.Debug("=" * 60)


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

        每个新的数据点都会触发此函数。
        在这里实现主要的交易逻辑。
        """
        # 等待指标准备就绪
        if not (self.sma_20.IsReady and self.sma_50.IsReady and self.rsi.IsReady):
            return


        # ========== 1. 访问证券信息 ==========

        # 获取 SPY 的当前价格
        spy_price = self.Securities[self.spy].Price
        spy_volume = self.Securities[self.spy].Volume

        # 获取买卖价
        spy_bid = self.Securities[self.spy].BidPrice
        spy_ask = self.Securities[self.spy].AskPrice


        # ========== 2. 访问投资组合信息 ==========

        # 检查是否已投资
        is_invested = self.Portfolio.Invested

        # 获取 SPY 的持仓信息
        spy_holdings = self.Portfolio[self.spy]
        spy_quantity = spy_holdings.Quantity           # 持仓数量
        spy_avg_price = spy_holdings.AveragePrice     # 平均成本
        spy_total_cost = spy_holdings.TotalCost       # 总成本

        # 获取账户信息
        total_portfolio_value = self.Portfolio.TotalPortfolioValue
        cash = self.Portfolio.Cash
        total_margin_used = self.Portfolio.TotalMarginUsed


        # ========== 3. 简单的交易逻辑示例 ==========

        # 获取指标值
        sma_20_value = self.sma_20.Current.Value
        sma_50_value = self.sma_50.Current.Value
        rsi_value = self.rsi.Current.Value
        atr_value = self.atr.Current.Value

        # 策略：短期均线上穿长期均线 且 RSI 不超买
        if sma_20_value > sma_50_value and not spy_holdings.IsLong:
            if rsi_value < 70:  # RSI 不超买
                self.SetHoldings(self.spy, 0.5)  # 使用50%资金买入
                self.trade_count += 1
                self.Debug(f"[BUY] {self.Time.date()} | "
                          f"Price: ${spy_price:.2f} | "
                          f"SMA20: {sma_20_value:.2f} | "
                          f"SMA50: {sma_50_value:.2f} | "
                          f"RSI: {rsi_value:.2f}")

        # 止损/止盈条件
        elif spy_holdings.IsLong:
            # 计算收益率
            return_pct = (spy_price / spy_avg_price - 1) * 100

            # 止损：亏损超过5%
            if return_pct < -5:
                self.Liquidate(self.spy)
                self.Debug(f"[STOP LOSS] {self.Time.date()} | "
                          f"Exit: ${spy_price:.2f} | "
                          f"P&L: {return_pct:.2f}%")

            # 止盈：收益超过15%
            elif return_pct > 15:
                self.Liquidate(self.spy)
                self.Debug(f"[TAKE PROFIT] {self.Time.date()} | "
                          f"Exit: ${spy_price:.2f} | "
                          f"P&L: {return_pct:.2f}%")

            # 均线死叉平仓
            elif sma_20_value < sma_50_value:
                self.Liquidate(self.spy)
                self.Debug(f"[EXIT] {self.Time.date()} | "
                          f"Price: ${spy_price:.2f} | "
                          f"SMA20: {sma_20_value:.2f} | "
                          f"SMA50: {sma_50_value:.2f} | "
                          f"P&L: {return_pct:.2f}%")


        # ========== 4. 绘制图表 ==========

        self.Plot("Strategy", "Price", spy_price)
        self.Plot("Strategy", "SMA20", sma_20_value)
        self.Plot("Strategy", "SMA50", sma_50_value)
        self.Plot("Indicators", "RSI", rsi_value)
        self.Plot("Portfolio", "Total Value", total_portfolio_value)
        self.Plot("Portfolio", "Cash", cash)


    def EveryDayAfterOpen(self):
        """每天开盘后30分钟执行"""
        spy_price = self.Securities[self.spy].Price
        self.Debug(f"[Scheduled] {self.Time.date()} {self.Time.time()} | "
                  f"Market Open +30min | SPY: ${spy_price:.2f}")


    def FridayBeforeClose(self):
        """每周五收盘前30分钟执行"""
        portfolio_value = self.Portfolio.TotalPortfolioValue
        total_return = (portfolio_value / self.starting_cash - 1) * 100

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


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

        当订单状态发生变化时触发。
        """
        if orderEvent.Status == OrderStatus.Filled:
            # 订单已成交（OrderEvent 没有 Order 属性，直接读取其成员）
            self.Debug(f"[ORDER FILLED] {self.Time.date()} | "
                      f"Symbol: {orderEvent.Symbol} | "
                      f"Quantity: {orderEvent.FillQuantity} | "
                      f"Price: ${orderEvent.FillPrice:.2f} | "
                      f"Fee: ${orderEvent.OrderFee.Value.Amount:.2f} | "
                      f"OrderId: {orderEvent.OrderId}")

            # 累计手续费（OrderFee 对象，金额取 Value.Amount）
            self.total_fees += float(orderEvent.OrderFee.Value.Amount)

        elif orderEvent.Status == OrderStatus.Canceled:
            self.Debug(f"[ORDER CANCELED] {orderEvent.OrderId}")

        elif orderEvent.Status == OrderStatus.Invalid:
            self.Debug(f"[ORDER INVALID] {orderEvent.Message}")


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

        每个证券都会触发一次。
        """
        if symbol == self.spy:
            # 只处理 SPY 的每日收盘
            portfolio_value = self.Portfolio.TotalPortfolioValue
            cash = self.Portfolio.Cash
            holdings = self.Portfolio[self.spy]

            self.Debug(f"[EOD] {self.Time.date()} | "
                      f"Portfolio: ${portfolio_value:,.2f} | "
                      f"Cash: ${cash:,.2f} | "
                      f"Holdings: {holdings.Quantity} | "
                      f"Total Fees: ${self.total_fees:.2f}")


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

        输出最终的统计信息。
        """
        final_value = self.Portfolio.TotalPortfolioValue
        total_return = (final_value / self.starting_cash - 1) * 100

        self.Debug("=" * 60)
        self.Debug("BACKTEST COMPLETED - FINAL STATISTICS")
        self.Debug("=" * 60)
        self.Debug(f"Starting Capital: ${self.starting_cash:,.2f}")
        self.Debug(f"Final Portfolio Value: ${final_value:,.2f}")
        self.Debug(f"Total Return: {total_return:.2f}%")
        self.Debug(f"Total Trades: {self.trade_count}")
        self.Debug(f"Total Fees Paid: ${self.total_fees:.2f}")

        # Statistics 是 StatisticsResults 对象：
        # 只有 TotalPerformance / RollingPerformances / Summary 三个成员
        stats = self.Statistics.TotalPerformance.PortfolioStatistics
        self.Debug(f"Win Rate: {stats.WinRate:.2f}")
        self.Debug(f"Sharpe Ratio: {stats.SharpeRatio:.2f}")
        # Drawdown 是 0-1 的小数（如 0.15 表示 15%），按百分比显示要乘 100
        self.Debug(f"Max Drawdown: {stats.Drawdown * 100:.2f}%")
        self.Debug("=" * 60)


    # ========== 辅助方法 ==========

    def GetPortfolioPosition(self, symbol):
        """
        获取持仓信息

        Args:
            symbol: 证券的 Symbol 对象

        Returns:
            dict: 包含持仓信息的字典
        """
        holdings = self.Portfolio[symbol]
        security = self.Securities[symbol]

        return {
            'symbol': symbol,
            'quantity': holdings.Quantity,
            'average_price': holdings.AveragePrice,
            'current_price': security.Price,
            'market_value': holdings.HoldingsValue,
            'total_cost': holdings.TotalCost,
            'unrealized_pnl': holdings.UnrealizedProfit,
            'unrealized_pnl_pct': holdings.UnrealizedProfitPercent * 100
        }

    def PrintPortfolioSummary(self):
        """打印投资组合摘要"""
        self.Debug("-" * 50)
        self.Debug("PORTFOLIO SUMMARY")
        self.Debug("-" * 50)
        self.Debug(f"Total Portfolio Value: ${self.Portfolio.TotalPortfolioValue:,.2f}")
        self.Debug(f"Total Cash: ${self.Portfolio.Cash:,.2f}")
        self.Debug(f"Total Margin Used: ${self.Portfolio.TotalMarginUsed:,.2f}")
        self.Debug(f"Invested: {self.Portfolio.Invested}")
        self.Debug("-" * 50)

        for symbol, holdings in self.Portfolio.items():
            if holdings.Invested:
                info = self.GetPortfolioPosition(symbol)
                self.Debug(f"{info['symbol']}:")
                self.Debug(f"  Quantity: {info['quantity']}")
                self.Debug(f"  Avg Price: ${info['average_price']:.2f}")
                self.Debug(f"  Current Price: ${info['current_price']:.2f}")
                self.Debug(f"  Market Value: ${info['market_value']:,.2f}")
                self.Debug(f"  Unrealized P&L: ${info['unrealized_pnl']:,.2f} ({info['unrealized_pnl_pct']:.2f}%)")
        self.Debug("-" * 50)


# ========== 简化版：只包含核心功能的示例 ==========

class SimpleQCAlgorithmExample(QCAlgorithm):
    """
    简化的 QCAlgorithm 示例

    只包含最基本的元素，适合快速理解。
    """

    def Initialize(self):
        # 1. 设置时间和资金
        self.SetStartDate(2023, 1, 1)
        self.SetEndDate(2023, 12, 31)
        self.SetCash(100000)

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

        # 3. 创建指标
        self.fast_ma = self.SMA(self.spy, 20, Resolution.Daily)
        self.slow_ma = self.SMA(self.spy, 50, Resolution.Daily)

    def OnData(self, data):
        # 等待指标就绪
        if not self.fast_ma.IsReady:
            return

        # 获取当前价格和指标
        price = self.Securities[self.spy].Price
        fast = self.fast_ma.Current.Value
        slow = self.slow_ma.Current.Value
        holdings = self.Portfolio[self.spy]

        # 简单的均线交叉策略
        if fast > slow and not holdings.IsLong:
            self.SetHoldings(self.spy, 1)  # 100% 买入
        elif fast < slow and holdings.IsLong:
            self.Liquidate(self.spy)  # 清仓

    def OnOrderEvent(self, orderEvent):
        # 订单成交时输出
        if orderEvent.Status == OrderStatus.Filled:
            self.Debug(f"Order filled: {orderEvent.Symbol}")
