Skip to content

TopkDropoutStrategy and SimulatorExecutor Source Analysis

This tutorial provides an in-depth analysis of the source code of two core components in the Qlib framework: TopkDropoutStrategy (Top-K dropout strategy) and SimulatorExecutor (simulator executor). Through source code analysis, we will understand their design philosophy, implementation details, and usage.

1. TopkDropoutStrategy Source Code Analysis

1.1 Overview

TopkDropoutStrategy is an important signal strategy in Qlib, located in qlib/contrib/strategy/signal_strategy.py. It inherits from BaseSignalStrategy and implements Top-K stock selection and dynamic portfolio rebalancing based on prediction signals.

1.2 Class Inheritance Structure

BaseStrategy (abstract base class)
    ↓
BaseSignalStrategy (signal strategy base class)
    ↓  
TopkDropoutStrategy (Top-K dropout strategy)

1.3 Core Parameter Analysis

Let's examine the core parameters of TopkDropoutStrategy in detail:

def __init__(
    self,
    *,
    topk,               # number of stocks held
    n_drop,             # number of stocks replaced each trading day
    method_sell="bottom",   # sell method: "bottom" (sell worst first) or "random" (sell randomly)
    method_buy="top",       # buy method: "top" (buy best first) or "random" (buy randomly)
    hold_thresh=1,         # minimum holding days threshold
    only_tradable=False,   # whether to consider only tradable stocks
    forbid_all_trade_at_limit=True,  # whether to forbid trading at the limit up/down price
    **kwargs,
):

Parameter Details:

  1. topk: the total number of stocks held in the portfolio
  2. n_drop: the number of stocks replaced each trading period; controls turnover rate
  3. method_sell:
  4. "bottom": sell the worst-performing stocks in ascending order of prediction score
  5. "random": randomly select held stocks to sell
  6. method_buy:
  7. "top": buy the best-performing stocks not currently held, in descending order of prediction score
  8. "random": buy randomly from candidate stocks
  9. hold_thresh: minimum holding period to prevent overly frequent trading
  10. only_tradable: whether trade decisions take a stock's tradability status into account
  11. forbid_all_trade_at_limit: limit up/down trading restriction policy

1.4 Core Algorithm Flow

The core logic of TopkDropoutStrategy is implemented in the generate_trade_decision() method:

Step 1: Get the prediction signal

trade_step = self.trade_calendar.get_trade_step()
trade_start_time, trade_end_time = self.trade_calendar.get_step_time(trade_step)
pred_start_time, pred_end_time = self.trade_calendar.get_step_time(trade_step, shift=1)
pred_score = self.signal.get_signal(start_time=pred_start_time, end_time=pred_end_time)

Step 2: Get current holdings

current_temp: Position = copy.deepcopy(self.trade_position)
current_stock_list = current_temp.get_stock_list()
last = pred_score.reindex(current_stock_list).sort_values(ascending=False).index

Step 3: Select buy candidates

if self.method_buy == "top":
    today = get_first_n(
        pred_score[~pred_score.index.isin(last)].sort_values(ascending=False).index,
        self.n_drop + self.topk - len(last),
    )
elif self.method_buy == "random":
    # random selection logic

Step 4: Determine the stocks to sell

# Merge currently held and candidate buy stocks to avoid selling high and buying low
comb = pred_score.reindex(last.union(pd.Index(today))).sort_values(ascending=False).index

if self.method_sell == "bottom":
    sell = last[last.isin(get_last_n(comb, self.n_drop))]
elif self.method_sell == "random":
    # random sell logic

Step 5: Generate trade orders

# Generate sell orders
for code in current_stock_list:
    if code in sell:
        # Check the holding time limit
        if current_temp.get_stock_count(code, bar=time_per_step) < self.hold_thresh:
            continue
        # Generate the sell order
        sell_order = Order(stock_id=code, amount=sell_amount, direction=Order.SELL, ...)

# Generate buy orders  
value = cash * self.risk_degree / len(buy) if len(buy) > 0 else 0
for code in buy:
    buy_order = Order(stock_id=code, amount=buy_amount, direction=Order.BUY, ...)

1.5 Key Design Features

  1. Preventing sell-high-buy-low: The comb mechanism ensures that highly ranked stocks are never sold to buy lower-ranked stocks
  2. Holding time control: The hold_thresh parameter avoids overly frequent trading
  3. Tradability checks: Supports decisions based on each stock's actual tradability status
  4. Limit up/down handling: Supports different trading policies at the limit up/down price
  5. Position risk control: Controls overall risk exposure via risk_degree

2. SimulatorExecutor Source Code Analysis

2.1 Overview

SimulatorExecutor is located in qlib/backtest/executor.py and is the core executor of the Qlib backtest framework, responsible for simulating the trade execution process in a realistic market environment.

2.2 Class Inheritance Structure

BaseExecutor (executor base class)
    ↓
SimulatorExecutor (simulator executor)

2.3 Core Parameter Analysis

def __init__(
    self,
    time_per_step: str,                    # time interval per step
    start_time: Union[str, pd.Timestamp] = None,    # start time
    end_time: Union[str, pd.Timestamp] = None,      # end time
    indicator_config: dict = {},           # indicator configuration
    generate_portfolio_metrics: bool = False,  # whether to generate portfolio metrics
    verbose: bool = False,                # whether to output detailed information
    track_data: bool = False,             # whether to track data (used for RL training)
    common_infra: CommonInfrastructure | None = None,  # common infrastructure
    trade_type: str = TT_SERIAL,          # trade type
    **kwargs: Any,
) -> None:

2.4 Trade Type Mechanism

SimulatorExecutor supports two trade execution modes:

Serial trading (TT_SERIAL)

TT_SERIAL = "serial"
# Orders are executed sequentially in order
# Supports selling stocks first, then using the freed-up cash to buy new stocks

Parallel trading (TT_PARAL)

TT_PARAL = "parallel"  
# Orders are executed in parallel
# Trying to sell before buying will fail (insufficient cash)

2.5 Core Execution Flow

Order iterator generation

def _get_order_iterator(self, trade_decision: BaseTradeDecision) -> List[Order]:
    orders = _retrieve_orders_from_decision(trade_decision)

    if self.trade_type == self.TT_SERIAL:
        order_it = orders  # keep the original order
    elif self.trade_type == self.TT_PARAL:
        # Sell orders first to avoid cash conflicts
        order_it = sorted(orders, key=lambda order: -order.direction)
    else:
        raise NotImplementedError(f"This type of input is not supported")
    return order_it

Data collection and execution

def _collect_data(self, trade_decision: BaseTradeDecision, level: int = 0) -> Tuple[List[object], dict]:
    execute_result: list = []

    for order in self._get_order_iterator(trade_decision):
        # Clear intraday trading data
        now_deal_day = self.trade_calendar.get_step_time()[0].floor(freq="D")
        if self.deal_day is None or now_deal_day > self.deal_day:
            self.dealt_order_amount = defaultdict(float)
            self.deal_day = now_deal_day

        # Execute the order
        trade_val, trade_cost, trade_price = self.trade_exchange.deal_order(
            order,
            trade_account=self.trade_account,
            dealt_order_amount=self.dealt_order_amount,
        )

        execute_result.append((order, trade_val, trade_cost, trade_price))
        self.dealt_order_amount[order.stock_id] += order.deal_amount

    return execute_result, {"trade_info": execute_result}

2.6 Key Design Features

  1. Trade type flexibility: Supports both serial and parallel trading modes
  2. Intraday trading tracking: Maintains dealt_order_amount to track cumulative intraday trading volume
  3. Account state management: Tightly integrated with the trading account, updating cash status in real time
  4. Detailed execution records: Records execution details of every trade for analysis
  5. Infrastructure integration: Seamlessly integrates with the exchange, accounts, and other infrastructure

3. How They Work Together

3.1 Strategy-Executor Collaboration Flow

  1. TopkDropoutStrategy receives market signals and generates trade decisions
  2. TradeDecisionWO wraps the order list and strategy information
  3. SimulatorExecutor receives the decision and executes the actual trades
  4. Exchange simulates the real trading environment to process orders
  5. Account updates the account and holdings status

3.2 Data Flow Analysis

  1. Signal input: TopkDropoutStrategy receives prediction signals
  2. Decision generation: Generates trade decisions based on the signals and current holdings
  3. Order extraction: SimulatorExecutor extracts the specific orders from the decision
  4. Execution simulation: Simulates order execution through the exchange interface
  5. State update: Updates the account and holdings status

4. Usage Recommendations and Best Practices

4.1 TopkDropoutStrategy Parameter Tuning

  1. topk-to-n_drop ratio: It is recommended that n_drop not exceed 20% of topk to avoid excessive turnover
  2. hold_thresh setting: Set a reasonable minimum holding period based on trading frequency
  3. Method selection:
  4. For strong signals, use the "top" + "bottom" combination
  5. For weak signals, consider introducing randomness

4.2 SimulatorExecutor Configuration Optimization

  1. trade_type selection:
  2. Daily-frequency backtests: TT_SERIAL recommended
  3. High-frequency backtests: choose based on the actual scenario
  4. indicator_config: Enable key indicators to monitor trade quality
  5. verbose mode: Enable during development and debugging; disable in production

4.3 Performance Optimization Tips

  1. Caching mechanisms: Use signal caching sensibly to reduce redundant computation
  2. Batch processing: Generate trade decisions in batches whenever possible
  3. Memory management: Clean up unneeded historical data promptly

5. Extension and Customization

5.1 Custom Strategy Implementation

class CustomTopkStrategy(BaseSignalStrategy):
    def generate_trade_decision(self, execute_result=None):
        # custom decision logic
        pass

5.2 Custom Executor

class CustomExecutor(BaseExecutor):
    def _collect_data(self, trade_decision, level=0):
        # custom execution logic
        pass

6. Conclusion

TopkDropoutStrategy and SimulatorExecutor are core components of the Qlib framework, and their collaboration constitutes the complete quantitative trading backtest workflow. By deeply understanding their source code implementations, we can:

  1. Better configure and tune strategy parameters
  2. Carry out customized development for specific needs
  3. Understand how backtest results are produced
  4. Optimize strategy execution efficiency

This modular design not only provides a high degree of flexibility but also gives users powerful extensibility, and is an excellent practice for modern quantitative investment platforms.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
TopkDropoutStrategy and SimulatorExecutor source code analysis demo

This example shows how to run a quantitative investment backtest with TopkDropoutStrategy
and SimulatorExecutor, and provides a deep dive into their internal mechanisms.

"""

import sys
import warnings
import numpy as np
import pandas as pd
from pathlib import Path

# Add the project root directory to the Python path
sys.path.insert(0, str(Path(__file__).parent.parent))

import qlib
from qlib.config import REG_CN
from qlib.contrib.data.handler import Alpha158
from qlib.contrib.model.gbdt import LGBModel
from qlib.contrib.strategy.signal_strategy import TopkDropoutStrategy
from qlib.backtest.executor import SimulatorExecutor
from qlib.backtest.account import Account
from qlib.backtest.exchange import Exchange
from qlib.data.dataset import DatasetH
from qlib.workflow import R
from qlib.backtest import backtest
from qlib.utils import init_instance_by_config
from qlib.model.trainer import TrainerR

# Suppress warnings
warnings.filterwarnings('ignore')

def initialize_qlib():
    """Initialize the Qlib environment"""
    print("🚀 Initializing Qlib environment...")
    try:
        # Initialize Qlib with local data
        provider_uri = "~/.qlib/qlib_data/cn_data"  # data path
        qlib.init(provider_uri=provider_uri, region=REG_CN)
        print("✅ Qlib initialized successfully")
        return True
    except Exception as e:
        print(f"❌ Qlib initialization failed: {e}")
        return False

def create_dataset():
    """Create the dataset"""
    print("\n📊 Creating the Alpha158 feature dataset...")

    # Alpha158 data handler configuration
    handler_config = {
        "start_time": "2020-01-01",
        "end_time": "2020-12-31", 
        "fit_start_time": "2020-01-01",
        "fit_end_time": "2020-08-31",
        "instruments": "csi300",  # CSI 300 constituents
        "infer_processors": [
            {
                "class": "RobustZScoreNorm",
                "kwargs": {"fields_group": "feature", "clip_outlier": True},
            },
            {"class": "Fillna", "kwargs": {"fields_group": "feature"}},
        ],
        "learn_processors": [
            {"class": "DropnaLabel"},
            {"class": "CSRankNorm", "kwargs": {"fields_group": "label"}},
        ],
        "label": ["Ref($close, -2) / Ref($close, -1) - 1"],  # 2-day forward return
    }

    # Create the Alpha158 handler
    handler = Alpha158(**handler_config)

    # Define dataset segments
    segments = {
        "train": ("2020-01-01", "2020-06-30"),
        "valid": ("2020-07-01", "2020-08-31"), 
        "test": ("2020-09-01", "2020-12-31")
    }

    # Create the dataset
    dataset = DatasetH(handler, segments=segments)

    print("✅ Dataset created successfully")
    print(f"   - Feature dimension: Alpha158 (158 technical indicators)")
    print(f"   - Stock pool: CSI 300 constituents") 
    print(f"   - Time range: 2020-01-01 to 2020-12-31")
    print(f"   - Label: 2-day forward return")

    return dataset

def train_model(dataset):
    """Train the LightGBM prediction model"""
    print("\n🤖 Training the LightGBM prediction model...")

    # Create the LGBModel instance directly
    model = LGBModel(
        objective="regression",
        num_leaves=60,
        learning_rate=0.1,
        feature_fraction=0.8,
        bagging_fraction=0.8,
        bagging_freq=5,
        verbose=-1,
        num_boost_round=100,
        early_stopping_rounds=10,
    )

    # Train the model
    model.fit(dataset)

    print("✅ Model training completed")
    print("   - Model type: LightGBM")
    print("   - Objective function: regression")
    print("   - Number of leaves: 60")
    print("   - Learning rate: 0.1")

    return model

def analyze_topk_dropout_strategy():
    """Analyze the core mechanisms of TopkDropoutStrategy"""
    print("\n🔍 TopkDropoutStrategy source code mechanism analysis")
    print("=" * 60)

    # 1. Core parameter explanation
    print("📋 Core parameters:")
    print("   • topk: number of stocks held (e.g.: 50 stocks)")
    print("   • n_drop: number of stocks rebalanced per day (e.g.: 5 stocks)")
    print("   • method_sell: sell strategy")
    print("     - 'bottom': sell the lowest-scoring stocks")
    print("     - 'random': sell randomly")
    print("   • method_buy: buy strategy") 
    print("     - 'top': buy the highest-scoring stocks not currently held")
    print("     - 'random': buy randomly")
    print("   • hold_thresh: minimum holding days")
    print("   • only_tradable: whether to consider only tradable stocks")
    print("   • forbid_all_trade_at_limit: whether trading is forbidden at the limit up/down price")

    # 2. Algorithm flow analysis
    print("\n🔄 Core algorithm flow:")
    print("   1️⃣ Get the prediction signals for the current trading day")
    print("   2️⃣ Analyze current holdings, sorted by score")  
    print("   3️⃣ Select buy candidates (high-scoring stocks not currently held)")
    print("   4️⃣ Determine the stocks to sell (avoiding sell-high-buy-low)")
    print("   5️⃣ Generate the concrete buy and sell orders")

    # 3. Key design highlights
    print("\n💡 Key design highlights:")
    print("   ✨ Sell-high-buy-low prevention: the comb mechanism ensures trading rationality")
    print("   ✨ Holding time control: hold_thresh avoids overly frequent trading")
    print("   ✨ Tradability checks: considers each stock's actual tradability status")
    print("   ✨ Risk management: risk_degree controls the overall position size")

def analyze_simulator_executor():
    """Analyze the core mechanisms of SimulatorExecutor"""
    print("\n🎮 SimulatorExecutor mechanism analysis")
    print("=" * 60)

    # 1. Execution mode analysis
    print("⚡ Trade execution modes:")
    print("   • TT_SERIAL (serial mode):")
    print("     - Orders executed sequentially")
    print("     - Supports sell-first-then-buy (release cash, then reinvest)")
    print("     - Suitable for daily-frequency trading")
    print("   • TT_PARAL (parallel mode):")
    print("     - Orders executed in parallel") 
    print("     - Sell orders executed first (to avoid cash conflicts)")
    print("     - Suitable for high-frequency trading scenarios")

    # 2. Core functionality
    print("\n🛠️ Core functional modules:")
    print("   📦 Order management: _get_order_iterator() processes the order sequence")
    print("   💰 Cash management: tracks account cash changes in real time")
    print("   📊 Trade records: records the execution details of every trade")
    print("   🔄 Intraday tracking: dealt_order_amount tracks cumulative intraday trades")

    # 3. Integration features
    print("\n🔗 Infrastructure integration:")
    print("   🏪 Exchange: simulates the real exchange environment")
    print("   💳 Account: manages cash and holdings status")
    print("   📅 Calendar: manages the trading calendar and time")
    print("   📈 Metrics: generates trade and portfolio metrics")

def create_strategy_config(model, dataset):
    """Create the strategy configuration"""
    print("\n⚙️ Configuring TopkDropoutStrategy...")

    # Strategy configuration
    strategy_config = {
        "class": "TopkDropoutStrategy",
        "kwargs": {
            "signal": (model, dataset),  # model and dataset
            "topk": 20,              # hold 20 stocks
            "n_drop": 3,             # rebalance 3 stocks per day
            "method_sell": "bottom", # sell the lowest-scoring stocks
            "method_buy": "top",     # buy the highest-scoring stocks  
            "hold_thresh": 1,        # hold for at least 1 day
            "only_tradable": True,   # consider only tradable stocks
            "forbid_all_trade_at_limit": True,  # forbid trading at the limit up/down price
        },
    }

    print("✅ Strategy configuration completed")
    print(f"   - Number of holdings: {strategy_config['kwargs']['topk']} stocks")
    print(f"   - Daily rebalancing amount: {strategy_config['kwargs']['n_drop']} stocks") 
    print(f"   - Turnover rate: {strategy_config['kwargs']['n_drop']/strategy_config['kwargs']['topk']*100:.1f}%")

    return strategy_config

def create_executor_config():
    """Create the executor configuration"""
    print("\n⚙️ Configuring SimulatorExecutor...")

    # Executor configuration
    executor_config = {
        "class": "SimulatorExecutor",
        "kwargs": {
            "time_per_step": "day",           # daily-frequency trading
            "generate_portfolio_metrics": True,  # generate portfolio metrics
            "verbose": False,                 # do not show detailed trade information
            "trade_type": SimulatorExecutor.TT_SERIAL,  # serial execution mode
            "indicator_config": {             # trade indicator configuration
                "show_indicator": True,
                "pa_config": {
                    "base_price": "twap",     # based on time-weighted average price
                    "weight_method": "mean",  # equal weighting
                },
                "ffr_config": {
                    "weight_method": "value_weighted",  # weighted by value
                }
            }
        },
    }

    print("✅ Executor configuration completed")
    print(f"   - Execution frequency: {executor_config['kwargs']['time_per_step']}")
    print(f"   - Execution mode: {executor_config['kwargs']['trade_type']}")
    print("   - Indicator monitoring: price advantage and fill-rate monitoring enabled")

    return executor_config

def run_backtest(strategy_config, executor_config):
    """Run the backtest"""
    print("\n🚀 Running the quantitative backtest...")
    print("=" * 60)

    # Backtest configuration
    backtest_config = {
        "start_time": "2020-09-01",
        "end_time": "2020-12-31", 
        "account": 1000000,       # initial capital: 1 million
        "benchmark": "SH000300",  # CSI 300 benchmark
        "exchange_kwargs": {
            "freq": "day",
            "limit_threshold": 0.095,  # limit up/down threshold
            "deal_price": "close",     # execute at the closing price
            "open_cost": 0.0005,       # commission: 0.05%
            "close_cost": 0.0005,
            "min_cost": 5,             # minimum commission: 5 yuan
        },
    }

    # Execute the backtest
    print("📊 Starting backtest computation...")

    try:
        # Run the backtest
        portfolio_metric_dict, indicator_dict = backtest(
            executor=executor_config,
            strategy=strategy_config, 
            **backtest_config
        )

        print("✅ Backtest computation completed")

        # Analyze the backtest results
        analyze_backtest_results(portfolio_metric_dict, indicator_dict)

        return portfolio_metric_dict, indicator_dict

    except Exception as e:
        print(f"❌ Backtest execution failed: {e}")
        return None, None

def analyze_backtest_results(portfolio_metric_dict, indicator_dict):
    """Analyze the backtest results"""
    print("\n📈 Backtest result analysis")
    print("=" * 60)

    if portfolio_metric_dict is None:
        print("❌ No valid backtest results")
        return

    try:
        # Extract key metrics
        excess_return_without_cost = portfolio_metric_dict.get('excess_return_without_cost', {})
        excess_return_with_cost = portfolio_metric_dict.get('excess_return_with_cost', {})

        print("📊 Portfolio performance:")
        if 'annualized_return' in excess_return_without_cost:
            print(f"   📈 Annualized return (without cost): {excess_return_without_cost['annualized_return']:.2%}")
        if 'annualized_return' in excess_return_with_cost:  
            print(f"   💰 Annualized return (with cost): {excess_return_with_cost['annualized_return']:.2%}")
        if 'information_ratio' in excess_return_with_cost:
            print(f"   📏 Information ratio: {excess_return_with_cost['information_ratio']:.3f}")
        if 'max_drawdown' in excess_return_with_cost:
            print(f"   📉 Maximum drawdown: {excess_return_with_cost['max_drawdown']:.2%}")

        # Trade indicator analysis
        if indicator_dict:
            print("\n💹 Trade execution analysis:")
            if '1day.pa' in indicator_dict:
                pa = indicator_dict['1day.pa']
                if isinstance(pa, (int, float)):
                    print(f"   ⚡ Price advantage (PA): {pa:.4f}")
            if '1day.ffr' in indicator_dict:
                ffr = indicator_dict['1day.ffr'] 
                if isinstance(ffr, (int, float)):
                    print(f"   ✅ Fill rate (FFR): {ffr:.2%}")

    except Exception as e:
        print(f"⚠️ Problem encountered during result analysis: {e}")
        print("📋 Available metric keys:", list(portfolio_metric_dict.keys()) if portfolio_metric_dict else "none")

def demonstrate_strategy_mechanism():
    """Demonstrate the strategy's internal mechanisms"""
    print("\n🔬 In-depth look at strategy mechanisms")
    print("=" * 60)

    # Simulate the strategy decision process
    print("🎯 Simulating the TopkDropoutStrategy decision process:")

    # Create simulated data
    np.random.seed(42)
    stocks = [f"Stock{i:03d}" for i in range(100)]
    pred_scores = pd.Series(np.random.randn(100), index=stocks, name='score')
    current_holdings = stocks[:20]  # currently holding the first 20 stocks

    print(f"\n📊 Current market state:")
    print(f"   • Stock pool size: {len(stocks)} stocks")
    print(f"   • Current holdings: {len(current_holdings)} stocks") 
    print(f"   • Prediction signal range: [{pred_scores.min():.3f}, {pred_scores.max():.3f}]")

    # Simulated strategy parameters
    topk, n_drop = 20, 3

    # Step 1: Rank current holdings
    current_scores = pred_scores[current_holdings].sort_values(ascending=False)
    print(f"\n🔹 Step 1 - Current holdings analysis:")
    print(f"   Best holding: {current_scores.index[0]} (score: {current_scores.iloc[0]:.3f})")
    print(f"   Worst holding: {current_scores.index[-1]} (score: {current_scores.iloc[-1]:.3f})")

    # Step 2: Buy candidate selection  
    not_holding = pred_scores[~pred_scores.index.isin(current_holdings)]
    buy_candidates = not_holding.sort_values(ascending=False).head(n_drop + topk - len(current_holdings))
    print(f"\n🔹 Step 2 - Buy candidate analysis:")
    print(f"   Number of candidates: {len(buy_candidates)} stocks")
    print(f"   Best candidate: {buy_candidates.index[0]} (score: {buy_candidates.iloc[0]:.3f})")

    # Step 3: Avoid sell-high-buy-low
    combined = pd.concat([current_scores, buy_candidates]).sort_values(ascending=False)
    sell_candidates = current_scores[current_scores.index.isin(combined.tail(n_drop).index)]
    print(f"\n🔹 Step 3 - Sell decision analysis:")
    print(f"   Number to sell: {len(sell_candidates)} stocks")
    if len(sell_candidates) > 0:
        print(f"   Will sell: {sell_candidates.index[0]} (score: {sell_candidates.iloc[0]:.3f})")

    # Step 4: Final trade decision
    actual_buy = buy_candidates.head(len(sell_candidates))
    print(f"\n🔹 Step 4 - Final trade decision:")
    print(f"   Number of stocks to sell: {len(sell_candidates)}")
    print(f"   Number of stocks to buy: {len(actual_buy)}")
    print(f"   Expected turnover rate: {len(sell_candidates)/topk*100:.1f}%")

def main():
    """Main function"""
    print("🎯 TopkDropoutStrategy and SimulatorExecutor source code analysis demo")
    print("=" * 80)

    # Initialize the environment
    if not initialize_qlib():
        print("❌ Environment initialization failed, program exiting")
        return

    try:
        # Source code mechanism analysis
        analyze_topk_dropout_strategy()
        analyze_simulator_executor() 

        # Demonstrate the strategy's internal mechanisms
        demonstrate_strategy_mechanism()

        # Create the dataset
        dataset = create_dataset()

        # Train the model
        model = train_model(dataset)

        # Configure the strategy and executor
        strategy_config = create_strategy_config(model, dataset)
        executor_config = create_executor_config()

        # Run the backtest
        portfolio_results, indicator_results = run_backtest(strategy_config, executor_config)

        print("\n🎉 Demo completed!")
        print("=" * 80)
        print("📚 Key takeaways:")
        print("   1️⃣ TopkDropoutStrategy implements intelligent stock selection and dynamic rebalancing")
        print("   2️⃣ SimulatorExecutor provides high-fidelity trade execution simulation")
        print("   3️⃣ The two work together to form a complete quantitative backtest system") 
        print("   4️⃣ The modular design supports flexible strategy customization and optimization")

        print(f"\n📖 Detailed tutorial document: tutorial/markdown/topk_dropout_strategy_and_simulator_executor_analysis.md")
        print(f"💻 Demo code location: demo/topk_dropout_and_simulator_demo.py")

    except Exception as e:
        print(f"❌ Program execution error: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()