Skip to content

Forecasting

forecasting


Assembly: Mathy Filename: forecasting.py Author: Terry D. Eppler Created: 08-31-2025

Last Modified By: Terry D. Eppler Last Modified On: 08-31-2025


 forecasting.py
 Copyright ©  2023  Terry Eppler

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

You can contact me at: terryeppler@gmail.com or eppler.terry@epa.gov

Provides time-series forecasting, cross-validation, lag-feature modeling, ARIMA, SARIMA, gradient-boosted lag-regression, and quantile lag-regression classes for Mathy forecasting workflows. The module standardizes training, projection, scoring, and residual-diagnostic operations across statsmodels and sklearn estimators.

TimeSeries

Share time-series state.

Purpose

Provides the base runtime attributes used by forecasting wrappers that train on ordered observations, store fitted target values, and retain the most recent forecast output. The class supplies a minimal common state contract for concrete time-series estimators.

Attributes:

Name Type Description
training_data Optional[ndarray]

Feature matrix or lagged design matrix used for training.

tranining_values Optional[ndarray]

Target values aligned to the training matrix.

prediction Optional[ndarray]

Most recent forecast or projection generated by the model.

Source code in forecasting.py
class TimeSeries( ):
	"""Share time-series state.

	Purpose:
	    Provides the base runtime attributes used by forecasting wrappers that train on
	    ordered observations, store fitted target values, and retain the most recent
	    forecast output. The class supplies a minimal common state contract for concrete
	    time-series estimators.

	Attributes:
	    training_data (Optional[np.ndarray]): Feature matrix or lagged design matrix used
	                                          for training.
	    tranining_values (Optional[np.ndarray]): Target values aligned to the training
	                                             matrix.
	    prediction (Optional[np.ndarray]): Most recent forecast or projection generated by
	                                       the model."""
	training_data: Optional[ np.ndarray ]
	tranining_values: Optional[ np.ndarray ]
	prediction: Optional[ np.ndarray ]

	def __init__( self ):
		"""Initializes a `TimeSeries` instance and its runtime state.

		Purpose:
		    Initializes a `TimeSeries` instance and its runtime state.

		Returns:
		    None: This method initializes the object and does not return a value."""
		self.training_data = None
		self.tranining_values = None
		self.prediction = None

ExpandingWindow

Create expanding-window validation splits.

Purpose

Generates forward-chaining train/test indices for time-series validation where each successive training window expands over time and each test window remains fixed in size. The splitter preserves temporal order, supports optional gaps, and exposes sklearn-style split-count and visualization helpers.

Attributes:

Name Type Description
initial_window int

Number of observations included in the first training window.

test_window int

Number of observations included in each testing window.

max_splits Optional[int]

Maximum number of splits produced by the generator.

n_splits Optional[int]

sklearn-style split count override.

max_train_size Optional[int]

Optional cap on the length of each training window.

gap int

Number of observations skipped between each train and test segment.

Source code in forecasting.py
class ExpandingWindow( ):
	"""Create expanding-window validation splits.

	Purpose:
	    Generates forward-chaining train/test indices for time-series validation where each
	    successive training window expands over time and each test window remains fixed in
	    size. The splitter preserves temporal order, supports optional gaps, and exposes
	    sklearn-style split-count and visualization helpers.

	Attributes:
	    initial_window (int): Number of observations included in the first training window.
	    test_window (int): Number of observations included in each testing window.
	    max_splits (Optional[int]): Maximum number of splits produced by the generator.
	    n_splits (Optional[int]): sklearn-style split count override.
	    max_train_size (Optional[int]): Optional cap on the length of each training window.
	    gap (int): Number of observations skipped between each train and test segment."""
	initial_window: int
	test_window: int
	max_splits: Optional[ int ]
	n_splits: Optional[ int ]
	max_train_size: Optional[ int ]
	gap: int

	def __init__( self, initial: int=30, windows: int=10, splits: int | None=None,
		n_splits: int | None=None, max_train_size: int | None=None, test_size: int | None=None,
		gap: int=0 ) -> None:
		"""Initialize expanding-window splitter.

		Purpose:
		    Configures the first training-window size, test-window size, split limit, optional
		    train-size cap, sklearn-style split count, and temporal gap used to produce
		    forward-chaining validation indices.

		Args:
		    initial (int): Number of observations in the first training window.
		    windows (int): Number of observations in each testing window.
		    splits (int | None): Legacy maximum number of expanding-window splits.
		    n_splits (int | None): sklearn-style maximum number of validation splits.
		    max_train_size (int | None): Optional cap applied to each training-window length.
		    test_size (int | None): Optional sklearn-style test-window size override.
		    gap (int): Number of observations skipped between train and test windows.

		Returns:
		    None: This method initializes the object and does not return a value."""
		self.initial_window = int( initial )
		self.test_window = int( test_size ) if test_size is not None else int( windows )
		self.max_splits = int( splits ) if splits is not None else None
		self.n_splits = int( n_splits ) if n_splits is not None else self.max_splits
		self.max_train_size = int( max_train_size ) if max_train_size is not None else None
		self.gap = int( gap )

	def split( self, series: np.ndarray, y: np.ndarray = None,
			groups: np.ndarray = None ) -> Generator[ Tuple[ np.ndarray, np.ndarray ], None, None ]:
		"""Yield expanding-window splits.

		Purpose:
		    Generates chronological train and test index arrays from a one-dimensional
		    time-series input using the configured expanding-window rules.

		Args:
		    series (np.ndarray): Ordered observations used to determine split boundaries.
		    y (np.ndarray): Optional target array accepted for sklearn splitter compatibility.
		    groups (np.ndarray): Optional group labels accepted for sklearn splitter
		                         compatibility.

		Returns:
		    Generator[Tuple[np.ndarray, np.ndarray], None, None]: Generator[Tuple[np.ndarray,
		                                                          np.ndarray], None, None]
		                                                          returned by the forecasting
		                                                          operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails.
		    ValueError: Raised when the `split` operation cannot complete."""
		try:
			throw_if( 'series', series )
			values = np.asarray( series ).reshape( -1 )
			n_obs = len( values )

			if self.initial_window < 1:
				raise ValueError( 'Argument "initial" must be greater than zero.' )

			if self.test_window < 1:
				raise ValueError( 'Argument "test_size" must be greater than zero.' )

			if self.gap < 0:
				raise ValueError( 'Argument "gap" cannot be negative.' )

			if self.max_train_size is not None and self.max_train_size < 1:
				raise ValueError( 'Argument "max_train_size" must be greater than zero.' )

			if self.n_splits is not None and self.n_splits < 1:
				raise ValueError( 'Argument "n_splits" must be greater than zero.' )

			if self.initial_window + self.gap + self.test_window > n_obs:
				message = (
						'Argument "series" does not contain enough observations for the '
						'requested initial window, gap, and test size.'
				)
				raise ValueError( message )

			split_count = 0
			train_stop = self.initial_window
			while (train_stop + self.gap + self.test_window) <= n_obs:
				if self.max_train_size is None:
					train_start = 0
				else:
					train_start = max( 0, train_stop - self.max_train_size )

				test_start = train_stop + self.gap
				test_stop = test_start + self.test_window
				train_idx = np.arange( train_start, train_stop, dtype=int )
				test_idx = np.arange( test_start, test_stop, dtype=int )

				if len( train_idx ) == 0 or len( test_idx ) == 0:
					break

				yield train_idx, test_idx
				split_count += 1
				if self.n_splits is not None and split_count >= self.n_splits:
					break

				train_stop = test_stop
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'ExpandingWindow'
			exception.method = 'split( self, *args ) -> Generator[Tuple[np.ndarray, np.ndarray], None, None]'
			Logger( ).write( exception )
			raise exception

	def get_splits( self, series: np.ndarray ) -> list[ Tuple[ np.ndarray, np.ndarray ] ]:
		"""Materialize expanding-window splits.

		Purpose:
		    Collects all expanding-window train/test index pairs into a list for inspection,
		    repeated use, or plotting.

		Args:
		    series (np.ndarray): Ordered observations used to determine split boundaries.

		Returns:
		    list[Tuple[np.ndarray, np.ndarray]]: list[Tuple[np.ndarray, np.ndarray]] returned by
		                                         the forecasting operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails."""
		try:
			throw_if( 'series', series )
			return list( self.split( series ) )
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'ExpandingWindow'
			exception.method = 'get_splits( self, series: np.ndarray ) -> list[Tuple[np.ndarray, np.ndarray]]'
			Logger( ).write( exception )
			raise exception

	def get_n_splits( self, series: Optional[ np.ndarray ] = None,
			y: Optional[ np.ndarray ] = None, groups: Optional[ np.ndarray ] = None ) -> int:
		"""Count expanding-window splits.

		Purpose:
		    Returns the number of validation splits that the expanding-window splitter will
		    produce for the supplied series and configuration.

		Args:
		    series (Optional[np.ndarray]): Optional ordered observations used to calculate
		                                   available splits.
		    y (Optional[np.ndarray]): Optional target array accepted for sklearn splitter
		                              compatibility.
		    groups (Optional[np.ndarray]): Optional group labels accepted for sklearn splitter
		                                   compatibility.

		Returns:
		    int: int returned by the forecasting operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails.
		    ValueError: Raised when the `get_n_splits` operation cannot complete."""
		try:
			if series is None:
				if self.n_splits is not None:
					return int( self.n_splits )

				raise ValueError( 'Argument "series" is required when the number of splits is not '
					'explicitly configured.' )

			throw_if( 'series', series )
			return len( list( self.split( series ) ) )
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'ExpandingWindow'
			exception.method = 'get_n_splits( self, *args ) -> int'
			Logger( ).write( exception )
			raise exception

	def visualize( self, series: np.ndarray ) -> plt.Figure | None:
		"""Visualize expanding-window splits.

		Purpose:
		    Builds a matplotlib figure showing the chronological train and test windows produced
		    by the expanding-window splitter.

		Args:
		    series (np.ndarray): Ordered observations used to generate the split visualization.

		Returns:
		    plt.Figure | None: plt.Figure | None returned by the forecasting operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails.
		    ValueError: Raised when the `visualize` operation cannot complete."""
		try:
			throw_if( 'series', series )
			values = np.asarray( series, dtype=float ).reshape( -1 )
			splits = self.get_splits( values )
			if not splits:
				raise ValueError( 'No train/test splits were generated for visualization.' )

			n_splits = len( splits )
			fig, axes = plt.subplots( n_splits, 1, figsize=(10, 2.5 * n_splits) )
			if n_splits == 1:
				axes = [ axes ]

			x_axis = np.arange( len( values ) )
			for i, (train_idx, test_idx) in enumerate( splits ):
				axis = axes[ i ]
				axis.plot( x_axis[ train_idx ], values[ train_idx ], label='Train' )
				axis.plot( x_axis[ test_idx ], values[ test_idx ], label='Test' )
				axis.set_title( f'Split {i + 1}' )
				axis.legend( )
				axis.grid( True, alpha=0.25 )

			plt.tight_layout( )
			return fig
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'ExpandingWindow'
			exception.method = 'visualize( self, series: np.ndarray ) -> plt.Figure | None'
			Logger( ).write( exception )
			raise exception

split

split(
    series: ndarray,
    y: ndarray = None,
    groups: ndarray = None,
) -> Generator[Tuple[np.ndarray, np.ndarray], None, None]

Yield expanding-window splits.

Purpose

Generates chronological train and test index arrays from a one-dimensional time-series input using the configured expanding-window rules.

Parameters:

Name Type Description Default
series ndarray

Ordered observations used to determine split boundaries.

required
y ndarray

Optional target array accepted for sklearn splitter compatibility.

None
groups ndarray

Optional group labels accepted for sklearn splitter compatibility.

None

Returns:

Type Description
None

Generator[Tuple[np.ndarray, np.ndarray], None, None]: Generator[Tuple[np.ndarray, np.ndarray], None, None] returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

ValueError

Raised when the split operation cannot complete.

Source code in forecasting.py
def split( self, series: np.ndarray, y: np.ndarray = None,
		groups: np.ndarray = None ) -> Generator[ Tuple[ np.ndarray, np.ndarray ], None, None ]:
	"""Yield expanding-window splits.

	Purpose:
	    Generates chronological train and test index arrays from a one-dimensional
	    time-series input using the configured expanding-window rules.

	Args:
	    series (np.ndarray): Ordered observations used to determine split boundaries.
	    y (np.ndarray): Optional target array accepted for sklearn splitter compatibility.
	    groups (np.ndarray): Optional group labels accepted for sklearn splitter
	                         compatibility.

	Returns:
	    Generator[Tuple[np.ndarray, np.ndarray], None, None]: Generator[Tuple[np.ndarray,
	                                                          np.ndarray], None, None]
	                                                          returned by the forecasting
	                                                          operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails.
	    ValueError: Raised when the `split` operation cannot complete."""
	try:
		throw_if( 'series', series )
		values = np.asarray( series ).reshape( -1 )
		n_obs = len( values )

		if self.initial_window < 1:
			raise ValueError( 'Argument "initial" must be greater than zero.' )

		if self.test_window < 1:
			raise ValueError( 'Argument "test_size" must be greater than zero.' )

		if self.gap < 0:
			raise ValueError( 'Argument "gap" cannot be negative.' )

		if self.max_train_size is not None and self.max_train_size < 1:
			raise ValueError( 'Argument "max_train_size" must be greater than zero.' )

		if self.n_splits is not None and self.n_splits < 1:
			raise ValueError( 'Argument "n_splits" must be greater than zero.' )

		if self.initial_window + self.gap + self.test_window > n_obs:
			message = (
					'Argument "series" does not contain enough observations for the '
					'requested initial window, gap, and test size.'
			)
			raise ValueError( message )

		split_count = 0
		train_stop = self.initial_window
		while (train_stop + self.gap + self.test_window) <= n_obs:
			if self.max_train_size is None:
				train_start = 0
			else:
				train_start = max( 0, train_stop - self.max_train_size )

			test_start = train_stop + self.gap
			test_stop = test_start + self.test_window
			train_idx = np.arange( train_start, train_stop, dtype=int )
			test_idx = np.arange( test_start, test_stop, dtype=int )

			if len( train_idx ) == 0 or len( test_idx ) == 0:
				break

			yield train_idx, test_idx
			split_count += 1
			if self.n_splits is not None and split_count >= self.n_splits:
				break

			train_stop = test_stop
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'ExpandingWindow'
		exception.method = 'split( self, *args ) -> Generator[Tuple[np.ndarray, np.ndarray], None, None]'
		Logger( ).write( exception )
		raise exception

get_splits

get_splits(
    series: ndarray,
) -> list[Tuple[np.ndarray, np.ndarray]]

Materialize expanding-window splits.

Purpose

Collects all expanding-window train/test index pairs into a list for inspection, repeated use, or plotting.

Parameters:

Name Type Description Default
series ndarray

Ordered observations used to determine split boundaries.

required

Returns:

Type Description
list[Tuple[ndarray, ndarray]]

list[Tuple[np.ndarray, np.ndarray]]: list[Tuple[np.ndarray, np.ndarray]] returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

Source code in forecasting.py
def get_splits( self, series: np.ndarray ) -> list[ Tuple[ np.ndarray, np.ndarray ] ]:
	"""Materialize expanding-window splits.

	Purpose:
	    Collects all expanding-window train/test index pairs into a list for inspection,
	    repeated use, or plotting.

	Args:
	    series (np.ndarray): Ordered observations used to determine split boundaries.

	Returns:
	    list[Tuple[np.ndarray, np.ndarray]]: list[Tuple[np.ndarray, np.ndarray]] returned by
	                                         the forecasting operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails."""
	try:
		throw_if( 'series', series )
		return list( self.split( series ) )
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'ExpandingWindow'
		exception.method = 'get_splits( self, series: np.ndarray ) -> list[Tuple[np.ndarray, np.ndarray]]'
		Logger( ).write( exception )
		raise exception

get_n_splits

get_n_splits(
    series: Optional[ndarray] = None,
    y: Optional[ndarray] = None,
    groups: Optional[ndarray] = None,
) -> int

Count expanding-window splits.

Purpose

Returns the number of validation splits that the expanding-window splitter will produce for the supplied series and configuration.

Parameters:

Name Type Description Default
series Optional[ndarray]

Optional ordered observations used to calculate available splits.

None
y Optional[ndarray]

Optional target array accepted for sklearn splitter compatibility.

None
groups Optional[ndarray]

Optional group labels accepted for sklearn splitter compatibility.

None

Returns:

Name Type Description
int int

int returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

ValueError

Raised when the get_n_splits operation cannot complete.

Source code in forecasting.py
def get_n_splits( self, series: Optional[ np.ndarray ] = None,
		y: Optional[ np.ndarray ] = None, groups: Optional[ np.ndarray ] = None ) -> int:
	"""Count expanding-window splits.

	Purpose:
	    Returns the number of validation splits that the expanding-window splitter will
	    produce for the supplied series and configuration.

	Args:
	    series (Optional[np.ndarray]): Optional ordered observations used to calculate
	                                   available splits.
	    y (Optional[np.ndarray]): Optional target array accepted for sklearn splitter
	                              compatibility.
	    groups (Optional[np.ndarray]): Optional group labels accepted for sklearn splitter
	                                   compatibility.

	Returns:
	    int: int returned by the forecasting operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails.
	    ValueError: Raised when the `get_n_splits` operation cannot complete."""
	try:
		if series is None:
			if self.n_splits is not None:
				return int( self.n_splits )

			raise ValueError( 'Argument "series" is required when the number of splits is not '
				'explicitly configured.' )

		throw_if( 'series', series )
		return len( list( self.split( series ) ) )
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'ExpandingWindow'
		exception.method = 'get_n_splits( self, *args ) -> int'
		Logger( ).write( exception )
		raise exception

visualize

visualize(series: ndarray) -> plt.Figure | None

Visualize expanding-window splits.

Purpose

Builds a matplotlib figure showing the chronological train and test windows produced by the expanding-window splitter.

Parameters:

Name Type Description Default
series ndarray

Ordered observations used to generate the split visualization.

required

Returns:

Type Description
Figure | None

plt.Figure | None: plt.Figure | None returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

ValueError

Raised when the visualize operation cannot complete.

Source code in forecasting.py
def visualize( self, series: np.ndarray ) -> plt.Figure | None:
	"""Visualize expanding-window splits.

	Purpose:
	    Builds a matplotlib figure showing the chronological train and test windows produced
	    by the expanding-window splitter.

	Args:
	    series (np.ndarray): Ordered observations used to generate the split visualization.

	Returns:
	    plt.Figure | None: plt.Figure | None returned by the forecasting operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails.
	    ValueError: Raised when the `visualize` operation cannot complete."""
	try:
		throw_if( 'series', series )
		values = np.asarray( series, dtype=float ).reshape( -1 )
		splits = self.get_splits( values )
		if not splits:
			raise ValueError( 'No train/test splits were generated for visualization.' )

		n_splits = len( splits )
		fig, axes = plt.subplots( n_splits, 1, figsize=(10, 2.5 * n_splits) )
		if n_splits == 1:
			axes = [ axes ]

		x_axis = np.arange( len( values ) )
		for i, (train_idx, test_idx) in enumerate( splits ):
			axis = axes[ i ]
			axis.plot( x_axis[ train_idx ], values[ train_idx ], label='Train' )
			axis.plot( x_axis[ test_idx ], values[ test_idx ], label='Test' )
			axis.set_title( f'Split {i + 1}' )
			axis.legend( )
			axis.grid( True, alpha=0.25 )

		plt.tight_layout( )
		return fig
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'ExpandingWindow'
		exception.method = 'visualize( self, series: np.ndarray ) -> plt.Figure | None'
		Logger( ).write( exception )
		raise exception

TimeSeriesSpliter

Create fixed-window time-series validation splits.

Purpose

Produces sklearn-style time-series cross-validation indices using a requested number of splits, optional training-window cap, optional test-window size, and optional temporal gap. The splitter maintains chronological ordering and supports split materialization and visualization for model-validation workflows.

Attributes:

Name Type Description
n_splits int

Number of train/test partitions generated for time-series validation.

max_train_size Optional[int]

Optional cap on each training-window length.

test_size Optional[int]

Optional number of observations in each test segment.

gap int

Number of observations skipped between train and test segments.

Source code in forecasting.py
class TimeSeriesSpliter( ):
	"""Create fixed-window time-series validation splits.

	Purpose:
	    Produces sklearn-style time-series cross-validation indices using a requested number
	    of splits, optional training-window cap, optional test-window size, and optional
	    temporal gap. The splitter maintains chronological ordering and supports split
	    materialization and visualization for model-validation workflows.

	Attributes:
	    n_splits (int): Number of train/test partitions generated for time-series
	                    validation.
	    max_train_size (Optional[int]): Optional cap on each training-window length.
	    test_size (Optional[int]): Optional number of observations in each test segment.
	    gap (int): Number of observations skipped between train and test segments."""
	n_splits: int
	max_train_size: Optional[ int ]
	test_size: Optional[ int ]
	gap: int

	def __init__( self, splits: int = 5, max_train_size: Optional[ int ] = None,
			test_size: Optional[ int ] = None, gap: int = 0 ) -> None:
		"""Initialize time-series splitter.

		Purpose:
		    Configures the number of chronological splits, optional maximum training size,
		    optional fixed test size, and temporal gap used by the fixed-window splitter.

		Args:
		    splits (int): Number of chronological validation splits.
		    max_train_size (Optional[int]): Optional cap applied to each training-window length.
		    test_size (Optional[int]): Optional number of observations in each testing window.
		    gap (int): Number of observations skipped between train and test windows.

		Returns:
		    None: This method initializes the object and does not return a value."""
		self.n_splits = int( splits )
		self.max_train_size = max_train_size
		self.test_size = test_size
		self.gap = int( gap )

	def split( self, series: np.ndarray, y: np.ndarray = None,
			groups: np.ndarray = None ) -> Generator[ Tuple[ np.ndarray, np.ndarray ], None, None ]:
		"""Yield time-series splits.

		Purpose:
		    Generates chronological train and test index arrays from a one-dimensional
		    time-series input using the configured fixed-window split rules.

		Args:
		    series (np.ndarray): Ordered observations used to determine split boundaries.
		    y (np.ndarray): Optional target array accepted for sklearn splitter compatibility.
		    groups (np.ndarray): Optional group labels accepted for sklearn splitter
		                         compatibility.

		Returns:
		    Generator[Tuple[np.ndarray, np.ndarray], None, None]: Generator[Tuple[np.ndarray,
		                                                          np.ndarray], None, None]
		                                                          returned by the forecasting
		                                                          operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails.
		    ValueError: Raised when the `split` operation cannot complete."""
		try:
			throw_if( 'series', series )

			values = np.asarray( series ).reshape( -1 )
			n_samples = len( values )

			if self.n_splits < 2:
				raise ValueError( 'Argument "splits" must be at least 2.' )

			if self.gap < 0:
				raise ValueError( 'Argument "gap" cannot be negative.' )

			if self.max_train_size is not None and self.max_train_size < 1:
				raise ValueError( 'Argument "max_train_size" must be greater than zero.' )

			if self.test_size is None:
				computed_test_size = n_samples // (self.n_splits + 1)
			else:
				computed_test_size = int( self.test_size )

			if computed_test_size < 1:
				raise ValueError( 'Argument "test_size" must be greater than zero.' )

			required = self.n_splits * computed_test_size + self.gap
			if required >= n_samples:
				raise ValueError(
					'The series does not contain enough observations for the '
					'requested number of splits, test size, and gap.'
				)

			test_starts = range( n_samples - (self.n_splits * computed_test_size),
				n_samples, computed_test_size )

			for test_start in test_starts:
				train_end = test_start - self.gap

				if train_end <= 0:
					raise ValueError(
						'The requested gap leaves no observations available for training.' )

				if self.max_train_size is not None and self.max_train_size < train_end:
					train_start = train_end - self.max_train_size
				else:
					train_start = 0

				train_index = np.arange( train_start, train_end, dtype=int )
				test_index = np.arange( test_start,
					min( test_start + computed_test_size, n_samples ), dtype=int )

				if len( train_index ) == 0 or len( test_index ) == 0:
					continue

				yield train_index, test_index
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'TimeSeriesSpliter'
			exception.method = 'split( self, *args ) -> Generator[Tuple[np.ndarray, np.ndarray], None, None]'
			Logger( ).write( exception )
			raise exception

	def get_n_splits( self, series: np.ndarray=None, y: np.ndarray=None,
		groups: np.ndarray=None ) -> int | None:
		"""Count time-series splits.

		Purpose:
		    Returns the configured number of chronological validation splits available for the
		    supplied series and splitter configuration.

		Args:
		    series (np.ndarray): Optional ordered observations used to validate split
		                         availability.
		    y (np.ndarray): Optional target array accepted for sklearn splitter compatibility.
		    groups (np.ndarray): Optional group labels accepted for sklearn splitter
		                         compatibility.

		Returns:
		    int | None: int | None returned by the forecasting operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails."""
		try:
			return self.n_splits
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'TimeSeriesSpliter'
			exception.method = 'get_n_splits( self, *args ) -> int | None'
			Logger( ).write( exception )
			raise exception

	def get_splits( self, series: np.ndarray ) -> list[ Tuple[ np.ndarray, np.ndarray ] ]:
		"""Materialize time-series splits.

		Purpose:
		    Collects all chronological train/test index pairs into a list for inspection,
		    repeated use, or plotting.

		Args:
		    series (np.ndarray): Ordered observations used to determine split boundaries.

		Returns:
		    list[Tuple[np.ndarray, np.ndarray]]: list[Tuple[np.ndarray, np.ndarray]] returned by
		                                         the forecasting operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails."""
		try:
			throw_if( 'series', series )
			return list( self.split( series ) )
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'TimeSeriesSpliter'
			exception.method = 'get_splits( self, series: np.ndarray ) -> list[Tuple[np.ndarray, np.ndarray]]'
			Logger( ).write( exception )
			raise exception

	def visualize( self, series: np.ndarray ) -> plt.Figure | None:
		"""Visualize time-series splits.

		Purpose:
		    Builds a matplotlib figure showing the chronological train and test windows produced
		    by the fixed-window splitter.

		Args:
		    series (np.ndarray): Ordered observations used to generate the split visualization.

		Returns:
		    plt.Figure | None: plt.Figure | None returned by the forecasting operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails.
		    ValueError: Raised when the `visualize` operation cannot complete."""
		try:
			throw_if( 'series', series )
			values = np.asarray( series, dtype=float ).reshape( -1 )
			splits = self.get_splits( values )

			if not splits:
				raise ValueError( 'No time-series splits were generated.' )

			fig, axes = plt.subplots( len( splits ), 1, figsize=(10, 2.5 * len( splits )) )
			if len( splits ) == 1:
				axes = [ axes ]

			x_axis = np.arange( len( values ) )
			for i, (train_idx, test_idx) in enumerate( splits ):
				axis = axes[ i ]
				axis.plot( x_axis[ train_idx ], values[ train_idx ], label='Train' )
				axis.plot( x_axis[ test_idx ], values[ test_idx ], label='Test' )
				axis.set_title( f'Split {i + 1}' )
				axis.grid( True, alpha=0.25 )
				axis.legend( )

			plt.tight_layout( )
			return fig
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'TimeSeriesSpliter'
			exception.method = 'visualize( self, series: np.ndarray ) -> plt.Figure | None'
			Logger( ).write( exception )
			raise exception

split

split(
    series: ndarray,
    y: ndarray = None,
    groups: ndarray = None,
) -> Generator[Tuple[np.ndarray, np.ndarray], None, None]

Yield time-series splits.

Purpose

Generates chronological train and test index arrays from a one-dimensional time-series input using the configured fixed-window split rules.

Parameters:

Name Type Description Default
series ndarray

Ordered observations used to determine split boundaries.

required
y ndarray

Optional target array accepted for sklearn splitter compatibility.

None
groups ndarray

Optional group labels accepted for sklearn splitter compatibility.

None

Returns:

Type Description
None

Generator[Tuple[np.ndarray, np.ndarray], None, None]: Generator[Tuple[np.ndarray, np.ndarray], None, None] returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

ValueError

Raised when the split operation cannot complete.

Source code in forecasting.py
def split( self, series: np.ndarray, y: np.ndarray = None,
		groups: np.ndarray = None ) -> Generator[ Tuple[ np.ndarray, np.ndarray ], None, None ]:
	"""Yield time-series splits.

	Purpose:
	    Generates chronological train and test index arrays from a one-dimensional
	    time-series input using the configured fixed-window split rules.

	Args:
	    series (np.ndarray): Ordered observations used to determine split boundaries.
	    y (np.ndarray): Optional target array accepted for sklearn splitter compatibility.
	    groups (np.ndarray): Optional group labels accepted for sklearn splitter
	                         compatibility.

	Returns:
	    Generator[Tuple[np.ndarray, np.ndarray], None, None]: Generator[Tuple[np.ndarray,
	                                                          np.ndarray], None, None]
	                                                          returned by the forecasting
	                                                          operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails.
	    ValueError: Raised when the `split` operation cannot complete."""
	try:
		throw_if( 'series', series )

		values = np.asarray( series ).reshape( -1 )
		n_samples = len( values )

		if self.n_splits < 2:
			raise ValueError( 'Argument "splits" must be at least 2.' )

		if self.gap < 0:
			raise ValueError( 'Argument "gap" cannot be negative.' )

		if self.max_train_size is not None and self.max_train_size < 1:
			raise ValueError( 'Argument "max_train_size" must be greater than zero.' )

		if self.test_size is None:
			computed_test_size = n_samples // (self.n_splits + 1)
		else:
			computed_test_size = int( self.test_size )

		if computed_test_size < 1:
			raise ValueError( 'Argument "test_size" must be greater than zero.' )

		required = self.n_splits * computed_test_size + self.gap
		if required >= n_samples:
			raise ValueError(
				'The series does not contain enough observations for the '
				'requested number of splits, test size, and gap.'
			)

		test_starts = range( n_samples - (self.n_splits * computed_test_size),
			n_samples, computed_test_size )

		for test_start in test_starts:
			train_end = test_start - self.gap

			if train_end <= 0:
				raise ValueError(
					'The requested gap leaves no observations available for training.' )

			if self.max_train_size is not None and self.max_train_size < train_end:
				train_start = train_end - self.max_train_size
			else:
				train_start = 0

			train_index = np.arange( train_start, train_end, dtype=int )
			test_index = np.arange( test_start,
				min( test_start + computed_test_size, n_samples ), dtype=int )

			if len( train_index ) == 0 or len( test_index ) == 0:
				continue

			yield train_index, test_index
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'TimeSeriesSpliter'
		exception.method = 'split( self, *args ) -> Generator[Tuple[np.ndarray, np.ndarray], None, None]'
		Logger( ).write( exception )
		raise exception

get_n_splits

get_n_splits(
    series: ndarray = None,
    y: ndarray = None,
    groups: ndarray = None,
) -> int | None

Count time-series splits.

Purpose

Returns the configured number of chronological validation splits available for the supplied series and splitter configuration.

Parameters:

Name Type Description Default
series ndarray

Optional ordered observations used to validate split availability.

None
y ndarray

Optional target array accepted for sklearn splitter compatibility.

None
groups ndarray

Optional group labels accepted for sklearn splitter compatibility.

None

Returns:

Type Description
int | None

int | None: int | None returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

Source code in forecasting.py
def get_n_splits( self, series: np.ndarray=None, y: np.ndarray=None,
	groups: np.ndarray=None ) -> int | None:
	"""Count time-series splits.

	Purpose:
	    Returns the configured number of chronological validation splits available for the
	    supplied series and splitter configuration.

	Args:
	    series (np.ndarray): Optional ordered observations used to validate split
	                         availability.
	    y (np.ndarray): Optional target array accepted for sklearn splitter compatibility.
	    groups (np.ndarray): Optional group labels accepted for sklearn splitter
	                         compatibility.

	Returns:
	    int | None: int | None returned by the forecasting operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails."""
	try:
		return self.n_splits
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'TimeSeriesSpliter'
		exception.method = 'get_n_splits( self, *args ) -> int | None'
		Logger( ).write( exception )
		raise exception

get_splits

get_splits(
    series: ndarray,
) -> list[Tuple[np.ndarray, np.ndarray]]

Materialize time-series splits.

Purpose

Collects all chronological train/test index pairs into a list for inspection, repeated use, or plotting.

Parameters:

Name Type Description Default
series ndarray

Ordered observations used to determine split boundaries.

required

Returns:

Type Description
list[Tuple[ndarray, ndarray]]

list[Tuple[np.ndarray, np.ndarray]]: list[Tuple[np.ndarray, np.ndarray]] returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

Source code in forecasting.py
def get_splits( self, series: np.ndarray ) -> list[ Tuple[ np.ndarray, np.ndarray ] ]:
	"""Materialize time-series splits.

	Purpose:
	    Collects all chronological train/test index pairs into a list for inspection,
	    repeated use, or plotting.

	Args:
	    series (np.ndarray): Ordered observations used to determine split boundaries.

	Returns:
	    list[Tuple[np.ndarray, np.ndarray]]: list[Tuple[np.ndarray, np.ndarray]] returned by
	                                         the forecasting operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails."""
	try:
		throw_if( 'series', series )
		return list( self.split( series ) )
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'TimeSeriesSpliter'
		exception.method = 'get_splits( self, series: np.ndarray ) -> list[Tuple[np.ndarray, np.ndarray]]'
		Logger( ).write( exception )
		raise exception

visualize

visualize(series: ndarray) -> plt.Figure | None

Visualize time-series splits.

Purpose

Builds a matplotlib figure showing the chronological train and test windows produced by the fixed-window splitter.

Parameters:

Name Type Description Default
series ndarray

Ordered observations used to generate the split visualization.

required

Returns:

Type Description
Figure | None

plt.Figure | None: plt.Figure | None returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

ValueError

Raised when the visualize operation cannot complete.

Source code in forecasting.py
def visualize( self, series: np.ndarray ) -> plt.Figure | None:
	"""Visualize time-series splits.

	Purpose:
	    Builds a matplotlib figure showing the chronological train and test windows produced
	    by the fixed-window splitter.

	Args:
	    series (np.ndarray): Ordered observations used to generate the split visualization.

	Returns:
	    plt.Figure | None: plt.Figure | None returned by the forecasting operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails.
	    ValueError: Raised when the `visualize` operation cannot complete."""
	try:
		throw_if( 'series', series )
		values = np.asarray( series, dtype=float ).reshape( -1 )
		splits = self.get_splits( values )

		if not splits:
			raise ValueError( 'No time-series splits were generated.' )

		fig, axes = plt.subplots( len( splits ), 1, figsize=(10, 2.5 * len( splits )) )
		if len( splits ) == 1:
			axes = [ axes ]

		x_axis = np.arange( len( values ) )
		for i, (train_idx, test_idx) in enumerate( splits ):
			axis = axes[ i ]
			axis.plot( x_axis[ train_idx ], values[ train_idx ], label='Train' )
			axis.plot( x_axis[ test_idx ], values[ test_idx ], label='Test' )
			axis.set_title( f'Split {i + 1}' )
			axis.grid( True, alpha=0.25 )
			axis.legend( )

		plt.tight_layout( )
		return fig
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'TimeSeriesSpliter'
		exception.method = 'visualize( self, series: np.ndarray ) -> plt.Figure | None'
		Logger( ).write( exception )
		raise exception

LaggingSeries

Bases: TimeSeries

Forecast with linear lag features.

Purpose

Builds lagged supervised-learning matrices from univariate time-series observations, trains a linear regression model on historical lag windows, projects future values recursively, and reports regression metrics for fitted lag forecasts.

Attributes:

Name Type Description
model Optional[RegressionResultsWrapper]

Linear regression estimator trained on lagged features.

lag int

Number of lagged observations used as predictors.

prediction Optional[ndarray]

Most recent recursive forecast output.

training_data Optional[ndarray]

Lagged feature matrix produced from the source series.

training_values Optional[ndarray]

Target or series values used during model fitting.

design_matrix Optional[ndarray]

Lagged predictor matrix constructed from the time series.

Source code in forecasting.py
class LaggingSeries( TimeSeries ):
	"""Forecast with linear lag features.

	Purpose:
	    Builds lagged supervised-learning matrices from univariate time-series observations,
	    trains a linear regression model on historical lag windows, projects future values
	    recursively, and reports regression metrics for fitted lag forecasts.

	Attributes:
	    model (Optional[RegressionResultsWrapper]): Linear regression estimator trained on
	                                                lagged features.
	    lag (int): Number of lagged observations used as predictors.
	    prediction (Optional[np.ndarray]): Most recent recursive forecast output.
	    training_data (Optional[np.ndarray]): Lagged feature matrix produced from the source
	                                          series.
	    training_values (Optional[np.ndarray]): Target or series values used during model
	                                            fitting.
	    design_matrix (Optional[np.ndarray]): Lagged predictor matrix constructed from the
	                                          time series."""
	model: Optional[ RegressionResultsWrapper ]
	lag: int
	prediction: Optional[ np.ndarray ]
	training_data: Optional[ np.ndarray ]
	training_values: Optional[ np.ndarray ]
	design_matrix: Optional[ np.ndarray ]

	def __init__( self, lag: int = 5 ) -> None:
		"""Initialize linear lag forecaster.

		Purpose:
		    Configures the lag-window length, constructs the linear regression estimator, and
		    prepares training, target, and prediction caches for lag-based forecasting.

		Args:
		    lag (int): Number of lagged observations used as predictors.

		Returns:
		    None: This method initializes the object and does not return a value."""
		self.lag = lag
		self.model = None
		self.prediction = None
		self.training_data = None
		self.training_values = None
		self.design_matrix = None

	def lag_transform( self, series: np.ndarray ) -> Tuple[ np.ndarray, np.ndarray ]:
		"""Create lagged training arrays.

		Purpose:
		    Converts an ordered univariate series into a supervised-learning design matrix where
		    each row contains lagged observations and each target value contains the next
		    observation.

		Args:
		    series (np.ndarray): Ordered univariate series used to create lagged features and
		                         targets.

		Returns:
		    Tuple[np.ndarray, np.ndarray]: Tuple[np.ndarray, np.ndarray] returned by the
		                                   forecasting operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails.
		    ValueError: Raised when the `lag_transform` operation cannot complete."""
		try:
			throw_if( 'series', series )
			if len( series ) <= self.lag:
				raise ValueError(
					f'Argument "series" must contain more than {self.lag} observations.' )

			values = np.asarray( series, dtype=float ).reshape( -1 )
			n = len( values )
			self.training_data = np.array(
				[ values[ i - self.lag:i ] for i in range( self.lag, n ) ],
				dtype=float )
			self.training_values = values[ self.lag: ]
			return self.training_data, self.training_values
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'LaggingSeries'
			exception.method = 'lag_transform( self, series: np.ndarray ) -> Tuple[np.ndarray, np.ndarray]'
			Logger( ).write( exception )
			raise exception

	def train( self, series: np.ndarray ) -> LaggingSeries | None:
		"""Fit LaggingSeries model.

		Purpose:
		    Fits the forecasting estimator to lagged features generated from the supplied time
		    series and stores the training matrix and aligned target vector on the class/object.

		Args:
		    series (np.ndarray): Ordered univariate series used to train the lag-based
		                         forecasting model.

		Returns:
		    LaggingSeries | None: LaggingSeries | None returned by the forecasting operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails."""
		try:
			throw_if( 'series', series )
			x_data, y_data = self.lag_transform( series )
			self.design_matrix = sm.add_constant( x_data, has_constant='add' )
			self.model = sm.OLS( y_data, self.design_matrix ).fit( )
			return self
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'LaggingSeries'
			exception.method = 'train( self, series: np.ndarray ) -> LaggingSeries | None'
			Logger( ).write( exception )
			raise exception

	def project( self, n_steps: int = 1 ) -> np.ndarray:
		"""Project future observations.

		Purpose:
		    Generates recursive forward forecasts by feeding each newly predicted value back
		    into the lag window for subsequent forecast steps.

		Args:
		    n_steps (int): Number of future periods to forecast.

		Returns:
		    np.ndarray: np.ndarray returned by the forecasting operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails.
		    ValueError: Raised when the `project` operation cannot complete."""
		try:
			throw_if( 'n_steps', n_steps )
			throw_if( 'training_data', self.training_data )
			throw_if( 'model', self.model )
			if n_steps < 1:
				raise ValueError( 'Argument "n_steps" must be greater than zero.' )

			last_window = self.training_data[ -1 ].astype( float ).copy( )
			preds = [ ]
			for _ in range( n_steps ):
				x_input = sm.add_constant( last_window.reshape( 1, -1 ), has_constant='add' )
				next_value = float( self.model.predict( x_input )[ 0 ] )
				preds.append( next_value )
				last_window = np.roll( last_window, -1 )
				last_window[ -1 ] = next_value

			self.prediction = np.array( preds, dtype=float )
			return self.prediction
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'LaggingSeries'
			exception.method = 'project( self, n_steps: int=1 ) -> np.ndarray'
			Logger( ).write( exception )
			raise exception

	def score( self ) -> float | None:
		"""Score fitted forecasts.

		Purpose:
		    Computes the coefficient of determination for fitted in-sample predictions against
		    the stored training target values.

		Returns:
		    float | None: float | None returned by the forecasting operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails."""
		try:
			throw_if( 'model', self.model )
			return float( self.model.rsquared )
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'LaggingSeries'
			exception.method = 'score( self ) -> float | None'
			Logger( ).write( exception )
			raise exception

	def analyze( self ) -> Dict[ str, float ] | None:
		"""Analyze forecast residuals.

		Purpose:
		    Computes regression diagnostics for fitted in-sample predictions, including squared
		    error, absolute error, explained variance, maximum error, median absolute error, and
		    coefficient of determination.

		Returns:
		    Dict[str, float] | None: Dict[str, float] | None returned by the forecasting
		                             operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails."""
		try:
			throw_if( 'training_values', self.training_values )
			throw_if( 'design_matrix', self.design_matrix )
			throw_if( 'model', self.model )
			self.prediction = np.asarray( self.model.predict( self.design_matrix ), dtype=float )
			return { 'MSE': mean_squared_error( self.training_values, self.prediction ),
			         'RMSE': np.sqrt( mean_squared_error( self.training_values, self.prediction ) ),
			         'MAE': mean_absolute_error( self.training_values, self.prediction ),
			         'MedianAE': median_absolute_error( self.training_values, self.prediction ),
			         'R2': r2_score( self.training_values, self.prediction ),
			         'ExplainedVariance': explained_variance_score( self.training_values,
				         self.prediction ) }
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'LaggingSeries'
			exception.method = 'analyze( self ) -> Dict[str, float] | None'
			Logger( ).write( exception )
			raise exception

lag_transform

lag_transform(
    series: ndarray,
) -> Tuple[np.ndarray, np.ndarray]

Create lagged training arrays.

Purpose

Converts an ordered univariate series into a supervised-learning design matrix where each row contains lagged observations and each target value contains the next observation.

Parameters:

Name Type Description Default
series ndarray

Ordered univariate series used to create lagged features and targets.

required

Returns:

Type Description
Tuple[ndarray, ndarray]

Tuple[np.ndarray, np.ndarray]: Tuple[np.ndarray, np.ndarray] returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

ValueError

Raised when the lag_transform operation cannot complete.

Source code in forecasting.py
def lag_transform( self, series: np.ndarray ) -> Tuple[ np.ndarray, np.ndarray ]:
	"""Create lagged training arrays.

	Purpose:
	    Converts an ordered univariate series into a supervised-learning design matrix where
	    each row contains lagged observations and each target value contains the next
	    observation.

	Args:
	    series (np.ndarray): Ordered univariate series used to create lagged features and
	                         targets.

	Returns:
	    Tuple[np.ndarray, np.ndarray]: Tuple[np.ndarray, np.ndarray] returned by the
	                                   forecasting operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails.
	    ValueError: Raised when the `lag_transform` operation cannot complete."""
	try:
		throw_if( 'series', series )
		if len( series ) <= self.lag:
			raise ValueError(
				f'Argument "series" must contain more than {self.lag} observations.' )

		values = np.asarray( series, dtype=float ).reshape( -1 )
		n = len( values )
		self.training_data = np.array(
			[ values[ i - self.lag:i ] for i in range( self.lag, n ) ],
			dtype=float )
		self.training_values = values[ self.lag: ]
		return self.training_data, self.training_values
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'LaggingSeries'
		exception.method = 'lag_transform( self, series: np.ndarray ) -> Tuple[np.ndarray, np.ndarray]'
		Logger( ).write( exception )
		raise exception

train

train(series: ndarray) -> LaggingSeries | None

Fit LaggingSeries model.

Purpose

Fits the forecasting estimator to lagged features generated from the supplied time series and stores the training matrix and aligned target vector on the class/object.

Parameters:

Name Type Description Default
series ndarray

Ordered univariate series used to train the lag-based forecasting model.

required

Returns:

Type Description
LaggingSeries | None

LaggingSeries | None: LaggingSeries | None returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

Source code in forecasting.py
def train( self, series: np.ndarray ) -> LaggingSeries | None:
	"""Fit LaggingSeries model.

	Purpose:
	    Fits the forecasting estimator to lagged features generated from the supplied time
	    series and stores the training matrix and aligned target vector on the class/object.

	Args:
	    series (np.ndarray): Ordered univariate series used to train the lag-based
	                         forecasting model.

	Returns:
	    LaggingSeries | None: LaggingSeries | None returned by the forecasting operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails."""
	try:
		throw_if( 'series', series )
		x_data, y_data = self.lag_transform( series )
		self.design_matrix = sm.add_constant( x_data, has_constant='add' )
		self.model = sm.OLS( y_data, self.design_matrix ).fit( )
		return self
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'LaggingSeries'
		exception.method = 'train( self, series: np.ndarray ) -> LaggingSeries | None'
		Logger( ).write( exception )
		raise exception

project

project(n_steps: int = 1) -> np.ndarray

Project future observations.

Purpose

Generates recursive forward forecasts by feeding each newly predicted value back into the lag window for subsequent forecast steps.

Parameters:

Name Type Description Default
n_steps int

Number of future periods to forecast.

1

Returns:

Type Description
ndarray

np.ndarray: np.ndarray returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

ValueError

Raised when the project operation cannot complete.

Source code in forecasting.py
def project( self, n_steps: int = 1 ) -> np.ndarray:
	"""Project future observations.

	Purpose:
	    Generates recursive forward forecasts by feeding each newly predicted value back
	    into the lag window for subsequent forecast steps.

	Args:
	    n_steps (int): Number of future periods to forecast.

	Returns:
	    np.ndarray: np.ndarray returned by the forecasting operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails.
	    ValueError: Raised when the `project` operation cannot complete."""
	try:
		throw_if( 'n_steps', n_steps )
		throw_if( 'training_data', self.training_data )
		throw_if( 'model', self.model )
		if n_steps < 1:
			raise ValueError( 'Argument "n_steps" must be greater than zero.' )

		last_window = self.training_data[ -1 ].astype( float ).copy( )
		preds = [ ]
		for _ in range( n_steps ):
			x_input = sm.add_constant( last_window.reshape( 1, -1 ), has_constant='add' )
			next_value = float( self.model.predict( x_input )[ 0 ] )
			preds.append( next_value )
			last_window = np.roll( last_window, -1 )
			last_window[ -1 ] = next_value

		self.prediction = np.array( preds, dtype=float )
		return self.prediction
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'LaggingSeries'
		exception.method = 'project( self, n_steps: int=1 ) -> np.ndarray'
		Logger( ).write( exception )
		raise exception

score

score() -> float | None

Score fitted forecasts.

Purpose

Computes the coefficient of determination for fitted in-sample predictions against the stored training target values.

Returns:

Type Description
float | None

float | None: float | None returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

Source code in forecasting.py
def score( self ) -> float | None:
	"""Score fitted forecasts.

	Purpose:
	    Computes the coefficient of determination for fitted in-sample predictions against
	    the stored training target values.

	Returns:
	    float | None: float | None returned by the forecasting operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails."""
	try:
		throw_if( 'model', self.model )
		return float( self.model.rsquared )
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'LaggingSeries'
		exception.method = 'score( self ) -> float | None'
		Logger( ).write( exception )
		raise exception

analyze

analyze() -> Dict[str, float] | None

Analyze forecast residuals.

Purpose

Computes regression diagnostics for fitted in-sample predictions, including squared error, absolute error, explained variance, maximum error, median absolute error, and coefficient of determination.

Returns:

Type Description
Dict[str, float] | None

Dict[str, float] | None: Dict[str, float] | None returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

Source code in forecasting.py
def analyze( self ) -> Dict[ str, float ] | None:
	"""Analyze forecast residuals.

	Purpose:
	    Computes regression diagnostics for fitted in-sample predictions, including squared
	    error, absolute error, explained variance, maximum error, median absolute error, and
	    coefficient of determination.

	Returns:
	    Dict[str, float] | None: Dict[str, float] | None returned by the forecasting
	                             operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails."""
	try:
		throw_if( 'training_values', self.training_values )
		throw_if( 'design_matrix', self.design_matrix )
		throw_if( 'model', self.model )
		self.prediction = np.asarray( self.model.predict( self.design_matrix ), dtype=float )
		return { 'MSE': mean_squared_error( self.training_values, self.prediction ),
		         'RMSE': np.sqrt( mean_squared_error( self.training_values, self.prediction ) ),
		         'MAE': mean_absolute_error( self.training_values, self.prediction ),
		         'MedianAE': median_absolute_error( self.training_values, self.prediction ),
		         'R2': r2_score( self.training_values, self.prediction ),
		         'ExplainedVariance': explained_variance_score( self.training_values,
			         self.prediction ) }
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'LaggingSeries'
		exception.method = 'analyze( self ) -> Dict[str, float] | None'
		Logger( ).write( exception )
		raise exception

LagBoostingSeries

Bases: TimeSeries

Forecast with histogram gradient boosting over lag features.

Purpose

Builds lagged supervised-learning matrices and trains a histogram gradient boosting regressor for nonlinear time-series forecasting. The class/object exposes the estimator configuration, recursive multi-step projection, and regression diagnostics for the fitted lag model.

Attributes:

Name Type Description
model Optional[HistGradientBoostingRegressor]

Boosting estimator trained on lagged features.

lag int

Number of lagged observations used as predictors.

loss str

Loss function minimized by the estimator.

quantile Optional[float]

Conditional quantile estimated by quantile-loss forecasting.

learning_rate float

Step-size shrinkage applied during iterative model fitting.

max_iter int

Maximum number of estimator iterations.

max_leaf_nodes Optional[int]

Maximum number of leaf nodes permitted in each tree.

max_depth Optional[int]

Maximum depth permitted for fitted decision trees.

min_samples_leaf int

Minimum number of samples permitted in a tree leaf.

l2_regularization float

L2 penalty applied by histogram gradient boosting.

max_features float

Feature subset size considered during model fitting.

max_bins int

Maximum number of bins used for continuous features.

monotonic_cst Optional[object]

Monotonic feature constraints applied during model fitting.

interaction_cst Optional[object]

Interaction constraints applied to histogram gradient boosting.

warm_start bool

Whether repeated fits reuse the preceding fitted estimator state.

early_stopping str | bool

Policy controlling validation-based early stopping.

scoring str

Metric used to evaluate validation performance.

validation_fraction float

Fraction of training data reserved for early stopping.

n_iter_no_change int

Stable-iteration count required to trigger early stopping.

tol float

Convergence tolerance used by the estimator.

verbose int

Estimator verbosity level.

random_state Optional[int]

Random seed or sklearn random-state value used for reproducibility.

training_values Optional[ndarray]

Target or series values used during model fitting.

fitted_values Optional[ndarray]

In-sample values predicted by the fitted forecasting model.

mean_absolute_error Optional[float]

Most recently calculated mean absolute error.

mean_squared_error Optional[float]

Most recently calculated mean squared error.

root_mean_squared_error Optional[float]

Most recently calculated root mean squared error.

r2_score Optional[float]

Most recently calculated coefficient of determination.

explained_variance_score Optional[float]

Most recently calculated explained-variance score.

median_absolute_error Optional[float]

Most recently calculated median absolute error.

max_error Optional[float]

Most recently calculated maximum residual error.

Source code in forecasting.py
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
class LagBoostingSeries( TimeSeries ):
	"""Forecast with histogram gradient boosting over lag features.

	Purpose:
	    Builds lagged supervised-learning matrices and trains a histogram gradient boosting
	    regressor for nonlinear time-series forecasting. The class/object exposes the estimator
	    configuration, recursive multi-step projection, and regression diagnostics for the
	    fitted lag model.

	Attributes:
	    model (Optional[ske.HistGradientBoostingRegressor]): Boosting estimator trained on
	                                                         lagged features.
	    lag (int): Number of lagged observations used as predictors.
	    loss (str): Loss function minimized by the estimator.
	    quantile (Optional[float]): Conditional quantile estimated by quantile-loss
	                                forecasting.
	    learning_rate (float): Step-size shrinkage applied during iterative model fitting.
	    max_iter (int): Maximum number of estimator iterations.
	    max_leaf_nodes (Optional[int]): Maximum number of leaf nodes permitted in each tree.
	    max_depth (Optional[int]): Maximum depth permitted for fitted decision trees.
	    min_samples_leaf (int): Minimum number of samples permitted in a tree leaf.
	    l2_regularization (float): L2 penalty applied by histogram gradient boosting.
	    max_features (float): Feature subset size considered during model fitting.
	    max_bins (int): Maximum number of bins used for continuous features.
	    monotonic_cst (Optional[object]): Monotonic feature constraints applied during model
	                                      fitting.
	    interaction_cst (Optional[object]): Interaction constraints applied to histogram
	                                        gradient boosting.
	    warm_start (bool): Whether repeated fits reuse the preceding fitted estimator state.
	    early_stopping (str | bool): Policy controlling validation-based early stopping.
	    scoring (str): Metric used to evaluate validation performance.
	    validation_fraction (float): Fraction of training data reserved for early stopping.
	    n_iter_no_change (int): Stable-iteration count required to trigger early stopping.
	    tol (float): Convergence tolerance used by the estimator.
	    verbose (int): Estimator verbosity level.
	    random_state (Optional[int]): Random seed or sklearn random-state value used for
	                                  reproducibility.
	    training_values (Optional[np.ndarray]): Target or series values used during model
	                                            fitting.
	    fitted_values (Optional[np.ndarray]): In-sample values predicted by the fitted
	                                          forecasting model.
	    mean_absolute_error (Optional[float]): Most recently calculated mean absolute error.
	    mean_squared_error (Optional[float]): Most recently calculated mean squared error.
	    root_mean_squared_error (Optional[float]): Most recently calculated root mean
	                                               squared error.
	    r2_score (Optional[float]): Most recently calculated coefficient of determination.
	    explained_variance_score (Optional[float]): Most recently calculated
	                                                explained-variance score.
	    median_absolute_error (Optional[float]): Most recently calculated median absolute
	                                             error.
	    max_error (Optional[float]): Most recently calculated maximum residual error."""
	model: Optional[ ske.HistGradientBoostingRegressor ]
	lag: int
	loss: str
	quantile: Optional[ float ]
	learning_rate: float
	max_iter: int
	max_leaf_nodes: Optional[ int ]
	max_depth: Optional[ int ]
	min_samples_leaf: int
	l2_regularization: float
	max_features: float
	max_bins: int
	monotonic_cst: Optional[ object ]
	interaction_cst: Optional[ object ]
	warm_start: bool
	early_stopping: str | bool
	scoring: str
	validation_fraction: float
	n_iter_no_change: int
	tol: float
	verbose: int
	random_state: Optional[ int ]
	training_values: Optional[ np.ndarray ]
	fitted_values: Optional[ np.ndarray ]
	mean_absolute_error: Optional[ float ]
	mean_squared_error: Optional[ float ]
	root_mean_squared_error: Optional[ float ]
	r2_score: Optional[ float ]
	explained_variance_score: Optional[ float ]
	median_absolute_error: Optional[ float ]
	max_error: Optional[ float ]

	def __init__( self, lag: int=12, loss: str='squared_error', quantile: Optional[ float ]=None,
		rate: float=0.1, iters: int=100, leaf_nodes: Optional[ int ]=31, depth: Optional[ int ]=None, leaf: int=20,
		regularization: float=0.0, features: float=1.0, bins: int=255,
		monotonic: Optional[ object ]=None, interaction: Optional[ object ]=None, warm: bool=False,
		stopping: str | bool='auto', scoring: str='loss', validation: float=0.1, no_change: int=10,
		tol: float=1e-7, verbose: int=0, rando: Optional[ int ]=None ) -> None:
		"""Initialize boosting lag forecaster.

		Purpose:
		    Configures the lag-window length and histogram gradient boosting regression options
		    used for nonlinear recursive time-series forecasting.

		Args:
		    lag (int): Number of lagged observations used as predictors.
		    loss (str): Loss function used by the boosting regressor.
		    quantile (Optional[float]): Quantile value used when quantile loss is selected.
		    rate (float): Learning rate for boosting updates.
		    iters (int): Maximum number of boosting iterations.
		    leaf_nodes (Optional[int]): Maximum number of leaf nodes per tree.
		    depth (Optional[int]): Maximum tree depth.
		    leaf (int): Minimum samples per leaf.
		    regularization (float): L2 regularization strength.
		    features (float): Fraction or count of features considered per split.
		    bins (int): Maximum number of histogram bins.
		    monotonic (Optional[object]): Monotonic constraint configuration.
		    interaction (Optional[object]): Interaction constraint configuration.
		    warm (bool): Flag indicating whether warm-start fitting is enabled.
		    stopping (str | bool): Early-stopping mode.
		    scoring (str): Scoring metric used for early stopping.
		    validation (float): Validation fraction used for early stopping.
		    no_change (int): Iterations without improvement allowed before stopping.
		    tol (float): Tolerance used for early-stopping improvement checks.
		    verbose (int): Verbosity level passed to the estimator.
		    rando (Optional[int]): Random seed passed to the estimator.

		Returns:
		    None: This method initializes the object and does not return a value."""
		super( ).__init__( )
		self.lag = lag
		self.loss = loss
		self.quantile = quantile
		self.learning_rate = rate
		self.max_iter = iters
		self.max_leaf_nodes = leaf_nodes
		self.max_depth = depth
		self.min_samples_leaf = leaf
		self.l2_regularization = regularization
		self.max_features = features
		self.max_bins = bins
		self.monotonic_cst = monotonic
		self.interaction_cst = interaction
		self.warm_start = warm
		self.early_stopping = stopping
		self.scoring = scoring
		self.validation_fraction = validation
		self.n_iter_no_change = no_change
		self.tol = tol
		self.verbose = verbose
		self.random_state = rando
		self.model = ske.HistGradientBoostingRegressor( loss=self.loss, quantile=self.quantile,
			learning_rate=self.learning_rate, max_iter=self.max_iter,
			max_leaf_nodes=self.max_leaf_nodes, max_depth=self.max_depth,
			min_samples_leaf=self.min_samples_leaf, l2_regularization=self.l2_regularization,
			max_features=self.max_features, max_bins=self.max_bins,
			monotonic_cst=self.monotonic_cst, interaction_cst=self.interaction_cst,
			warm_start=self.warm_start, early_stopping=self.early_stopping, scoring=self.scoring,
			validation_fraction=self.validation_fraction, n_iter_no_change=self.n_iter_no_change,
			tol=self.tol, verbose=self.verbose, random_state=self.random_state )
		self.training_data = None
		self.training_values = None
		self.prediction = None
		self.fitted_values = None
		self.mean_absolute_error = 0.0
		self.mean_squared_error = 0.0
		self.root_mean_squared_error = 0.0
		self.r2_score = 0.0
		self.explained_variance_score = 0.0
		self.median_absolute_error = 0.0
		self.max_error = 0.0

	def lag_transform( self, series: np.ndarray ) -> Tuple[ np.ndarray, np.ndarray ]:
		"""Create lagged training arrays.

		Purpose:
		    Converts an ordered univariate series into a supervised-learning design matrix where
		    each row contains lagged observations and each target value contains the next
		    observation.

		Args:
		    series (np.ndarray): Ordered univariate series used to create lagged features and
		                         targets.

		Returns:
		    Tuple[np.ndarray, np.ndarray]: Tuple[np.ndarray, np.ndarray] returned by the
		                                   forecasting operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails.
		    ValueError: Raised when the `lag_transform` operation cannot complete."""
		try:
			throw_if( 'series', series )

			if self.lag < 1:
				raise ValueError( 'Argument "lag" must be greater than zero.' )

			values = np.asarray( series, dtype=float ).reshape( -1 )
			if len( values ) <= self.lag:
				raise ValueError(
					f'Argument "series" must contain more than {self.lag} observations.' )

			self.training_data = np.array(
				[ values[ i - self.lag:i ] for i in range( self.lag, len( values ) ) ],
				dtype=float )

			self.training_values = values[ self.lag: ]
			return self.training_data, self.training_values
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'LagBoostingSeries'
			exception.method = 'lag_transform( self, series: np.ndarray ) -> Tuple[np.ndarray, np.ndarray]'
			Logger( ).write( exception )
			raise exception

	def train( self, series: np.ndarray ) -> LagBoostingSeries | None:
		"""Fit LagBoostingSeries model.

		Purpose:
		    Fits the forecasting estimator to lagged features generated from the supplied time
		    series and stores the training matrix and aligned target vector on the class/object.

		Args:
		    series (np.ndarray): Ordered univariate series used to train the lag-based
		                         forecasting model.

		Returns:
		    LagBoostingSeries | None: LagBoostingSeries | None returned by the forecasting
		                              operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails.
		    ValueError: Raised when the `train` operation cannot complete."""
		try:
			throw_if( 'series', series )
			if self.loss == 'quantile' and self.quantile is None:
				raise ValueError( 'Argument "quantile" is required when loss is "quantile".' )

			x_data, y_data = self.lag_transform( series )
			self.model.fit( x_data, y_data )
			self.fitted_values = self.model.predict( x_data )
			self.prediction = None
			return self
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'LagBoostingSeries'
			exception.method = 'train( self, series: np.ndarray ) -> LagBoostingSeries | None'
			Logger( ).write( exception )
			raise exception

	def project( self, n_steps: int = 1 ) -> np.ndarray | None:
		"""Project future observations.

		Purpose:
		    Generates recursive forward forecasts by feeding each newly predicted value back
		    into the lag window for subsequent forecast steps.

		Args:
		    n_steps (int): Number of future periods to forecast.

		Returns:
		    np.ndarray | None: np.ndarray | None returned by the forecasting operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails.
		    ValueError: Raised when the `project` operation cannot complete."""
		try:
			throw_if( 'n_steps', n_steps )
			throw_if( 'training_data', self.training_data )
			throw_if( 'model', self.model )

			if n_steps < 1:
				raise ValueError( 'Argument "n_steps" must be greater than zero.' )

			last_window = self.training_data[ -1 ].astype( float ).copy( )
			preds = [ ]

			for _ in range( n_steps ):
				next_value = float( self.model.predict( last_window.reshape( 1, -1 ) )[ 0 ] )
				preds.append( next_value )
				last_window = np.roll( last_window, -1 )
				last_window[ -1 ] = next_value

			self.prediction = np.array( preds, dtype=float )
			return self.prediction
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'LagBoostingSeries'
			exception.method = 'project( self, n_steps: int=1 ) -> np.ndarray | None'
			Logger( ).write( exception )
			raise exception

	def score( self ) -> float | None:
		"""Score fitted forecasts.

		Purpose:
		    Computes the coefficient of determination for fitted in-sample predictions against
		    the stored training target values.

		Returns:
		    float | None: float | None returned by the forecasting operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails."""
		try:
			throw_if( 'training_data', self.training_data )
			throw_if( 'training_values', self.training_values )
			return float( self.model.score( self.training_data, self.training_values ) )
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'LagBoostingSeries'
			exception.method = 'score( self ) -> float | None'
			Logger( ).write( exception )
			raise exception

	def analyze( self ) -> Dict[ str, float ] | None:
		"""Analyze forecast residuals.

		Purpose:
		    Computes regression diagnostics for fitted in-sample predictions, including squared
		    error, absolute error, explained variance, maximum error, median absolute error, and
		    coefficient of determination.

		Returns:
		    Dict[str, float] | None: Dict[str, float] | None returned by the forecasting
		                             operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails."""
		try:
			throw_if( 'training_values', self.training_values )
			if self.fitted_values is None:
				throw_if( 'training_data', self.training_data )
				self.fitted_values = self.model.predict( self.training_data )

			self.mean_absolute_error = mean_absolute_error( self.training_values,
				self.fitted_values )

			self.mean_squared_error = mean_squared_error( self.training_values,
				self.fitted_values )

			self.root_mean_squared_error = float( np.sqrt( self.mean_squared_error ) )
			self.r2_score = r2_score( self.training_values, self.fitted_values )
			self.explained_variance_score = explained_variance_score( self.training_values,
				self.fitted_values )

			self.median_absolute_error = median_absolute_error( self.training_values,
				self.fitted_values )
			self.max_error = max_error( self.training_values, self.fitted_values )

			return { 'MAE': float( self.mean_absolute_error ),
				'MSE': float( self.mean_squared_error ),
				'RMSE': float( self.root_mean_squared_error ), 'R2': float( self.r2_score ),
				'EVS': float( self.explained_variance_score ),
				'MedianAE': float( self.median_absolute_error ), 'MAX': float( self.max_error ) }
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'LagBoostingSeries'
			exception.method = 'analyze( self ) -> Dict[str, float] | None'
			Logger( ).write( exception )
			raise exception

lag_transform

lag_transform(
    series: ndarray,
) -> Tuple[np.ndarray, np.ndarray]

Create lagged training arrays.

Purpose

Converts an ordered univariate series into a supervised-learning design matrix where each row contains lagged observations and each target value contains the next observation.

Parameters:

Name Type Description Default
series ndarray

Ordered univariate series used to create lagged features and targets.

required

Returns:

Type Description
Tuple[ndarray, ndarray]

Tuple[np.ndarray, np.ndarray]: Tuple[np.ndarray, np.ndarray] returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

ValueError

Raised when the lag_transform operation cannot complete.

Source code in forecasting.py
def lag_transform( self, series: np.ndarray ) -> Tuple[ np.ndarray, np.ndarray ]:
	"""Create lagged training arrays.

	Purpose:
	    Converts an ordered univariate series into a supervised-learning design matrix where
	    each row contains lagged observations and each target value contains the next
	    observation.

	Args:
	    series (np.ndarray): Ordered univariate series used to create lagged features and
	                         targets.

	Returns:
	    Tuple[np.ndarray, np.ndarray]: Tuple[np.ndarray, np.ndarray] returned by the
	                                   forecasting operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails.
	    ValueError: Raised when the `lag_transform` operation cannot complete."""
	try:
		throw_if( 'series', series )

		if self.lag < 1:
			raise ValueError( 'Argument "lag" must be greater than zero.' )

		values = np.asarray( series, dtype=float ).reshape( -1 )
		if len( values ) <= self.lag:
			raise ValueError(
				f'Argument "series" must contain more than {self.lag} observations.' )

		self.training_data = np.array(
			[ values[ i - self.lag:i ] for i in range( self.lag, len( values ) ) ],
			dtype=float )

		self.training_values = values[ self.lag: ]
		return self.training_data, self.training_values
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'LagBoostingSeries'
		exception.method = 'lag_transform( self, series: np.ndarray ) -> Tuple[np.ndarray, np.ndarray]'
		Logger( ).write( exception )
		raise exception

train

train(series: ndarray) -> LagBoostingSeries | None

Fit LagBoostingSeries model.

Purpose

Fits the forecasting estimator to lagged features generated from the supplied time series and stores the training matrix and aligned target vector on the class/object.

Parameters:

Name Type Description Default
series ndarray

Ordered univariate series used to train the lag-based forecasting model.

required

Returns:

Type Description
LagBoostingSeries | None

LagBoostingSeries | None: LagBoostingSeries | None returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

ValueError

Raised when the train operation cannot complete.

Source code in forecasting.py
def train( self, series: np.ndarray ) -> LagBoostingSeries | None:
	"""Fit LagBoostingSeries model.

	Purpose:
	    Fits the forecasting estimator to lagged features generated from the supplied time
	    series and stores the training matrix and aligned target vector on the class/object.

	Args:
	    series (np.ndarray): Ordered univariate series used to train the lag-based
	                         forecasting model.

	Returns:
	    LagBoostingSeries | None: LagBoostingSeries | None returned by the forecasting
	                              operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails.
	    ValueError: Raised when the `train` operation cannot complete."""
	try:
		throw_if( 'series', series )
		if self.loss == 'quantile' and self.quantile is None:
			raise ValueError( 'Argument "quantile" is required when loss is "quantile".' )

		x_data, y_data = self.lag_transform( series )
		self.model.fit( x_data, y_data )
		self.fitted_values = self.model.predict( x_data )
		self.prediction = None
		return self
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'LagBoostingSeries'
		exception.method = 'train( self, series: np.ndarray ) -> LagBoostingSeries | None'
		Logger( ).write( exception )
		raise exception

project

project(n_steps: int = 1) -> np.ndarray | None

Project future observations.

Purpose

Generates recursive forward forecasts by feeding each newly predicted value back into the lag window for subsequent forecast steps.

Parameters:

Name Type Description Default
n_steps int

Number of future periods to forecast.

1

Returns:

Type Description
ndarray | None

np.ndarray | None: np.ndarray | None returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

ValueError

Raised when the project operation cannot complete.

Source code in forecasting.py
def project( self, n_steps: int = 1 ) -> np.ndarray | None:
	"""Project future observations.

	Purpose:
	    Generates recursive forward forecasts by feeding each newly predicted value back
	    into the lag window for subsequent forecast steps.

	Args:
	    n_steps (int): Number of future periods to forecast.

	Returns:
	    np.ndarray | None: np.ndarray | None returned by the forecasting operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails.
	    ValueError: Raised when the `project` operation cannot complete."""
	try:
		throw_if( 'n_steps', n_steps )
		throw_if( 'training_data', self.training_data )
		throw_if( 'model', self.model )

		if n_steps < 1:
			raise ValueError( 'Argument "n_steps" must be greater than zero.' )

		last_window = self.training_data[ -1 ].astype( float ).copy( )
		preds = [ ]

		for _ in range( n_steps ):
			next_value = float( self.model.predict( last_window.reshape( 1, -1 ) )[ 0 ] )
			preds.append( next_value )
			last_window = np.roll( last_window, -1 )
			last_window[ -1 ] = next_value

		self.prediction = np.array( preds, dtype=float )
		return self.prediction
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'LagBoostingSeries'
		exception.method = 'project( self, n_steps: int=1 ) -> np.ndarray | None'
		Logger( ).write( exception )
		raise exception

score

score() -> float | None

Score fitted forecasts.

Purpose

Computes the coefficient of determination for fitted in-sample predictions against the stored training target values.

Returns:

Type Description
float | None

float | None: float | None returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

Source code in forecasting.py
def score( self ) -> float | None:
	"""Score fitted forecasts.

	Purpose:
	    Computes the coefficient of determination for fitted in-sample predictions against
	    the stored training target values.

	Returns:
	    float | None: float | None returned by the forecasting operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails."""
	try:
		throw_if( 'training_data', self.training_data )
		throw_if( 'training_values', self.training_values )
		return float( self.model.score( self.training_data, self.training_values ) )
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'LagBoostingSeries'
		exception.method = 'score( self ) -> float | None'
		Logger( ).write( exception )
		raise exception

analyze

analyze() -> Dict[str, float] | None

Analyze forecast residuals.

Purpose

Computes regression diagnostics for fitted in-sample predictions, including squared error, absolute error, explained variance, maximum error, median absolute error, and coefficient of determination.

Returns:

Type Description
Dict[str, float] | None

Dict[str, float] | None: Dict[str, float] | None returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

Source code in forecasting.py
def analyze( self ) -> Dict[ str, float ] | None:
	"""Analyze forecast residuals.

	Purpose:
	    Computes regression diagnostics for fitted in-sample predictions, including squared
	    error, absolute error, explained variance, maximum error, median absolute error, and
	    coefficient of determination.

	Returns:
	    Dict[str, float] | None: Dict[str, float] | None returned by the forecasting
	                             operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails."""
	try:
		throw_if( 'training_values', self.training_values )
		if self.fitted_values is None:
			throw_if( 'training_data', self.training_data )
			self.fitted_values = self.model.predict( self.training_data )

		self.mean_absolute_error = mean_absolute_error( self.training_values,
			self.fitted_values )

		self.mean_squared_error = mean_squared_error( self.training_values,
			self.fitted_values )

		self.root_mean_squared_error = float( np.sqrt( self.mean_squared_error ) )
		self.r2_score = r2_score( self.training_values, self.fitted_values )
		self.explained_variance_score = explained_variance_score( self.training_values,
			self.fitted_values )

		self.median_absolute_error = median_absolute_error( self.training_values,
			self.fitted_values )
		self.max_error = max_error( self.training_values, self.fitted_values )

		return { 'MAE': float( self.mean_absolute_error ),
			'MSE': float( self.mean_squared_error ),
			'RMSE': float( self.root_mean_squared_error ), 'R2': float( self.r2_score ),
			'EVS': float( self.explained_variance_score ),
			'MedianAE': float( self.median_absolute_error ), 'MAX': float( self.max_error ) }
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'LagBoostingSeries'
		exception.method = 'analyze( self ) -> Dict[str, float] | None'
		Logger( ).write( exception )
		raise exception

LagQuantileSeries

Bases: TimeSeries

Forecast quantiles with lag features.

Purpose

Builds lagged supervised-learning matrices and trains a quantile regression estimator for conditional quantile forecasting. The class/object supports recursive projection and regression diagnostics for median, lower-tail, or upper-tail time-series forecasts.

Attributes:

Name Type Description
model Optional[QuantileRegressor]

Quantile regression estimator trained on lagged features.

lag int

Number of lagged observations used as predictors.

quantile float

Conditional quantile estimated by the regression model.

alpha float

L1 regularization strength passed to sklearn QuantileRegressor.

fit_intercept bool

Whether the estimator fits an intercept term.

solver str

Optimization algorithm used to fit the estimator.

solver_options Optional[Dict[str, object]]

Additional settings supplied to the optimization solver.

training_values Optional[ndarray]

Target or series values used during model fitting.

fitted_values Optional[ndarray]

In-sample values predicted by the fitted forecasting model.

mean_absolute_error Optional[float]

Most recently calculated mean absolute error.

mean_squared_error Optional[float]

Most recently calculated mean squared error.

root_mean_squared_error Optional[float]

Most recently calculated root mean squared error.

r2_score Optional[float]

Most recently calculated coefficient of determination.

explained_variance_score Optional[float]

Most recently calculated explained-variance score.

median_absolute_error Optional[float]

Most recently calculated median absolute error.

max_error Optional[float]

Most recently calculated maximum residual error.

Source code in forecasting.py
class LagQuantileSeries( TimeSeries ):
	"""Forecast quantiles with lag features.

	Purpose:
	    Builds lagged supervised-learning matrices and trains a quantile regression
	    estimator for conditional quantile forecasting. The class/object supports recursive
	    projection and regression diagnostics for median, lower-tail, or upper-tail
	    time-series forecasts.

	Attributes:
	    model (Optional[skl.QuantileRegressor]): Quantile regression estimator trained on
	                                             lagged features.
	    lag (int): Number of lagged observations used as predictors.
	    quantile (float): Conditional quantile estimated by the regression model.
	    alpha (float): L1 regularization strength passed to sklearn QuantileRegressor.
	    fit_intercept (bool): Whether the estimator fits an intercept term.
	    solver (str): Optimization algorithm used to fit the estimator.
	    solver_options (Optional[Dict[str, object]]): Additional settings supplied to the
	                                                  optimization solver.
	    training_values (Optional[np.ndarray]): Target or series values used during model
	                                            fitting.
	    fitted_values (Optional[np.ndarray]): In-sample values predicted by the fitted
	                                          forecasting model.
	    mean_absolute_error (Optional[float]): Most recently calculated mean absolute error.
	    mean_squared_error (Optional[float]): Most recently calculated mean squared error.
	    root_mean_squared_error (Optional[float]): Most recently calculated root mean
	                                               squared error.
	    r2_score (Optional[float]): Most recently calculated coefficient of determination.
	    explained_variance_score (Optional[float]): Most recently calculated
	                                                explained-variance score.
	    median_absolute_error (Optional[float]): Most recently calculated median absolute
	                                             error.
	    max_error (Optional[float]): Most recently calculated maximum residual error."""
	model: Optional[ skl.QuantileRegressor ]
	lag: int
	quantile: float
	alpha: float
	fit_intercept: bool
	solver: str
	solver_options: Optional[ Dict[ str, object ] ]
	training_values: Optional[ np.ndarray ]
	fitted_values: Optional[ np.ndarray ]
	mean_absolute_error: Optional[ float ]
	mean_squared_error: Optional[ float ]
	root_mean_squared_error: Optional[ float ]
	r2_score: Optional[ float ]
	explained_variance_score: Optional[ float ]
	median_absolute_error: Optional[ float ]
	max_error: Optional[ float ]

	def __init__( self, lag: int=12, quantile: float=0.5, alpha: float=1.0, fit: bool=True,
		solver: str='highs', solver_options: Optional[ Dict[ str, object ] ]=None ) -> None:
		"""Initialize quantile lag forecaster.

		Purpose:
		    Configures the lag-window length and quantile regression options used to estimate
		    conditional quantiles from lagged time-series features.

		Args:
		    lag (int): Number of lagged observations used as predictors.
		    quantile (float): Conditional quantile estimated by the model.
		    alpha (float): L1 regularization strength.
		    fit (bool): Flag indicating whether an intercept is fitted.
		    solver (str): Linear programming solver used by QuantileRegressor.
		    solver_options (Optional[Dict[str, object]]): Optional solver-specific configuration
		                                                  dictionary.

		Returns:
		    None: This method initializes the object and does not return a value."""
		super( ).__init__( )
		self.lag = lag
		self.quantile = quantile
		self.alpha = alpha
		self.fit_intercept = fit
		self.solver = solver
		self.solver_options = solver_options
		self.model = skl.QuantileRegressor( quantile=self.quantile, alpha=self.alpha,
			fit_intercept=self.fit_intercept, solver=self.solver,
			solver_options=self.solver_options )
		self.training_data = None
		self.training_values = None
		self.prediction = None
		self.fitted_values = None
		self.mean_absolute_error = 0.0
		self.mean_squared_error = 0.0
		self.root_mean_squared_error = 0.0
		self.r2_score = 0.0
		self.explained_variance_score = 0.0
		self.median_absolute_error = 0.0
		self.max_error = 0.0

	def lag_transform( self, series: np.ndarray ) -> Tuple[ np.ndarray, np.ndarray ]:
		"""Create lagged training arrays.

		Purpose:
		    Converts an ordered univariate series into a supervised-learning design matrix where
		    each row contains lagged observations and each target value contains the next
		    observation.

		Args:
		    series (np.ndarray): Ordered univariate series used to create lagged features and
		                         targets.

		Returns:
		    Tuple[np.ndarray, np.ndarray]: Tuple[np.ndarray, np.ndarray] returned by the
		                                   forecasting operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails.
		    ValueError: Raised when the `lag_transform` operation cannot complete."""
		try:
			throw_if( 'series', series )
			if self.lag < 1:
				raise ValueError( 'Argument "lag" must be greater than zero.' )

			values = np.asarray( series, dtype=float ).reshape( -1 )
			if len( values ) <= self.lag:
				raise ValueError(
					f'Argument "series" must contain more than {self.lag} observations.' )

			self.training_data = np.array(
				[ values[ i - self.lag:i ] for i in range( self.lag, len( values ) ) ],
				dtype=float )
			self.training_values = values[ self.lag: ]
			return self.training_data, self.training_values
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'LagQuantileSeries'
			exception.method = 'lag_transform( self, series: np.ndarray ) -> Tuple[np.ndarray, np.ndarray]'
			Logger( ).write( exception )
			raise exception

	def train( self, series: np.ndarray ) -> LagQuantileSeries | None:
		"""Fit LagQuantileSeries model.

		Purpose:
		    Fits the forecasting estimator to lagged features generated from the supplied time
		    series and stores the training matrix and aligned target vector on the class/object.

		Args:
		    series (np.ndarray): Ordered univariate series used to train the lag-based
		                         forecasting model.

		Returns:
		    LagQuantileSeries | None: LagQuantileSeries | None returned by the forecasting
		                              operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails.
		    ValueError: Raised when the `train` operation cannot complete."""
		try:
			throw_if( 'series', series )
			if self.quantile <= 0.0 or self.quantile >= 1.0:
				raise ValueError( 'Argument "quantile" must be strictly between 0 and 1.' )

			if self.alpha < 0.0:
				raise ValueError( 'Argument "alpha" cannot be negative.' )

			x_data, y_data = self.lag_transform( series )
			self.model.fit( x_data, y_data )
			self.fitted_values = self.model.predict( x_data )
			self.prediction = None
			return self
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'LagQuantileSeries'
			exception.method = 'train( self, series: np.ndarray ) -> LagQuantileSeries | None'
			Logger( ).write( exception )
			raise exception

	def project( self, n_steps: int = 1 ) -> np.ndarray | None:
		"""Project future observations.

		Purpose:
		    Generates recursive forward forecasts by feeding each newly predicted value back
		    into the lag window for subsequent forecast steps.

		Args:
		    n_steps (int): Number of future periods to forecast.

		Returns:
		    np.ndarray | None: np.ndarray | None returned by the forecasting operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails.
		    ValueError: Raised when the `project` operation cannot complete."""
		try:
			throw_if( 'n_steps', n_steps )
			throw_if( 'training_data', self.training_data )
			throw_if( 'model', self.model )

			if n_steps < 1:
				raise ValueError( 'Argument "n_steps" must be greater than zero.' )

			last_window = self.training_data[ -1 ].astype( float ).copy( )
			preds = [ ]
			for _ in range( n_steps ):
				next_value = float( self.model.predict( last_window.reshape( 1, -1 ) )[ 0 ] )
				preds.append( next_value )
				last_window = np.roll( last_window, -1 )
				last_window[ -1 ] = next_value

			self.prediction = np.array( preds, dtype=float )
			return self.prediction
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'LagQuantileSeries'
			exception.method = 'project( self, n_steps: int=1 ) -> np.ndarray | None'
			Logger( ).write( exception )
			raise exception

	def score( self ) -> float | None:
		"""Score fitted forecasts.

		Purpose:
		    Computes the coefficient of determination for fitted in-sample predictions against
		    the stored training target values.

		Returns:
		    float | None: float | None returned by the forecasting operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails."""
		try:
			throw_if( 'training_data', self.training_data )
			throw_if( 'training_values', self.training_values )
			return float( self.model.score( self.training_data, self.training_values ) )
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'LagQuantileSeries'
			exception.method = 'score( self ) -> float | None'
			Logger( ).write( exception )
			raise exception

	def analyze( self ) -> Dict[ str, float ] | None:
		"""Analyze forecast residuals.

		Purpose:
		    Computes regression diagnostics for fitted in-sample predictions, including squared
		    error, absolute error, explained variance, maximum error, median absolute error, and
		    coefficient of determination.

		Returns:
		    Dict[str, float] | None: Dict[str, float] | None returned by the forecasting
		                             operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails."""
		try:
			throw_if( 'training_values', self.training_values )
			if self.fitted_values is None:
				throw_if( 'training_data', self.training_data )
				self.fitted_values = self.model.predict( self.training_data )

			self.mean_absolute_error = mean_absolute_error( self.training_values,
				self.fitted_values )
			self.mean_squared_error = mean_squared_error( self.training_values,
				self.fitted_values )
			self.root_mean_squared_error = float( np.sqrt( self.mean_squared_error ) )
			self.r2_score = r2_score( self.training_values, self.fitted_values )
			self.explained_variance_score = explained_variance_score( self.training_values,
				self.fitted_values )
			self.median_absolute_error = median_absolute_error( self.training_values,
				self.fitted_values )
			self.max_error = max_error( self.training_values, self.fitted_values )
			return { 'MAE': float( self.mean_absolute_error ),
				'MSE': float( self.mean_squared_error ),
				'RMSE': float( self.root_mean_squared_error ), 'R2': float( self.r2_score ),
				'EVS': float( self.explained_variance_score ),
				'MedianAE': float( self.median_absolute_error ), 'MAX': float( self.max_error ) }
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'LagQuantileSeries'
			exception.method = 'analyze( self ) -> Dict[str, float] | None'
			Logger( ).write( exception )
			raise exception

lag_transform

lag_transform(
    series: ndarray,
) -> Tuple[np.ndarray, np.ndarray]

Create lagged training arrays.

Purpose

Converts an ordered univariate series into a supervised-learning design matrix where each row contains lagged observations and each target value contains the next observation.

Parameters:

Name Type Description Default
series ndarray

Ordered univariate series used to create lagged features and targets.

required

Returns:

Type Description
Tuple[ndarray, ndarray]

Tuple[np.ndarray, np.ndarray]: Tuple[np.ndarray, np.ndarray] returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

ValueError

Raised when the lag_transform operation cannot complete.

Source code in forecasting.py
def lag_transform( self, series: np.ndarray ) -> Tuple[ np.ndarray, np.ndarray ]:
	"""Create lagged training arrays.

	Purpose:
	    Converts an ordered univariate series into a supervised-learning design matrix where
	    each row contains lagged observations and each target value contains the next
	    observation.

	Args:
	    series (np.ndarray): Ordered univariate series used to create lagged features and
	                         targets.

	Returns:
	    Tuple[np.ndarray, np.ndarray]: Tuple[np.ndarray, np.ndarray] returned by the
	                                   forecasting operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails.
	    ValueError: Raised when the `lag_transform` operation cannot complete."""
	try:
		throw_if( 'series', series )
		if self.lag < 1:
			raise ValueError( 'Argument "lag" must be greater than zero.' )

		values = np.asarray( series, dtype=float ).reshape( -1 )
		if len( values ) <= self.lag:
			raise ValueError(
				f'Argument "series" must contain more than {self.lag} observations.' )

		self.training_data = np.array(
			[ values[ i - self.lag:i ] for i in range( self.lag, len( values ) ) ],
			dtype=float )
		self.training_values = values[ self.lag: ]
		return self.training_data, self.training_values
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'LagQuantileSeries'
		exception.method = 'lag_transform( self, series: np.ndarray ) -> Tuple[np.ndarray, np.ndarray]'
		Logger( ).write( exception )
		raise exception

train

train(series: ndarray) -> LagQuantileSeries | None

Fit LagQuantileSeries model.

Purpose

Fits the forecasting estimator to lagged features generated from the supplied time series and stores the training matrix and aligned target vector on the class/object.

Parameters:

Name Type Description Default
series ndarray

Ordered univariate series used to train the lag-based forecasting model.

required

Returns:

Type Description
LagQuantileSeries | None

LagQuantileSeries | None: LagQuantileSeries | None returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

ValueError

Raised when the train operation cannot complete.

Source code in forecasting.py
def train( self, series: np.ndarray ) -> LagQuantileSeries | None:
	"""Fit LagQuantileSeries model.

	Purpose:
	    Fits the forecasting estimator to lagged features generated from the supplied time
	    series and stores the training matrix and aligned target vector on the class/object.

	Args:
	    series (np.ndarray): Ordered univariate series used to train the lag-based
	                         forecasting model.

	Returns:
	    LagQuantileSeries | None: LagQuantileSeries | None returned by the forecasting
	                              operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails.
	    ValueError: Raised when the `train` operation cannot complete."""
	try:
		throw_if( 'series', series )
		if self.quantile <= 0.0 or self.quantile >= 1.0:
			raise ValueError( 'Argument "quantile" must be strictly between 0 and 1.' )

		if self.alpha < 0.0:
			raise ValueError( 'Argument "alpha" cannot be negative.' )

		x_data, y_data = self.lag_transform( series )
		self.model.fit( x_data, y_data )
		self.fitted_values = self.model.predict( x_data )
		self.prediction = None
		return self
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'LagQuantileSeries'
		exception.method = 'train( self, series: np.ndarray ) -> LagQuantileSeries | None'
		Logger( ).write( exception )
		raise exception

project

project(n_steps: int = 1) -> np.ndarray | None

Project future observations.

Purpose

Generates recursive forward forecasts by feeding each newly predicted value back into the lag window for subsequent forecast steps.

Parameters:

Name Type Description Default
n_steps int

Number of future periods to forecast.

1

Returns:

Type Description
ndarray | None

np.ndarray | None: np.ndarray | None returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

ValueError

Raised when the project operation cannot complete.

Source code in forecasting.py
def project( self, n_steps: int = 1 ) -> np.ndarray | None:
	"""Project future observations.

	Purpose:
	    Generates recursive forward forecasts by feeding each newly predicted value back
	    into the lag window for subsequent forecast steps.

	Args:
	    n_steps (int): Number of future periods to forecast.

	Returns:
	    np.ndarray | None: np.ndarray | None returned by the forecasting operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails.
	    ValueError: Raised when the `project` operation cannot complete."""
	try:
		throw_if( 'n_steps', n_steps )
		throw_if( 'training_data', self.training_data )
		throw_if( 'model', self.model )

		if n_steps < 1:
			raise ValueError( 'Argument "n_steps" must be greater than zero.' )

		last_window = self.training_data[ -1 ].astype( float ).copy( )
		preds = [ ]
		for _ in range( n_steps ):
			next_value = float( self.model.predict( last_window.reshape( 1, -1 ) )[ 0 ] )
			preds.append( next_value )
			last_window = np.roll( last_window, -1 )
			last_window[ -1 ] = next_value

		self.prediction = np.array( preds, dtype=float )
		return self.prediction
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'LagQuantileSeries'
		exception.method = 'project( self, n_steps: int=1 ) -> np.ndarray | None'
		Logger( ).write( exception )
		raise exception

score

score() -> float | None

Score fitted forecasts.

Purpose

Computes the coefficient of determination for fitted in-sample predictions against the stored training target values.

Returns:

Type Description
float | None

float | None: float | None returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

Source code in forecasting.py
def score( self ) -> float | None:
	"""Score fitted forecasts.

	Purpose:
	    Computes the coefficient of determination for fitted in-sample predictions against
	    the stored training target values.

	Returns:
	    float | None: float | None returned by the forecasting operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails."""
	try:
		throw_if( 'training_data', self.training_data )
		throw_if( 'training_values', self.training_values )
		return float( self.model.score( self.training_data, self.training_values ) )
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'LagQuantileSeries'
		exception.method = 'score( self ) -> float | None'
		Logger( ).write( exception )
		raise exception

analyze

analyze() -> Dict[str, float] | None

Analyze forecast residuals.

Purpose

Computes regression diagnostics for fitted in-sample predictions, including squared error, absolute error, explained variance, maximum error, median absolute error, and coefficient of determination.

Returns:

Type Description
Dict[str, float] | None

Dict[str, float] | None: Dict[str, float] | None returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

Source code in forecasting.py
def analyze( self ) -> Dict[ str, float ] | None:
	"""Analyze forecast residuals.

	Purpose:
	    Computes regression diagnostics for fitted in-sample predictions, including squared
	    error, absolute error, explained variance, maximum error, median absolute error, and
	    coefficient of determination.

	Returns:
	    Dict[str, float] | None: Dict[str, float] | None returned by the forecasting
	                             operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails."""
	try:
		throw_if( 'training_values', self.training_values )
		if self.fitted_values is None:
			throw_if( 'training_data', self.training_data )
			self.fitted_values = self.model.predict( self.training_data )

		self.mean_absolute_error = mean_absolute_error( self.training_values,
			self.fitted_values )
		self.mean_squared_error = mean_squared_error( self.training_values,
			self.fitted_values )
		self.root_mean_squared_error = float( np.sqrt( self.mean_squared_error ) )
		self.r2_score = r2_score( self.training_values, self.fitted_values )
		self.explained_variance_score = explained_variance_score( self.training_values,
			self.fitted_values )
		self.median_absolute_error = median_absolute_error( self.training_values,
			self.fitted_values )
		self.max_error = max_error( self.training_values, self.fitted_values )
		return { 'MAE': float( self.mean_absolute_error ),
			'MSE': float( self.mean_squared_error ),
			'RMSE': float( self.root_mean_squared_error ), 'R2': float( self.r2_score ),
			'EVS': float( self.explained_variance_score ),
			'MedianAE': float( self.median_absolute_error ), 'MAX': float( self.max_error ) }
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'LagQuantileSeries'
		exception.method = 'analyze( self ) -> Dict[str, float] | None'
		Logger( ).write( exception )
		raise exception

ARIMA

Bases: TimeSeries

Forecast with ARIMA.

Purpose

Wraps statsmodels ARIMA for nonseasonal autoregressive integrated moving-average forecasting. The class/object stores the fitted results object, produces forward projections, and reports regression-style diagnostics against fitted in-sample values.

Attributes:

Name Type Description
order Tuple[int, int, int]

ARIMA autoregressive, differencing, and moving-average order.

model Optional[ARIMA]

statsmodels ARIMA model object created during training.

results Optional[ARIMAResults]

Fitted statsmodels results object used for forecasts and diagnostics.

prediction Optional[ndarray]

Most recent forecast output.

train_data Optional[ndarray]

Time-series observations used to fit the forecasting model.

Source code in forecasting.py
class ARIMA( TimeSeries ):
	"""Forecast with ARIMA.

	Purpose:
	    Wraps statsmodels ARIMA for nonseasonal autoregressive integrated moving-average
	    forecasting. The class/object stores the fitted results object, produces forward
	    projections, and reports regression-style diagnostics against fitted in-sample
	    values.

	Attributes:
	    order (Tuple[int, int, int]): ARIMA autoregressive, differencing, and moving-average
	                                  order.
	    model (Optional[am.ARIMA]): statsmodels ARIMA model object created during training.
	    results (Optional[am.ARIMAResults]): Fitted statsmodels results object used for
	                                         forecasts and diagnostics.
	    prediction (Optional[np.ndarray]): Most recent forecast output.
	    train_data (Optional[np.ndarray]): Time-series observations used to fit the
	                                       forecasting model."""
	order: Tuple[ int, int, int ]
	model: Optional[ am.ARIMA ]
	results: Optional[ am.ARIMAResults ]
	prediction: Optional[ np.ndarray ]
	train_data: Optional[ np.ndarray ]

	def __init__( self, order: Tuple[ int, int, int ]=(1, 0, 0) ) -> None:
		"""Initialize ARIMA forecaster.

		Purpose:
		    Configures the nonseasonal ARIMA order and prepares model, fitted-result,
		    training-value, and prediction state for later forecasting.

		Args:
		    order (Tuple[int, int, int]): Autoregressive, differencing, and moving-average
		                                  order.

		Returns:
		    None: This method initializes the object and does not return a value."""
		self.order = order
		self.model = None
		self.results = None
		self.prediction = None
		self.train_data = None

	def train( self, series: np.ndarray ) -> ARIMA | None:
		"""Fit ARIMA model.

		Purpose:
		    Fits the statsmodels ARIMA model to the supplied ordered series and stores the
		    fitted results object for forecasting and diagnostics.

		Args:
		    series (np.ndarray): Ordered univariate series used to fit the forecasting model.

		Returns:
		    ARIMA | None: ARIMA | None returned by the forecasting operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails.
		    ValueError: Raised when the `train` operation cannot complete."""
		try:
			throw_if( 'series', series )
			values = np.asarray( series, dtype=float ).reshape( -1 )
			if len( values ) <= max( self.order[ 0 ], self.order[ 2 ], 1 ):
				msg = 'Argument "series" doesnt contain enough observations for the selected ARIMA'
				raise ValueError( msg )

			self.train_data = values
			self.model = am.ARIMA( endog=self.train_data, order=self.order )
			self.results = self.model.fit( )
			return self
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'ARIMA'
			exception.method = 'train( self, series: np.ndarray ) -> ARIMA | None'
			Logger( ).write( exception )
			raise exception

	def project( self, n_steps: int = 1 ) -> np.ndarray:
		"""Project future observations.

		Purpose:
		    Generates a forward forecast from the fitted statsmodels results object for the
		    requested number of future periods.

		Args:
		    n_steps (int): Number of future periods to forecast.

		Returns:
		    np.ndarray: np.ndarray returned by the forecasting operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails.
		    ValueError: Raised when the `project` operation cannot complete."""
		try:
			throw_if( 'results', self.results )
			throw_if( 'n_steps', n_steps )
			if n_steps < 1:
				raise ValueError( 'Argument "n_steps" must be greater than zero.' )

			forecast = np.asarray( self.results.forecast( steps=n_steps ), dtype=float )
			self.prediction = forecast
			return self.prediction
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'ARIMA'
			exception.method = 'project( self, n_steps: int=1 ) -> np.ndarray'
			Logger( ).write( exception )
			raise exception

	def score( self ) -> float | None:
		"""Score fitted forecasts.

		Purpose:
		    Computes the coefficient of determination for fitted in-sample values against the
		    original training series.

		Returns:
		    float | None: float | None returned by the forecasting operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails.
		    ValueError: Raised when the `score` operation cannot complete."""
		try:
			throw_if( 'train_data', self.train_data )
			throw_if( 'results', self.results )
			y_pred = np.asarray( self.results.fittedvalues, dtype=float ).reshape( -1 )
			y_true = np.asarray( self.train_data, dtype=float ).reshape( -1 )
			if len( y_pred ) == 0:
				raise ValueError( 'ARIMA fitted values are empty.' )

			y_true = y_true[ -len( y_pred ): ]
			return float( r2_score( y_true, y_pred ) )
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'ARIMA'
			exception.method = 'score( self ) -> float | None'
			Logger( ).write( exception )
			raise exception

	def analyze( self ) -> Dict[ str, float ] | None:
		"""Analyze forecast residuals.

		Purpose:
		    Computes regression diagnostics for fitted in-sample values against the original
		    training series, including squared error, absolute error, explained variance,
		    maximum error, median absolute error, and coefficient of determination.

		Returns:
		    Dict[str, float] | None: Dict[str, float] | None returned by the forecasting
		                             operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails.
		    ValueError: Raised when the `analyze` operation cannot complete."""
		try:
			throw_if( 'train_data', self.train_data )
			throw_if( 'results', self.results )
			y_pred = np.asarray( self.results.fittedvalues, dtype=float ).reshape( -1 )
			y_true = np.asarray( self.train_data, dtype=float ).reshape( -1 )
			if len( y_pred ) == 0:
				raise ValueError( 'ARIMA fitted values are empty.' )

			y_true = y_true[ -len( y_pred ): ]
			return { 'MSE': mean_squared_error( y_true, y_pred ),
				'RMSE': np.sqrt( mean_squared_error( y_true, y_pred ) ),
				'MAE': mean_absolute_error( y_true, y_pred ),
				'MedianAE': median_absolute_error( y_true, y_pred ),
				'R2': r2_score( y_true, y_pred ),
				'ExplainedVariance': explained_variance_score( y_true, y_pred ) }
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'ARIMA'
			exception.method = 'analyze( self ) -> Dict[str, float] | None'
			Logger( ).write( exception )
			raise exception

train

train(series: ndarray) -> ARIMA | None

Fit ARIMA model.

Purpose

Fits the statsmodels ARIMA model to the supplied ordered series and stores the fitted results object for forecasting and diagnostics.

Parameters:

Name Type Description Default
series ndarray

Ordered univariate series used to fit the forecasting model.

required

Returns:

Type Description
ARIMA | None

ARIMA | None: ARIMA | None returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

ValueError

Raised when the train operation cannot complete.

Source code in forecasting.py
def train( self, series: np.ndarray ) -> ARIMA | None:
	"""Fit ARIMA model.

	Purpose:
	    Fits the statsmodels ARIMA model to the supplied ordered series and stores the
	    fitted results object for forecasting and diagnostics.

	Args:
	    series (np.ndarray): Ordered univariate series used to fit the forecasting model.

	Returns:
	    ARIMA | None: ARIMA | None returned by the forecasting operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails.
	    ValueError: Raised when the `train` operation cannot complete."""
	try:
		throw_if( 'series', series )
		values = np.asarray( series, dtype=float ).reshape( -1 )
		if len( values ) <= max( self.order[ 0 ], self.order[ 2 ], 1 ):
			msg = 'Argument "series" doesnt contain enough observations for the selected ARIMA'
			raise ValueError( msg )

		self.train_data = values
		self.model = am.ARIMA( endog=self.train_data, order=self.order )
		self.results = self.model.fit( )
		return self
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'ARIMA'
		exception.method = 'train( self, series: np.ndarray ) -> ARIMA | None'
		Logger( ).write( exception )
		raise exception

project

project(n_steps: int = 1) -> np.ndarray

Project future observations.

Purpose

Generates a forward forecast from the fitted statsmodels results object for the requested number of future periods.

Parameters:

Name Type Description Default
n_steps int

Number of future periods to forecast.

1

Returns:

Type Description
ndarray

np.ndarray: np.ndarray returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

ValueError

Raised when the project operation cannot complete.

Source code in forecasting.py
def project( self, n_steps: int = 1 ) -> np.ndarray:
	"""Project future observations.

	Purpose:
	    Generates a forward forecast from the fitted statsmodels results object for the
	    requested number of future periods.

	Args:
	    n_steps (int): Number of future periods to forecast.

	Returns:
	    np.ndarray: np.ndarray returned by the forecasting operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails.
	    ValueError: Raised when the `project` operation cannot complete."""
	try:
		throw_if( 'results', self.results )
		throw_if( 'n_steps', n_steps )
		if n_steps < 1:
			raise ValueError( 'Argument "n_steps" must be greater than zero.' )

		forecast = np.asarray( self.results.forecast( steps=n_steps ), dtype=float )
		self.prediction = forecast
		return self.prediction
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'ARIMA'
		exception.method = 'project( self, n_steps: int=1 ) -> np.ndarray'
		Logger( ).write( exception )
		raise exception

score

score() -> float | None

Score fitted forecasts.

Purpose

Computes the coefficient of determination for fitted in-sample values against the original training series.

Returns:

Type Description
float | None

float | None: float | None returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

ValueError

Raised when the score operation cannot complete.

Source code in forecasting.py
def score( self ) -> float | None:
	"""Score fitted forecasts.

	Purpose:
	    Computes the coefficient of determination for fitted in-sample values against the
	    original training series.

	Returns:
	    float | None: float | None returned by the forecasting operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails.
	    ValueError: Raised when the `score` operation cannot complete."""
	try:
		throw_if( 'train_data', self.train_data )
		throw_if( 'results', self.results )
		y_pred = np.asarray( self.results.fittedvalues, dtype=float ).reshape( -1 )
		y_true = np.asarray( self.train_data, dtype=float ).reshape( -1 )
		if len( y_pred ) == 0:
			raise ValueError( 'ARIMA fitted values are empty.' )

		y_true = y_true[ -len( y_pred ): ]
		return float( r2_score( y_true, y_pred ) )
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'ARIMA'
		exception.method = 'score( self ) -> float | None'
		Logger( ).write( exception )
		raise exception

analyze

analyze() -> Dict[str, float] | None

Analyze forecast residuals.

Purpose

Computes regression diagnostics for fitted in-sample values against the original training series, including squared error, absolute error, explained variance, maximum error, median absolute error, and coefficient of determination.

Returns:

Type Description
Dict[str, float] | None

Dict[str, float] | None: Dict[str, float] | None returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

ValueError

Raised when the analyze operation cannot complete.

Source code in forecasting.py
def analyze( self ) -> Dict[ str, float ] | None:
	"""Analyze forecast residuals.

	Purpose:
	    Computes regression diagnostics for fitted in-sample values against the original
	    training series, including squared error, absolute error, explained variance,
	    maximum error, median absolute error, and coefficient of determination.

	Returns:
	    Dict[str, float] | None: Dict[str, float] | None returned by the forecasting
	                             operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails.
	    ValueError: Raised when the `analyze` operation cannot complete."""
	try:
		throw_if( 'train_data', self.train_data )
		throw_if( 'results', self.results )
		y_pred = np.asarray( self.results.fittedvalues, dtype=float ).reshape( -1 )
		y_true = np.asarray( self.train_data, dtype=float ).reshape( -1 )
		if len( y_pred ) == 0:
			raise ValueError( 'ARIMA fitted values are empty.' )

		y_true = y_true[ -len( y_pred ): ]
		return { 'MSE': mean_squared_error( y_true, y_pred ),
			'RMSE': np.sqrt( mean_squared_error( y_true, y_pred ) ),
			'MAE': mean_absolute_error( y_true, y_pred ),
			'MedianAE': median_absolute_error( y_true, y_pred ),
			'R2': r2_score( y_true, y_pred ),
			'ExplainedVariance': explained_variance_score( y_true, y_pred ) }
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'ARIMA'
		exception.method = 'analyze( self ) -> Dict[str, float] | None'
		Logger( ).write( exception )
		raise exception

SARIMA

Bases: TimeSeries

Forecast with SARIMA.

Purpose

Wraps statsmodels SARIMAX for seasonal autoregressive integrated moving-average forecasting. The class/object stores the fitted seasonal model, produces forward projections, and reports regression-style diagnostics against fitted in-sample values.

Attributes:

Name Type Description
order Tuple[int, int, int]

Nonseasonal autoregressive, differencing, and moving-average order.

seasonal_order Tuple[int, int, int, int]

Seasonal autoregressive, differencing, and moving-average order.

model Optional[SARIMAX]

statsmodels SARIMAX model object created during training.

results Optional[SARIMAXResults]

Fitted statsmodels results object used for forecasts and diagnostics.

training_data Optional[ndarray]

Time-series observations used to fit the forecasting model.

prediction Optional[ndarray]

Most recent forecast output.

Source code in forecasting.py
class SARIMA( TimeSeries ):
	"""Forecast with SARIMA.

	Purpose:
	    Wraps statsmodels SARIMAX for seasonal autoregressive integrated moving-average
	    forecasting. The class/object stores the fitted seasonal model, produces forward
	    projections, and reports regression-style diagnostics against fitted in-sample
	    values.

	Attributes:
	    order (Tuple[int, int, int]): Nonseasonal autoregressive, differencing, and
	                                  moving-average order.
	    seasonal_order (Tuple[int, int, int, int]): Seasonal autoregressive, differencing,
	                                                and moving-average order.
	    model (Optional[st.SARIMAX]): statsmodels SARIMAX model object created during
	                                  training.
	    results (Optional[st.SARIMAXResults]): Fitted statsmodels results object used for
	                                           forecasts and diagnostics.
	    training_data (Optional[np.ndarray]): Time-series observations used to fit the
	                                          forecasting model.
	    prediction (Optional[np.ndarray]): Most recent forecast output."""
	order: Tuple[ int, int, int ]
	seasonal_order: Tuple[ int, int, int, int ]
	model: Optional[ st.SARIMAX ]
	results: Optional[ st.SARIMAXResults ]
	training_data: Optional[ np.ndarray ]
	prediction: Optional[ np.ndarray ]

	def __init__( self, order: Tuple[ int, int, int ] = (1, 1, 1),
			seasonal: Tuple[ int, int, int, int ] = (0, 0, 0, 0) ) -> None:
		"""Initialize SARIMA forecaster.

		Purpose:
		    Configures nonseasonal and seasonal SARIMA orders and prepares model, fitted-result,
		    training-value, and prediction state for later forecasting.

		Args:
		    order (Tuple[int, int, int]): Nonseasonal autoregressive, differencing, and
		                                  moving-average order.
		    seasonal (Tuple[int, int, int, int]): Seasonal autoregressive, differencing,
		                                          moving-average, and period order.

		Returns:
		    None: This method initializes the object and does not return a value."""
		self.order = order
		self.seasonal_order = seasonal
		self.model = None
		self.results = None
		self.training_data = None
		self.prediction = None

	def train( self, series: np.ndarray ) -> SARIMA | None:
		"""Fit SARIMA model.

		Purpose:
		    Fits the statsmodels SARIMA model to the supplied ordered series and stores the
		    fitted results object for forecasting and diagnostics.

		Args:
		    series (np.ndarray): Ordered univariate series used to fit the forecasting model.

		Returns:
		    SARIMA | None: SARIMA | None returned by the forecasting operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails.
		    ValueError: Raised when the `train` operation cannot complete."""
		try:
			throw_if( 'series', series )
			values = np.asarray( series, dtype=float ).reshape( -1 )
			min_obs = max( self.order[ 0 ] + self.order[ 1 ] + self.order[ 2 ],
			               self.seasonal_order[ 0 ] + self.seasonal_order[ 1 ] +
			               self.seasonal_order[ 2 ], 1 )
			if len( values ) <= min_obs:
				msg = 'Argument "series" doesnt contain enough observations for the selected SARIMA'
				raise ValueError( msg )

			self.training_data = values
			self.model = st.SARIMAX( endog=self.training_data, order=self.order,
				seasonal_order=self.seasonal_order, enforce_stationarity=False,
				enforce_invertibility=False )
			self.results = self.model.fit( disp=False )
			return self
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'SARIMA'
			exception.method = 'train( self, series: np.ndarray ) -> SARIMA | None'
			Logger( ).write( exception )
			raise exception

	def project( self, n_steps: int = 1 ) -> np.ndarray:
		"""Project future observations.

		Purpose:
		    Generates a forward forecast from the fitted statsmodels results object for the
		    requested number of future periods.

		Args:
		    n_steps (int): Number of future periods to forecast.

		Returns:
		    np.ndarray: np.ndarray returned by the forecasting operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails.
		    ValueError: Raised when the `project` operation cannot complete."""
		try:
			throw_if( 'results', self.results )
			throw_if( 'n_steps', n_steps )
			if n_steps < 1:
				raise ValueError( 'Argument "n_steps" must be greater than zero.' )

			forecast = np.asarray( self.results.forecast( steps=n_steps ), dtype=float )
			self.prediction = forecast
			return self.prediction
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'SARIMA'
			exception.method = 'project( self, n_steps: int=1 ) -> np.ndarray'
			Logger( ).write( exception )
			raise exception

	def score( self ) -> float | None:
		"""Score fitted forecasts.

		Purpose:
		    Computes the coefficient of determination for fitted in-sample values against the
		    original training series.

		Returns:
		    float | None: float | None returned by the forecasting operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails.
		    ValueError: Raised when the `score` operation cannot complete."""
		try:
			throw_if( 'training_data', self.training_data )
			throw_if( 'results', self.results )
			y_pred = np.asarray( self.results.fittedvalues, dtype=float ).reshape( -1 )
			y_true = np.asarray( self.training_data, dtype=float ).reshape( -1 )
			if len( y_pred ) == 0:
				raise ValueError( 'SARIMA fitted values are empty.' )

			y_true = y_true[ -len( y_pred ): ]
			return float( r2_score( y_true, y_pred ) )
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'SARIMA'
			exception.method = 'score( self ) -> float | None'
			Logger( ).write( exception )
			raise exception

	def analyze( self ) -> Dict[ str, float ] | None:
		"""Analyze forecast residuals.

		Purpose:
		    Computes regression diagnostics for fitted in-sample values against the original
		    training series, including squared error, absolute error, explained variance,
		    maximum error, median absolute error, and coefficient of determination.

		Returns:
		    Dict[str, float] | None: Dict[str, float] | None returned by the forecasting
		                             operation.

		Raises:
		    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
		           calculation fails.
		    ValueError: Raised when the `analyze` operation cannot complete."""
		try:
			throw_if( 'training_data', self.training_data )
			throw_if( 'results', self.results )
			y_pred = np.asarray( self.results.fittedvalues, dtype=float ).reshape( -1 )
			y_true = np.asarray( self.training_data, dtype=float ).reshape( -1 )
			if len( y_pred ) == 0:
				raise ValueError( 'SARIMA fitted values are empty.' )

			y_true = y_true[ -len( y_pred ): ]
			return { 'MSE': mean_squared_error( y_true, y_pred ),
				'RMSE': np.sqrt( mean_squared_error( y_true, y_pred ) ),
				'MAE': mean_absolute_error( y_true, y_pred ),
				'MedianAE': median_absolute_error( y_true, y_pred ),
				'R2': r2_score( y_true, y_pred ),
				'ExplainedVariance': explained_variance_score( y_true, y_pred ) }
		except Exception as e:
			exception = Error( e )
			exception.module = 'mathy'
			exception.cause = 'SARIMA'
			exception.method = 'analyze( self ) -> Dict[str, float] | None'
			Logger( ).write( exception )
			raise exception

train

train(series: ndarray) -> SARIMA | None

Fit SARIMA model.

Purpose

Fits the statsmodels SARIMA model to the supplied ordered series and stores the fitted results object for forecasting and diagnostics.

Parameters:

Name Type Description Default
series ndarray

Ordered univariate series used to fit the forecasting model.

required

Returns:

Type Description
SARIMA | None

SARIMA | None: SARIMA | None returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

ValueError

Raised when the train operation cannot complete.

Source code in forecasting.py
def train( self, series: np.ndarray ) -> SARIMA | None:
	"""Fit SARIMA model.

	Purpose:
	    Fits the statsmodels SARIMA model to the supplied ordered series and stores the
	    fitted results object for forecasting and diagnostics.

	Args:
	    series (np.ndarray): Ordered univariate series used to fit the forecasting model.

	Returns:
	    SARIMA | None: SARIMA | None returned by the forecasting operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails.
	    ValueError: Raised when the `train` operation cannot complete."""
	try:
		throw_if( 'series', series )
		values = np.asarray( series, dtype=float ).reshape( -1 )
		min_obs = max( self.order[ 0 ] + self.order[ 1 ] + self.order[ 2 ],
		               self.seasonal_order[ 0 ] + self.seasonal_order[ 1 ] +
		               self.seasonal_order[ 2 ], 1 )
		if len( values ) <= min_obs:
			msg = 'Argument "series" doesnt contain enough observations for the selected SARIMA'
			raise ValueError( msg )

		self.training_data = values
		self.model = st.SARIMAX( endog=self.training_data, order=self.order,
			seasonal_order=self.seasonal_order, enforce_stationarity=False,
			enforce_invertibility=False )
		self.results = self.model.fit( disp=False )
		return self
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'SARIMA'
		exception.method = 'train( self, series: np.ndarray ) -> SARIMA | None'
		Logger( ).write( exception )
		raise exception

project

project(n_steps: int = 1) -> np.ndarray

Project future observations.

Purpose

Generates a forward forecast from the fitted statsmodels results object for the requested number of future periods.

Parameters:

Name Type Description Default
n_steps int

Number of future periods to forecast.

1

Returns:

Type Description
ndarray

np.ndarray: np.ndarray returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

ValueError

Raised when the project operation cannot complete.

Source code in forecasting.py
def project( self, n_steps: int = 1 ) -> np.ndarray:
	"""Project future observations.

	Purpose:
	    Generates a forward forecast from the fitted statsmodels results object for the
	    requested number of future periods.

	Args:
	    n_steps (int): Number of future periods to forecast.

	Returns:
	    np.ndarray: np.ndarray returned by the forecasting operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails.
	    ValueError: Raised when the `project` operation cannot complete."""
	try:
		throw_if( 'results', self.results )
		throw_if( 'n_steps', n_steps )
		if n_steps < 1:
			raise ValueError( 'Argument "n_steps" must be greater than zero.' )

		forecast = np.asarray( self.results.forecast( steps=n_steps ), dtype=float )
		self.prediction = forecast
		return self.prediction
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'SARIMA'
		exception.method = 'project( self, n_steps: int=1 ) -> np.ndarray'
		Logger( ).write( exception )
		raise exception

score

score() -> float | None

Score fitted forecasts.

Purpose

Computes the coefficient of determination for fitted in-sample values against the original training series.

Returns:

Type Description
float | None

float | None: float | None returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

ValueError

Raised when the score operation cannot complete.

Source code in forecasting.py
def score( self ) -> float | None:
	"""Score fitted forecasts.

	Purpose:
	    Computes the coefficient of determination for fitted in-sample values against the
	    original training series.

	Returns:
	    float | None: float | None returned by the forecasting operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails.
	    ValueError: Raised when the `score` operation cannot complete."""
	try:
		throw_if( 'training_data', self.training_data )
		throw_if( 'results', self.results )
		y_pred = np.asarray( self.results.fittedvalues, dtype=float ).reshape( -1 )
		y_true = np.asarray( self.training_data, dtype=float ).reshape( -1 )
		if len( y_pred ) == 0:
			raise ValueError( 'SARIMA fitted values are empty.' )

		y_true = y_true[ -len( y_pred ): ]
		return float( r2_score( y_true, y_pred ) )
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'SARIMA'
		exception.method = 'score( self ) -> float | None'
		Logger( ).write( exception )
		raise exception

analyze

analyze() -> Dict[str, float] | None

Analyze forecast residuals.

Purpose

Computes regression diagnostics for fitted in-sample values against the original training series, including squared error, absolute error, explained variance, maximum error, median absolute error, and coefficient of determination.

Returns:

Type Description
Dict[str, float] | None

Dict[str, float] | None: Dict[str, float] | None returned by the forecasting operation.

Raises:

Type Description
Error

Raised when validation, model execution, forecasting, scoring, or diagnostic calculation fails.

ValueError

Raised when the analyze operation cannot complete.

Source code in forecasting.py
def analyze( self ) -> Dict[ str, float ] | None:
	"""Analyze forecast residuals.

	Purpose:
	    Computes regression diagnostics for fitted in-sample values against the original
	    training series, including squared error, absolute error, explained variance,
	    maximum error, median absolute error, and coefficient of determination.

	Returns:
	    Dict[str, float] | None: Dict[str, float] | None returned by the forecasting
	                             operation.

	Raises:
	    Error: Raised when validation, model execution, forecasting, scoring, or diagnostic
	           calculation fails.
	    ValueError: Raised when the `analyze` operation cannot complete."""
	try:
		throw_if( 'training_data', self.training_data )
		throw_if( 'results', self.results )
		y_pred = np.asarray( self.results.fittedvalues, dtype=float ).reshape( -1 )
		y_true = np.asarray( self.training_data, dtype=float ).reshape( -1 )
		if len( y_pred ) == 0:
			raise ValueError( 'SARIMA fitted values are empty.' )

		y_true = y_true[ -len( y_pred ): ]
		return { 'MSE': mean_squared_error( y_true, y_pred ),
			'RMSE': np.sqrt( mean_squared_error( y_true, y_pred ) ),
			'MAE': mean_absolute_error( y_true, y_pred ),
			'MedianAE': median_absolute_error( y_true, y_pred ),
			'R2': r2_score( y_true, y_pred ),
			'ExplainedVariance': explained_variance_score( y_true, y_pred ) }
	except Exception as e:
		exception = Error( e )
		exception.module = 'mathy'
		exception.cause = 'SARIMA'
		exception.method = 'analyze( self ) -> Dict[str, float] | None'
		Logger( ).write( exception )
		raise exception

throw_if

throw_if(name: str, value: object) -> None

Validate a required forecasting argument.

Purpose

Enforces the presence of required time-series inputs, fitted models, design matrices, and forecast parameters before model execution. The validation accepts populated NumPy arrays and standard Python containers while rejecting null values and empty collections that cannot support training, projection, scoring, cross-validation, or diagnostic calculations.

Parameters:

Name Type Description Default
name str

Argument name used in the validation error message.

required
value object

Argument value checked for a null or empty state.

required

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Raises:

Type Description
ValueError

Raised when value is None or empty.

Source code in forecasting.py
def throw_if( name: str, value: object ) -> None:
	"""Validate a required forecasting argument.

	Purpose:
	    Enforces the presence of required time-series inputs, fitted models, design
	    matrices, and forecast parameters before model execution. The validation accepts
	    populated NumPy arrays and standard Python containers while rejecting null values
	    and empty collections that cannot support training, projection, scoring,
	    cross-validation, or diagnostic calculations.

	Args:
	    name (str): Argument name used in the validation error message.
	    value (object): Argument value checked for a null or empty state.

	Returns:
	    None: This function performs its work through side effects and does not return a
	          value.

	Raises:
	    ValueError: Raised when `value` is None or empty."""
	if value is None:
		raise ValueError( f'Argument "{name}" cannot be empty!' )

	if isinstance( value, np.ndarray ) and value.size == 0:
		raise ValueError( f'Argument "{name}" cannot be empty!' )

	if isinstance( value, (str, list, tuple, dict, set) ) and len( value ) == 0:
		raise ValueError( f'Argument "{name}" cannot be empty!' )