import pandas as pd import numpy as np class WFAEngine: def __init__(self, data_df, train_window_days=756, test_window_days=252): """ Walk-Forward Analysis Engine. :param data_df: pd.DataFrame with all historical data. :param train_window_days: Number of days to train on (e.g., 3 years ~ 756 days). :param test_window_days: Number of days to test on (e.g., 1 year ~ 252 days). """ self.df = data_df self.train_window_days = train_window_days self.test_window_days = test_window_days def generate_windows(self): """ Generator yielding (train_df, test_df) chunks. Moves forward by test_window_days each step. """ start_idx = 0 total_len = len(self.df) while start_idx + self.train_window_days < total_len: train_end_idx = start_idx + self.train_window_days test_end_idx = min(train_end_idx + self.test_window_days, total_len) train_df = self.df.iloc[0:train_end_idx] test_df = self.df.iloc[train_end_idx:test_end_idx] # Print window info train_start, train_end = train_df.index[0].date(), train_df.index[-1].date() test_start, test_end = test_df.index[0].date(), test_df.index[-1].date() yield train_df, test_df # Advance step start_idx += self.test_window_days def run(self, policy_wrapper, start_amount=1_000_000, max_windows=None): """ Run the fully stitched OOS test out. :param policy_wrapper: A class/object that implements .fit(train_df) and .predict(test_df). :param max_windows: If set, only runs the LAST N windows. :return: (stitched_portfolio_series, stitched_holdings_df) """ stitched_values = [] stitched_holdings = [] current_amount = start_amount total_all_windows = list(self.generate_windows()) total_count = len(total_all_windows) all_windows = total_all_windows if max_windows is not None: all_windows = all_windows[-max_windows:] for idx, (train_df, test_df) in enumerate(all_windows): train_start, train_end = train_df.index[0].date(), train_df.index[-1].date() test_start, test_end = test_df.index[0].date(), test_df.index[-1].date() # Calculate backward index: 1 is the latest window, 2 is the one before, etc. # absolute_idx = total_count - len(all_windows) + idx # backward_idx = total_count - absolute_idx # Simplified: current_absolute_idx = total_count - len(all_windows) + idx backward_idx = total_count - current_absolute_idx print(f"WFA Fold {backward_idx} (Latest-{backward_idx-1}) -> Train: {train_start} to {train_end} | Test (OOS): {test_start} to {test_end}") policy_wrapper.fit(train_df, window_idx=backward_idx) test_values, test_holdings = policy_wrapper.predict(test_df, current_amount) if len(test_values) > 0: # Append to overall stitched results stitched_values.append(test_values) stitched_holdings.append(test_holdings) # Carry forward the capital current_amount = test_values.iloc[-1] if not stitched_values: raise ValueError("No windows generated. Check dataframe length and window settings.") full_stitched_values = pd.concat(stitched_values) full_stitched_holdings = pd.concat(stitched_holdings) # Prevent duplicated dates if test_window stepping overlaps, though code prevents it by step full_stitched_values = full_stitched_values[~full_stitched_values.index.duplicated(keep='first')] full_stitched_holdings = full_stitched_holdings[~full_stitched_holdings.index.duplicated(keep='first')] return full_stitched_values, full_stitched_holdings