Here's an enhanced and more robust version of your regress_and_forecast_from_series function. It includes:
- Better data validation and alignment
- Optional preprocessing steps: imputation, normalization/scaling, outlier handling
- Support for multiple regression/ML models, including scikit-learn and statsmodels
- Improved flexibility in model configuration
- Error handling and logging
✅ Updated Function: regress_and_forecast_from_series
from typing import Dict, Optional, Union, Any, List
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
from sklearn.linear_model import LinearRegression, Ridge, Lasso
from sklearn.ensemble import RandomForestRegressor
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.base import RegressorMixin
def regress_and_forecast_from_series(
series_dict: Dict[str, pd.Series],
formula: str,
future_row: Dict[str, float],
adjustment: float = 1.0,
max_year: Optional[int] = None,
year_index_filter: bool = True,
model_type: str = "ols", # 'ols', 'glm', 'linear', 'ridge', 'lasso', 'random_forest'
model_kwargs: Optional[Dict[str, Any]] = None,
preprocess_steps: Optional[List[str]] = None,
verbose: bool = False,
) -> float:
"""
Fit a regression or ML model from multiple aligned Series using a formula string and forecast a future value.
Parameters:
series_dict (dict[str, pd.Series]): Mapping of variable names to pandas Series.
formula (str): A formula string like 'y ~ x1 + x2'.
future_row (dict): Dictionary of future input values to forecast on.
adjustment (float): Multiplier applied to the prediction.
max_year (int): Optional max value to filter the index by (if datetime-like or integer index).
year_index_filter (bool): Whether to apply max_year filter on the index.
model_type (str): Model type: 'ols', 'glm', 'linear', 'ridge', 'lasso', 'random_forest'
model_kwargs (dict): Additional keyword arguments for the model constructor.
preprocess_steps (list): Preprocessing steps to apply before modeling.
Options: ['impute', 'scale', 'outlier_clip']
verbose (bool): If True, print intermediate info.
Returns:
float: The forecasted and adjusted result.
"""
# Validate inputs
if not all(isinstance(s, pd.Series) for s in series_dict.values()):
raise TypeError("All values in series_dict must be pandas Series.")
# Align indices
index = next(iter(series_dict.values())).index
for name, s in series_dict.items():
series_dict[name] = s.reindex(index)
# Combine into DataFrame
df = pd.concat(series_dict.values(), axis=1)
df.columns = series_dict.keys()
# Apply time filtering
if max_year is not None and year_index_filter:
if isinstance(df.index[0], (int, float, np.integer)):
df = df[df.index <= max_year]
elif np.issubdtype(df.index.dtype, np.datetime64):
df = df[df.index.year <= max_year]
else:
raise ValueError("Unsupported index type for max_year filtering.")
# Extract response variable
y_name = formula.split("~")[0].strip()
if y_name not in df.columns:
raise ValueError(f"Target variable '{y_name}' not found in provided data.")
# Prepare feature matrix and target
X = df.drop(columns=[y_name])
y = df[y_name]
# Data cleaning / preprocessing
preprocess_steps = preprocess_steps or []
model_kwargs = model_kwargs or {}
pipeline_steps = []
if "impute" in preprocess_steps:
pipeline_steps.append(("imputer", SimpleImputer(strategy="mean")))
if "scale" in preprocess_steps:
scaler = StandardScaler() if "standard" in preprocess_steps else MinMaxScaler()
pipeline_steps.append(("scaler", scaler))
if "outlier_clip" in preprocess_steps:
q = 0.99
upper_bounds = X.quantile(q)
lower_bounds = X.quantile(1 - q)
X = X.clip(lower=lower_bounds, upper=upper_bounds, axis=1)
# Build model
if model_type == "ols":
model = smf.ols(formula=formula, data=df).fit()
elif model_type == "glm":
model = smf.glm(formula=formula, data=df).fit()
elif model_type == "linear":
model = Pipeline(pipeline_steps + [("model", LinearRegression(**model_kwargs))])
model.fit(X, y)
elif model_type == "ridge":
model = Pipeline(pipeline_steps + [("model", Ridge(**model_kwargs))])
model.fit(X, y)
elif model_type == "lasso":
model = Pipeline(pipeline_steps + [("model", Lasso(**model_kwargs))])
model.fit(X, y)
elif model_type == "random_forest":
model = Pipeline(pipeline_steps + [("model", RandomForestRegressor(**model_kwargs))])
model.fit(X, y)
else:
raise ValueError(
f"Unknown model_type: {model_type}. "
f"Supported types: ols, glm, linear, ridge, lasso, random_forest"
)
# Forecast
future_df = pd.DataFrame([future_row])
if model_type in ["ols", "glm"]:
prediction = float(model.predict(future_df)) * adjustment
else:
prediction = float(model.predict(future_df)[0]) * adjustment
if verbose:
print("Model Summary:")
if hasattr(model, "summary"):
print(model.summary())
print(f"Prediction: {prediction}")
return prediction