def runbacktest(self): self.initengine() backtestfun = self.orderengine dates =…
- User
def run_backtest(self): self.init_engine() backtest_fun = self.order_engine dates = self.get_backtest_dates() rebalance_times = sorted(self.predictions.keys())
self.orders.clear() pre_datetime_key = None for date in tqdm(dates, desc="Daily Backtest Progress"): # Reset todays_bought_stocks at the start of each day backtest_fun.todays_bought_stocks = set() # Special handling for the very first day to initialize net value if not self.daily_net_value: self.net_value_init(date) for i, time in enumerate(rebalance_times): if time not in self.predictions or date not in self.predictions[time]: continue datetime_key = (date, time) # 1. Set correct prediction for the current time slot self.prediction = self.predictions[time] setattr(self.order_engine, 'prediction', self.prediction) # 2. Set correct trade price for the current time slot price_col = self._get_price_col_for_time(time) if price_col not in self.trade_prices_df.columns: print(f"Warning: Price column '{price_col}' not found for {time}. Skipping.") continue # Pivot the vwap data for the current time slot current_prices = self.trade_prices_df.pivot_table(index='date', columns='order_book_id', values=price_col) self.trade_price = current_prices.ffill() # 3. Generate order if pre_datetime_key is None: # First trade of the entire backtest tmp_order = self.gen_open_order(date) else: # Inject bought stocks to prevent selling them setattr(backtest_fun, 'todays_bought_stocks', backtest_fun.todays_bought_stocks) # The strategy needs the date of the last position to fetch predictions and prices. tmp_order = backtest_fun.gen_rebalance_order(pre_datetime_key[0]) if tmp_order is None or tmp_order.empty: pre_datetime_key = datetime_key continue # 4. Update todays_bought_stocks buy_orders = tmp_order[tmp_order['order_direction'] == 'Buy'] if not buy_orders.empty: backtest_fun.todays_bought_stocks.update(buy_orders['code'].tolist()) # 5. Update position and cash self.change_position(datetime_key, tmp_order, pre_datetime_key) tmp_order['tradeDate'] = date tmp_order['tradeTime'] = time self.orders[datetime_key] = tmp_order # This function now calculates the value change for this specific trade # and updates self.cash and self.available_assets self.calculate_intraday_snapshot(datetime_key, tmp_order, self.position[datetime_key]) # Update available assets for the next trade backtest_fun.available_assets = self.available_assets setattr(self.order_engine, 'available_assets', self.available_assets) pre_datetime_key = datetime_key # --- Simplified and Corrected EOD Logic --- # At the end of each day, always calculate the EOD net value based on the last known position # This correctly handles both trading and non-trading days. last_position_key = pre_datetime_key if pre_datetime_key else (list(self.position.keys())[-1] if self.position else None) if last_position_key: # Pop the opening snapshot for the day, which was added by net_value_init # This is only relevant if it's not the very first day of the backtest. if len(self.daily_net_value) > 1 and self.daily_net_value[-1]['date'] == date: self.daily_net_value.pop() self.calculate_eod_net_value(date, self.position[last_position_key]) elif self.daily_net_value: # Handle very first day if no trades occurred last_nv = self.daily_net_value[-1].copy() last_nv['date'] = date self.daily_net_value.append(last_nv) def calculate_intraday_snapshot(self, datetime_key, orders_df, position_df): # This function calculates the net value after a trade and updates cash. # It logs the snapshot to intraday_net_value. # It reuses the logic from the parent's calculate_daily_net_value but doesn't append to daily_net_value. date = datetime_key[0] cash_balance = self.cash daily_cost = 0 daily_revenue = 0 if not orders_df.empty: sell_orders = orders_df[orders_df['order_direction'] == 'Sell'] for _, order in sell_orders.iterrows(): code = order['code'] code = f'{code}.XSHG' if code.startswith('6') else f'{code}.XSHE' shares = order['order_quantity'] price = self.trade_price.loc[date, code] if pd.isna(price): price = self.quote_data.loc[date, code] if pd.isna(price): continue revenue = shares * price * (1 - self.close_commission - self.close_tax) daily_revenue += revenue buy_orders = orders_df[orders_df['order_direction'] == 'Buy'] for _, order in buy_orders.iterrows(): code = order['code'] code = f'{code}.XSHG' if code.startswith('6') else f'{code}.XSHE' shares = order['order_quantity'] price = self.trade_price.loc[date, code] if pd.isna(price): price = self.quote_data.loc[date, code] if pd.isna(price): continue cost = shares * price * (1 + self.open_commission) if cost > (cash_balance + daily_revenue - daily_cost): continue daily_cost += cost cash_balance -= daily_cost cash_balance += daily_revenue daily_position_value = 0 if not position_df.empty: for _, position in position_df.iterrows(): code = position['secID'] shares = position['position_quantity'] price = self.trade_price.loc[date, code] # Use current interval's price for snapshot if pd.isna(price): price = self.quote_data.loc[date, code] if pd.isna(price): continue daily_position_value += shares * price total_assets = cash_balance + daily_position_value self.intraday_net_value.append({ 'datetime': datetime_key, 'cash_balance': cash_balance, 'position_value': daily_position_value, 'total_assets': total_assets }) self.cash = cash_balance self.available_assets = total_assets * self.available_ratio 这个函数的逻辑有问题吗 Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.