executing-plans
executing-plans
Use when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available
ds-time-series-forecasting"Implements ARIMA, exponential smoothing, state-space models, LSTM networks and deep learning methods for temporal prediction"
Independent GitHub snapshot · Automated classification · Original documentation governs
name: ds-time-series-forecasting compatibility: opencode completeness: 95 content-types:
Comprehensive guide to time series forecasting in machine learning and data science workflows.
Time Series Forecasting is a critical component of the machine learning workflow. This skill covers:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.holtwinters import ExponentialSmoothing
from sklearn.metrics import mean_absolute_error, mean_squared_error
def basic_forecasting_pipeline(data: pd.Series, forecast_horizon: int = 10) -> dict:
"""
Demonstrates a basic time series forecasting pipeline using Exponential Smoothing.
"""
if data is None or data.empty:
raise ValueError("Input data cannot be None or empty")
if not isinstance(data.index, pd.DatetimeIndex):
data.index = pd.date_range(start="2020-01-01", periods=len(data), freq="D")
split_idx = int(len(data) * 0.8)
train_data = data.iloc[:split_idx]
test_data = data.iloc[split_idx:]
model = ExponentialSmoothing(
train_data,
trend='add',
seasonal='add',
seasonal_periods=7
)
fitted_model = model.fit(optimized=True)
forecasts = fitted_model.forecast(forecast_horizon)
test_forecasts = fitted_model.predict(start=test_data.index[0], end=test_data.index[-1])
mae = mean_absolute_error(test_data, test_forecasts)
rmse = np.sqrt(mean_squared_error(test_data, test_forecasts))
return {
'forecasts': forecasts
'metrics': {'mae': mae, 'rmse': rmse}
'fitted_model': fitted_model
}
import logging
import pandas as pd
import numpy as np
from typing import Any, Dict, Optional
from statsmodels.tsa.arima.model import ARIMA
from sklearn.metrics import mean_absolute_error, mean_squared_error
logger = logging.getLogger(__name__)
class TimeSeriesForecasting:
"""Production-grade time series forecasting class with ARIMA."""
def __init__(self, order: tuple = (1, 1, 1), forecast_steps: int = 10):
self.order = order
self.forecast_steps = forecast_steps
self.model = None
self.history = None
def _validate_data(self, data: pd.DataFrame) -> pd.Series:
if data is None or data.empty:
raise ValueError("Input data cannot be None or empty")
if not isinstance(data.index, pd.DatetimeIndex):
raise ValueError("Data index must be a DatetimeIndex")
return data.squeeze()
def fit(self, data: pd.DataFrame) -> 'TimeSeriesForecasting':
"""Fit the ARIMA model on historical data."""
self.history = self._validate_data(data)
try:
self.model = ARIMA(self.history, order=self.order)
self.fitted_model = self.model.fit()
logger.info(f"Model fitted successfully with order {self.order}")
except Exception as e:
logger.error(f"Failed to fit model: {e}")
raise RuntimeError("Model fitting failed") from e
return self
def predict(self, steps: Optional[int] = None) -> pd.Series:
"""Generate future forecasts."""
if self.model is None:
raise RuntimeError("Model must be fitted before prediction")
horizon = steps or self.forecast_steps
return self.fitted_model.forecast(steps=horizon)
def evaluate(self, test_data: pd.DataFrame) -> Dict[str, float]:
"""Evaluate model performance on held-out test data."""
test_series = self._validate_data(test_data)
test_forecasts = self.fitted_model.predict(
start=test_series.index[0],
end=test_series.index[-1]
)
mae = mean_absolute_error(test_series, test_forecasts)
rmse = np.sqrt(mean_squared_error(test_series, test_forecasts))
return {'mae': mae, 'rmse': rmse}
| Pitfall | Problem | Solution | |
Authoritative documentation links for this skill's domain. The model follows markdown links at load time to resolve external references and inline content.