基于路径依赖的Python股票池每周动态维持模拟需求
Hey there! Let's walk through how to implement this stock portfolio simulation exactly as you've outlined. Here's a structured breakdown with actionable steps and example logic:
Core Simulation Requirements Recap
First, let's align on the ground rules we're working with:
- 6 years of weekly stock data, with ~1000 stocks per week (slight variance)
- Start at
t0with a random selection of 75 stocks - Each subsequent week
t_n:- Some stocks exit the portfolio with probability
p(due to structural reasons like delisting/merger) - Rebalance the portfolio to always maintain exactly 75 stocks by replacing exited stocks with new picks from the week's non-portfolio stocks
- Some stocks exit the portfolio with probability
Step 1: Initialize the Portfolio at t0
- Pull the full list of stocks available in the first week (
t0) - Use a true random sampling method to pick 75 distinct stocks from this pool. Avoid any bias (e.g., don't favor large-cap or high-volume stocks unless specified)
Step 2: Weekly Exit Logic
For each stock in your current 75-stock portfolio:
- Independently check if it exits: generate a random number between 0 and 1, and if it's less than
p, mark the stock for removal - Optional edge case handling: If a stock no longer exists in the current week's full stock pool (e.g., it delisted outside the probability-based exit), automatically mark it as exited
- Count the total number of exiting stocks (
exit_count), which will range from 0 to 75
Step 3: Rebalance to 75 Stocks
- Calculate how many stocks you need to add:
need_to_add = exit_count(since we start with 75, subtract the remaining after exits to get the gap) - Filter the current week's full stock pool to get available candidates: all stocks not already in your current portfolio
- Randomly sample
need_to_addstocks from this available pool and add them to your portfolio - Verify the final portfolio size is exactly 75 to catch any edge cases (e.g., if the available pool is unexpectedly small)
Key Edge Cases to Anticipate
- Insufficient available stocks: While your setup says ~1000 stocks per week (so 925+ available after excluding the portfolio), in rare cases you might hit a week with fewer available stocks than needed. If this happens, you could:
- Adjust the exit probability dynamically for that week
- Prioritize adding stocks that have been present in recent weeks (to avoid one-off new listings)
- Repeat selections: Ensure your random sampling doesn't pick the same stock multiple times in one rebalance (most standard random sample functions handle this automatically)
- Consistent randomness: If you need reproducible results, set a fixed random seed at the start of the simulation
Example Pseudocode (Python)
Here's a concrete snippet to illustrate the logic:
import random # Prepped data: Dictionary mapping each week number to its list of stocks # (Replace with your actual 6-year weekly stock data) total_weeks = 52 * 6 all_stocks_by_week = { week: [f"stock_{i}" for i in range(random.randint(950, 1050))] for week in range(total_weeks) } # Step 1: Initialize t0 portfolio initial_stocks = all_stocks_by_week[0] current_portfolio = random.sample(initial_stocks, 75) exit_probability = 0.02 # Replace with your desired probability p # Step 2 & 3: Iterate through each subsequent week for week in range(1, total_weeks): current_week_stocks = all_stocks_by_week[week] # Determine exiting stocks exiting_stocks = [] for stock in current_portfolio: # Auto-exit if stock isn't in the current week's pool, plus probability-based exit if stock not in current_week_stocks or random.random() < exit_probability: exiting_stocks.append(stock) # Remove exited stocks from portfolio current_portfolio = [s for s in current_portfolio if s not in exiting_stocks] # Calculate how many to add and select candidates need_to_add = 75 - len(current_portfolio) available_stocks = [s for s in current_week_stocks if s not in current_portfolio] added_stocks = random.sample(available_stocks, need_to_add) # Update portfolio current_portfolio.extend(added_stocks) # Sanity check assert len(current_portfolio) == 75, f"Week {week}: Portfolio size mismatch! Expected 75, got {len(current_portfolio)}"
内容的提问来源于stack exchange,提问作者Martin Richter
相关产品推荐
相关产品推荐

