Class GARCHModel<T>
- Namespace
- AiDotNet.TimeSeries
- Assembly
- AiDotNet.dll
Represents a Generalized Autoregressive Conditional Heteroskedasticity (GARCH) model for time series with changing volatility.
public class GARCHModel<T> : TimeSeriesModelBase<T>, ITimeSeriesModel<T>, IFullModel<T, Matrix<T>, Vector<T>>, IModel<Matrix<T>, Vector<T>, ModelMetadata<T>>, IModelSerializer, ICheckpointableModel, IParameterizable<T, Matrix<T>, Vector<T>>, IFeatureAware, IFeatureImportance<T>, ICloneable<IFullModel<T, Matrix<T>, Vector<T>>>, IGradientComputable<T, Matrix<T>, Vector<T>>, IJitCompilable<T>
Type Parameters
TThe numeric type used for calculations, typically float or double.
- Inheritance
-
GARCHModel<T>
- Implements
- Inherited Members
- Extension Methods
Remarks
The GARCH model is specifically designed for time series data that exhibits volatility clustering, where periods of high volatility are followed by periods of high volatility, and periods of low volatility are followed by periods of low volatility. It combines a mean model (typically an ARIMA model) with a variance model that captures the conditional heteroskedasticity.
For Beginners: GARCH models help predict both the value and the uncertainty of financial data.
Think of it like weather forecasting:
- Regular forecasting predicts the temperature (the mean value)
- GARCH also predicts how much the temperature might vary (the volatility)
For example, with stock prices:
- Some days, prices barely change (low volatility)
- Other days, prices swing wildly up and down (high volatility)
- Often, volatile periods tend to cluster together (volatility clustering)
GARCH helps model this behavior by:
- Using one model to predict the average price (mean model)
- Using another model to predict how much prices might fluctuate (volatility model)
This is especially useful for financial risk management, option pricing, and trading strategies.
Constructors
GARCHModel(GARCHModelOptions<T>?)
Initializes a new instance of the GARCHModel<T> class with the specified options.
public GARCHModel(GARCHModelOptions<T>? options = null)
Parameters
optionsGARCHModelOptions<T>The configuration options for the GARCH model. If null, default options are used.
Remarks
This constructor initializes the GARCH model with the provided configuration options or default options if none are specified. The options determine parameters such as the ARCH and GARCH orders, the mean model to use, and various other settings that control the model's behavior.
For Beginners: This sets up your GARCH model with your chosen settings.
When creating the model, you can specify:
- ARCHOrder: How many past squared errors to consider
- GARCHOrder: How many past volatilities to consider
- MeanModel: The model used to predict the average value
For example:
- GARCH(1,1) is common, meaning 1 past error term and 1 past volatility term
- Higher orders (like GARCH(2,2)) capture more complex patterns but need more data
If you don't provide options, the model uses sensible defaults.
Methods
CreateInstance()
Creates a new instance of the GARCH model with the same options.
protected override IFullModel<T, Matrix<T>, Vector<T>> CreateInstance()
Returns
- IFullModel<T, Matrix<T>, Vector<T>>
A new instance of the GARCH model.
Remarks
This method creates a new instance of the GARCH model with the same configuration options as the current instance. This is useful for creating copies or clones of the model for purposes like cross-validation or ensemble modeling.
For Beginners: This creates a new copy of the model with the same settings.
Creating a new instance:
- Makes a fresh copy of the model with the same configuration
- The new copy hasn't been trained yet
- You can train and use the copy independently from the original
This is helpful when you want to:
- Train multiple versions of the same model on different data subsets
- Compare different training approaches while keeping the base configuration the same
- Create an ensemble of similar models
DeserializeCore(BinaryReader)
Deserializes the model's core parameters from a binary reader.
protected override void DeserializeCore(BinaryReader reader)
Parameters
readerBinaryReaderThe binary reader to read from.
Remarks
This method reads the model's essential parameters from a binary stream, allowing a previously saved model to be loaded from a file or database. The deserialized parameters include the GARCH parameters (omega, alpha, beta), the residuals, the conditional variances, and the model options.
For Beginners: This loads a previously saved model.
The method:
- Reads the saved model data from a file or database
- Converts this data back into the model's parameters
- Reconstructs the model exactly as it was when saved
This is particularly useful when:
- You want to use a model that took a long time to train
- You want to ensure consistent results across different runs
- You need to deploy the model in a production environment
Think of it like opening a document you previously saved, allowing you to continue using the model without having to train it again.
EvaluateModel(Matrix<T>, Vector<T>)
Evaluates the model's performance on test data.
public override Dictionary<string, T> EvaluateModel(Matrix<T> xTest, Vector<T> yTest)
Parameters
xTestMatrix<T>The test input features matrix.
yTestVector<T>The test target values vector.
Returns
- Dictionary<string, T>
A dictionary containing various evaluation metrics.
Remarks
This method evaluates the model's performance on test data by generating predictions and calculating various error metrics. The returned metrics include Mean Squared Error (MSE), Root Mean Squared Error (RMSE), Mean Absolute Error (MAE), and Mean Absolute Percentage Error (MAPE).
For Beginners: This measures how accurate the model's predictions are.
The evaluation:
- Makes predictions for data the model hasn't seen before
- Compares these predictions to the actual values
- Calculates different types of error measurements:
- MSE (Mean Squared Error): Average of squared differences
- RMSE (Root Mean Squared Error): Square root of MSE, in the same units as your data
- MAE (Mean Absolute Error): Average of absolute differences
- MAPE (Mean Absolute Percentage Error): Average percentage difference
These metrics help you understand how well your model is likely to perform when forecasting new data. Lower values indicate better performance.
GetModelMetadata()
Returns metadata about the model, including its type, parameters, and configuration.
public override ModelMetadata<T> GetModelMetadata()
Returns
- ModelMetadata<T>
A ModelMetaData object containing information about the model.
Remarks
This method returns detailed metadata about the GARCH model, including its type, current parameters (omega, alpha, beta), and configuration options. This metadata can be used for model selection, comparison, documentation, and serialization purposes.
For Beginners: This provides information about your model's settings and state.
The metadata includes:
- The type of model (GARCH)
- Current parameter values (omega, alpha, beta)
- Information about the mean model
- Configuration settings from when you created the model
- A serialized version of the entire model
This information is useful for:
- Keeping track of different models you've created
- Comparing model configurations
- Documenting which settings worked best
- Sharing model information with others
- Storing model details in a database or registry
Predict(Matrix<T>)
Generates predictions for the given input data, including both mean and volatility forecasts.
public override Vector<T> Predict(Matrix<T> xNew)
Parameters
xNewMatrix<T>The input features matrix for the forecast period.
Returns
- Vector<T>
A vector containing the predicted values that incorporate both the mean forecast and volatility.
Remarks
This method generates forecasts for future time periods by first predicting the mean using the mean model, then forecasting the conditional variance using the GARCH parameters, and finally generating residuals based on the forecasted variance to create the final predictions.
For Beginners: This makes predictions that include both expected values and uncertainty.
The prediction process:
- Predicts the average value for each future period using the mean model
- Estimates how much uncertainty (volatility) to expect for each period
- Generates realistic random variations based on this volatility
- Combines the average prediction with these variations
This gives you not just a prediction, but a realistic scenario that includes the natural randomness seen in volatile data.
For example, instead of just predicting "tomorrow's stock price will be $100," it might predict "tomorrow's stock price will be $100 with a likely range of $95-$105."
PredictSingle(Vector<T>)
Predicts a single value based on the input vector.
public override T PredictSingle(Vector<T> input)
Parameters
inputVector<T>The input vector containing features for the prediction.
Returns
- T
The predicted value for the given input.
Remarks
This method generates a single prediction by combining the mean prediction from the mean model with a simulated residual based on the estimated volatility. It creates appropriate context for the prediction and ensures consistency with the model's learned patterns.
For Beginners: This generates a prediction for a single point in time.
The method:
- Creates a context for generating a single prediction
- Gets the mean prediction (expected value) from the mean model
- Estimates the volatility (uncertainty) for this time point
- Generates a realistic random variation based on this volatility
- Combines the mean prediction with the random variation
This approach provides not just an expected value, but also incorporates the appropriate level of randomness based on current volatility conditions. It's like predicting that tomorrow's temperature will be 75°F, but with a range of ±3° because weather conditions are currently stable.
Reset()
Resets the model to its initial state.
public override void Reset()
Remarks
This method resets the GARCH model to its initial state, clearing any learned parameters and returning to the initial configuration provided in the options. This is useful when you want to retrain the model from scratch.
For Beginners: This resets the model to start fresh.
Resetting the model:
- Clears all learned parameters (omega, alpha, beta)
- Reinitializes the mean model
- Empties stored residuals and variances
- Returns the model to its original state before training
This is useful when you want to:
- Train the model on different data
- Try different settings or approaches
- Start with a clean slate after experimentation
SerializeCore(BinaryWriter)
Serializes the model's core parameters to a binary writer.
protected override void SerializeCore(BinaryWriter writer)
Parameters
writerBinaryWriterThe binary writer to write to.
Remarks
This method writes the model's essential parameters to a binary stream, allowing the model to be saved to a file or database. The serialized parameters include the GARCH parameters (omega, alpha, beta), the residuals, the conditional variances, and the model options.
For Beginners: This saves the model so you can use it later.
The method:
- Converts the model's parameters to a format that can be saved
- Writes these values to a file or database
- Includes all the information needed to recreate the model exactly
This allows you to:
- Save a trained model for future use
- Share the model with others
- Use the model in other applications
It's like saving a document so you can open it again later without having to start from scratch.
TrainCore(Matrix<T>, Vector<T>)
Core implementation of the training logic for the GARCH model.
protected override void TrainCore(Matrix<T> x, Vector<T> y)
Parameters
xMatrix<T>The input features matrix.
yVector<T>The target values vector (the time series data to model).
Remarks
This method implements the core training mechanism for the GARCH model, which involves training the mean model first, then estimating the parameters of the variance equation based on the residuals. It follows a multi-step process that captures both the average behavior of the series and its changing volatility patterns.
For Beginners: This is the engine that powers the model's learning process.
This method:
- Trains the model that predicts the average values (mean model)
- Calculates the errors in these predictions (residuals)
- Sets up initial GARCH parameters to model the volatility
- Finds the optimal parameter values to best explain the volatility patterns
- Calculates the final volatility estimates for the historical data
It's the actual "learning" part of the model, where it discovers patterns in both the values and the volatility of your time series data.