models package

Submodules

models.bcgns module

class models.bcgns.BCGNS(theta, dim, device)[source]

Bases: object

Wrapper of the neural network model proposed in:

Barrera, D., Crépey, S., Gobet, E., Nguyen, H. D., & Saadeddine, B. (2022). Learning value-at-risk and expected shortfall. arXiv preprint arXiv:2209.06476.

and implemented in:

https://github.com/BouazzaSE/Learning-VaR-and-ES

Parameters:

  • theta: float

    desired confidence level.

  • dim: int

    dimension of the input space.

  • device: torch.device

    device to use.

Example of usage

import torch
import numpy as np
from models.bcgns import BCGNS #Import the model

y = np.random.randn(1500)  #Replace with your data
device = torch.device("cuda:0") #Device to use
theta = 0.05 #Set the desired confidence level
ti, tv = 1000, 1250 #Train and (train+val) lengths
x_lags_B = 25 #Number of lags to fed the neural network

# Prepare the data for the neural models
x = np.concatenate([
    y.reshape(-1,1)[k:-x_lags_B+k] for k in range(x_lags_B)], axis=1) #Create lagged data
x = torch.tensor(x, dtype=torch.float32).to(device) #x contains the past values of y
y_torch = torch.tensor(
    y.reshape(-1,1)[x_lags_B:], dtype=torch.float32).to(device) #y contains the target
x_train, y_train = x[:ti-x_lags_B], y_torch[:ti-x_lags_B] #Train data
x_val, y_val = x[ti-x_lags_B:tv-x_lags_B], y_torch[ti-x_lags_B:tv-x_lags_B] #Val data
x_test = x[tv-x_lags_B:] #Test data

mdl = BCGNS(theta, x_train.shape[1], device) #Initialize the model
mdl.fit(x_train, y_train, x_val, y_val, batch_size=16) #Fit the model

res = mdl.predict(x_test) #Predict
q_pred = res['qf'] #Quantile forecast
es_pred = res['ef'] #Expected shortfall forecast

Methods:

fit(x_train_, y_train_, x_val_, y_val_, batch_size)[source]

Fit the model.

INPUTS:
  • x_train_: torch.Tensor

    training input data.

  • y_train_: torch.Tensor

    training output data.

  • x_val_: torch.Tensor

    validation input data.

  • y_val_: torch.Tensor

    validation output data.

  • batch_size: int

    batch size.

predict(x_test_)[source]

Predict the quantile forecast and expected shortfall.

INPUTS:
OUTPUTS:
  • qf: ndarray

    quantile forecast.

  • ef: ndarray

    expected shortfall forecast.

models.caesar module

class models.caesar.CAESar(theta, spec='AS', lambdas={}, p=1, u=1)[source]

Bases: object

Conditional Autoregressive Expected Shortfall (CAESar) model for joint quantile and expected shortfall estimation. The model has been introduced is:

Gatta, F., Lillo, F., & Mazzarisi, P. (2024). CAESar: Conditional Autoregressive Expected Shortfall. arXiv preprint arXiv:2407.06619.

Parameters:

  • theta: float

    quantile level.

  • spec: str, optional

    specification of the model (SAV, AS, GARCH). Default is AS.

  • p: int, optional

    number of lags for the y variable. Default is 1.

  • u: int, optional

    number of lags for ^q and ^e. Default is 1.

Example of usage

import numpy as np
from models.caesar import CAESar #Import the model

y = np.random.randn(1500)  #Replace with your data
tv = 1250 #Training set length
theta = 0.05 #Set the desired confidence level

mdl = CAESar(theta, 'AS') #Initialize the model
res = mdl.fit_predict(y, tv, seed=2, return_train=True) # Fit and predict
q_fitted = res['qi'] #Quantile fitted values
es_fitted = res['ei'] #Expected shortfall fitted values
coef = res['beta'] #Fitted coefficients

q_pred = res['qf'] #Quantile forecast
e_pred = res['ef'] #Expected shortfall forecast

Methods:

fit(yi, seed=None, return_train=False, q0=None, nV=102, n_init=3, n_rep=5)[source]

Fit the CAESar model. INPUTS:

  • yi: ndarray

    target time series.

  • seed: int or None, optional

    random seed. Default is None.

  • return_train: bool, optional

    if True, the function returns the fitted values. Default is False.

  • q0: list of float or None, optional

    [initial quantile, initial expected shortfall]. If None, the initial quantile is computed as the empirical quantile in the first 10% of the training set; the initial expected shortfall as the tail mean in the same subset. Default is None.

  • nV: int, optional

    number of random initializations of the model coefficients. Default is 102.

  • n_init: int, optional

    number of best initializations to work with. Default is 3.

  • n_rep: int, optional

    number of repetitions for the optimization. Default is 5.

OUTPUTS:
  • qi: ndarray

    quantile forecast in the training set (if return_train=True).

  • ei: ndarray

    expected shortfall forecast in the training set (if return_train=True).

  • beta: ndarray

    optimized coefficients of the model. The shape is (2, self.n_parameters) (if return_train=True).

fit_predict(y, ti, seed=None, return_train=True, q0=None, nV=102, n_init=3, n_rep=5)[source]

Fit and predict the CAESar model. INPUTS:

  • y: ndarray

    target time series.

  • ti: int

    train set length.

  • seed: int or None, optional

    random seed. Default is None.

  • return_train: bool, optional

    return the train set. Default is True.

  • q0: list of float or None, optional

    [initial quantile, initial expected shortfall]. If None, the initial quantile is computed as the empirical quantile in the first 10% of the training set; the initial expected shortfall as the tail mean in the same subset. Default is None.

  • nV: int, optional

    number of random initializations of the model coefficients. Default is 102.

  • n_init: int, optional

    number of best initializations to work with. Default is 3.

  • n_rep: int, optional

    number of repetitions for the optimization. Default is 5.

OUTPUTS:
  • qi: ndarray

    quantile forecast in the training set (if return_train=True).

  • ei: ndarray

    expected shortfall forecast in the training set (if return_train=True).

  • qf: ndarray

    quantile forecast in the test set.

  • ef: ndarray

    expected shortfall forecast in the test set.

  • beta: ndarray

    optimized coefficients of the model. The shape is (2, self.n_parameters).

predict(yf=array([], dtype=float64))[source]

Predict the quantile. INPUTS:

  • yf: ndarray, optional

    test data. If yf is not empty, the internal state is updated with the last observation. Default is an empty list.

OUTPUTS:
  • qf: ndarray

    quantile forecast in the test set.

  • ef: ndarray

    expected shortfall forecast in the test set.

models.caviar module

class models.caviar.CAViaR(theta, spec='AS', p=1, u=1)[source]

Bases: object

Python implementation of the CAViaR regression for quantile estimation proposed in:

Engle, R. F., & Manganelli, S. (2004). CAViaR: Conditional autoregressive value at risk by regression quantiles. Journal of Business & Economic Statistics, 22(4), 367-381.

whose MATLAB implementation can be found in the author website:

https://simonemanganelli.org/Simone/Research.html

Parameters:

  • theta: float

    quantile level.

  • spec: str, optional

    specification of the model (SAV, AS, GARCH). Default is AS.

  • p: int, optional

    number of lags for the y variable. Default is 1.

  • u: int, optional

    number of lags for the quantile. Default is 1.

Example of usage

import numpy as np
from models.caviar import CAViaR #Import the model

y = np.random.randn(1500)  #Replace with your data
tv = 1250 #Training set length
theta = 0.05 #Set the desired confidence level

mdl = CAViaR(theta, 'AS') #Initialize the model
res = mdl.fit_predict(y, tv, seed=2) # Fit and predict

coef = res['beta'] #Fitted coefficients
q_pred = res['qf'] #Quantile forecast

Methods:

fit(yi, seed=None, return_train=False, q0=None)[source]

Fit the CAViaR model.

INPUTS:
  • yi: ndarray

    training data.

  • seed: int or None, optional

    random seed. Default is None.

  • return_train: bool, optional

    return the training prediction. Default is False.

  • q0: float, optional

    initial quantile. Default is None.

OUTPUTS:
  • qi: ndarray

    quantile forecast in the training set (if return_train=True).

  • beta: ndarray

    fitted coefficients of the regression (if return_train=True).

fit_predict(y, ti, seed=None, return_train=True, q0=None)[source]

Fit the model and predict the quantile.

INPUTS:
  • y: ndarray

    data.

  • ti: int

    train/test split point.

  • seed: int or None, optional

    random seed. Default is None.

  • return_train: bool, optional

    return the training prediction. Default is True.

  • q0: float, optional

    initial quantile. Default is None.

OUTPUTS:
  • qi: ndarray

    quantile forecast in the training set (if return_train=True).

  • qf: ndarray

    quantile forecast in the test set

  • beta: ndarray

    fitted coefficients of the regression

predict(yf=array([], dtype=float64))[source]

Predict the quantile.

INPUTS:
  • yf: ndarray, optional

    test data. If yf is not empty, the internal state is updated with the last observation.Default is an empty list.

OUTPUTS:
  • qf: ndarray

    quantile estimate.

models.gas module

class models.gas.GAS1(theta)[source]

Bases: object

Generative Autoregressive Score (GAS) one-factor model for Expected Shortfall estimation. It reproduces the model proposed in:

Patton, A. J., Ziegel, J. F., & Chen, R. (2019). Dynamic semiparametric models for expected shortfall (and value-at-risk). Journal of econometrics, 211(2), 388-413.

Parameters:

  • theta: float

    desired confidence level.

Example of usage

import numpy as np
from models.gas import GAS1 #Import the model

y_train, y_test = np.random.randn(1250), np.random.randn(250)  #Replace with your data
tv = 1250 #Training set length
theta = 0.05 #Set the desired confidence level

mdl = GAS1(theta) #Initialize the model
res_train = mdl.fit(y_train, seed=2, return_train=True) #Train the model
q_fitted = res_train['qi'] #Quantile fitted values
es_fitted = res_train['ei'] #Expected shortfall fitted values
coef = mdl.beta #Fitted coefficients

res_test = mdl.predict(y_test) # Predict out-of-sample
state_var = res_test['kf'] #State variable out-of-sample
q_pred = res_test['qf'] #Quantile forecast
es_pred = res_test['ef'] #Expected shortfall forecast

Methods:

fit(yi, seed=None, return_train=False)[source]

Fit the GAS1 model.

INPUTS:
  • yi: ndarray

    target time series.

  • seed: int or None, optional

    random seed. Default is None.

  • return_train: bool, optional

    if True, return the fitted variables. Default is False.

OUTPUTS:
  • qi: ndarray

    quantile forecast in the training set (if return_train=True).

  • ei: ndarray

    expected shortfall in the training set (if return_train=True).

  • ki: ndarray

    state variable in the training set (if return_train=True).

  • beta: ndarray

    optimized model parameters (if return_train=True).

fit_predict(y, ti, seed=None, return_train=False)[source]

Fit and predict the GAS1 model.

INPUTS:
  • y: ndarray

    target time series.

  • ti: int

    train set length.

  • seed: int or None, optional

    random seed. Default is None.

  • return_train: bool, optional

    if True, return the fitted values in training set. Default is False.

OUTPUTS:
  • qi: ndarray

    quantile forecast in the training set (if return_train=True).

  • ei: ndarray

    expected shortfall forecast in the training set (if return_train=True).

  • ki: ndarray

    state variable in the training set (if return_train=True).

  • qf: ndarray

    quantile forecast in the test set.

  • ef: ndarray

    expected shortfall forecast in the test set.

  • kf: ndarray

    state variable in the test set.

  • beta: ndarray

    optimized model parameters.

predict(yf=array([], dtype=float64))[source]

Predict the GAS1 model.

INPUTS:
  • yf: ndarray, optional

    target time series. If yf is not empty, the internal state is updated with the last observation. Default is an empty list.

OUTPUTS:
  • qf: ndarray

    quantile forecast in the test set.

  • ef: ndarray

    expected shortfall forecast in the test set.

  • kf: ndarray

    state variable in the test set.

class models.gas.GAS2(theta)[source]

Bases: object

Generative Autoregressive Score (GAS) two-factors model for Expected Shortfall estimation. It reproduces the model proposed in:

Patton, A. J., Ziegel, J. F., & Chen, R. (2019). Dynamic semiparametric models for expected shortfall (and value-at-risk). Journal of econometrics, 211(2), 388-413.

Parameters:

  • theta: float

    desired confidence level.

Example of usage

import numpy as np
from models.gas import GAS2 #Import the model

y = np.random.randn(1500)  #Replace with your data
tv = 1250 #Training set length
theta = 0.05 #Set the desired confidence level

mdl = GAS2(theta) #Initialize the model
res = mdl.fit_predict(y, tv, seed=2) # Fit and predict

q_pred = res['qf'] #Quantile forecast
es_pred = res['ef'] #Expected shortfall forecast

Methods:

fit(yi, seed=None, return_train=False)[source]

Fit the GAS2 model. INPUTS:

  • yi: ndarray

    target time series.

  • seed: int or None, optional

    random seed. Default is None.

  • return_train: bool, optional

    if True, return the fitted variables. Default is False.

OUTPUTS:
  • qi: ndarray

    quantile forecast in the training set (if return_train=True).

  • ei: ndarray

    expected shortfall forecast in the training set (if return_train=True).

  • beta: ndarray

    optimized model parameters (if return_train=True).

fit_predict(y, ti, seed=None, return_train=False)[source]

Fit and predict the GAS1 model. INPUTS:

  • y: ndarray

    target time series.

  • ti: int

    train set length.

  • seed: int or None, optional

    random seed. Default is None.

  • return_train: bool, optional

    if True, return the fitted values in training set. Default is False.

OUTPUTS:
  • qi: ndarray

    quantile forecast in the training set (if return_train=True).

  • ei: ndarray

    expected shortfall forecast in the training set (if return_train=True).

  • qf: ndarray

    quantile forecast in the test set.

  • ef: ndarray

    expected shortfall forecast in the test set.

  • beta

    optimized model parameters.

predict(yf=array([], dtype=float64))[source]

Predict the GAS2 model. INPUTS:

  • yf: ndarray, optional

    target time series. If yf is not empty, the internal state is updated with the last observation. Default is an empty list.

OUTPUTS:
  • qf: ndarray

    quantile forecast in the test set.

  • ef: ndarray

    expected shortfall forecast in the test set.

models.kcaviar module

class models.kcaviar.K_CAViaR(theta, spec='AS', n_points=10)[source]

Bases: object

Expected Shortfall estimation via Kratz approach [1] with CAViaR [2] for quantile regression.

[1] Kratz, M., Lok, Y. H., & McNeil, A. J. (2018). Multinomial VaR backtests: A simple implicit approach to backtesting expected shortfall. Journal of Banking & Finance, 88, 393-407.

[2] Engle, R. F., & Manganelli, S. (2004). CAViaR: Conditional autoregressive value at risk by regression quantiles. Journal of Business & Economic Statistics, 22(4), 367-381.

Parameters:

  • theta: float

    desired confidence level.

  • spec: str, optional

    specification of the model (SAV, AS, GARCH). Default is AS.

  • n_points: int, optional

    number of points for mean approximation. Default is 10.

Example of usage

import numpy as np
from models.kcaviar import K_CAViaR #Import the model

y = np.random.randn(1500)  #Replace with your data
tv = 1250 #Training set length
theta = 0.05 #Set the desired confidence level

mdl = K_CAViaR(theta, 'AS', 10) # Initialize the model
res = mdl.fit_predict(y, tv, seed=2, jobs=10) # Fit and predict

q_pred = res['qf'] #Quantile forecast
es_pred = res['ef'] #Expected shortfall forecast

Methods:

fit_predict(y, ti, seed=None, jobs=1, return_train=False, q0=None)[source]

Fit and predict the K-CAViaR model. INPUTS:

  • y: ndarray

    target time series.

  • ti: int

    train set length.

  • seed: int or None, optional

    random seed. Default is None.

  • jobs: int, optional

    number of parallel jobs. Default is 1.

  • return_train: bool, optional

    return the train set. Default is False.

  • q0: float

    initial quantile. Default is None.

OUTPUTS:
  • qi: ndarray

    quantile forecast in the training set (if return_train=True).

  • ei: ndarray

    expected shortfall in the training set (if return_train=True).

  • qf: ndarray

    quantile forecast in the test set.

  • ef: ndarray

    expected shortfall forecast in the test set.

models.kqrnn module

class models.kqrnn.K_QRNN(theta, params, dev, verbose=True)[source]

Bases: BaseNN

Expected Shortfall estimation via Kratz approach [1] with Quantile Regression Neural Network (QRNN) for quantile regression.

[1] Kratz, M., Lok, Y. H., & McNeil, A. J. (2018). Multinomial VaR backtests: A simple implicit approach to backtesting expected shortfall. Journal of Banking & Finance, 88, 393-407.

Parameters:

  • theta: float

    desired confidence level.

  • params: dict

    parameters of the model: - optimizer: str, optional

    optimizer to use, either ‘Adam’ or ‘RMSProp’. Default is ‘Adam’.

    • reg_type: str or None, optional

      type of regularization. Either None, ‘l1’, ‘l2’, or ‘l1_l2’. Default is None.

    • reg: float or list of float, optional

      regularization parameter. Not consider when reg_type=None. float when reg_type=’l1’ or ‘l2’. List with two floats (l1 and l2) when reg_type=’l1_l2’. Default is 0.

    • initializer: str, optional

      initializer for the weights. Either ‘glorot_normal’ or ‘glorot_uniform’. Default is ‘glorot_normal’.

    • activation: str, optional

      activation function. Either ‘relu’, ‘sigmoid’, or ‘tanh’. Default is ‘relu’.

    • lr: float, optional

      learning rate. Default is 0.01.

    • dropout: float, optional

      dropout rate. Default is 0.

    • batch_size: int, optional

      batch size. Default is -1, that is full batch. When batch_size < x_train.shape[0], mini-batch training is performed.

    • patience: int, optional

      patience for early stopping. Default is np.inf, that is no early stopping.

    • verbose: int, optional

      set after how many epochs the information on losses are printed. Default is 1.

  • dev: torch.device

    indicates the device where the model will be trained.

  • verbose: bool, optional

    if True, print the training progress. Default is True.

Example of usage

import torch
import numpy as np
from models.kqrnn import K_QRNN #Import the model

y = np.random.randn(1500)  #Replace with your data
device = torch.device("cuda:0") #Device to use
theta = 0.05 #Set the desired confidence level
ti, tv = 1000, 1250 #Train and (train+val) lengths
x_lags_Q = 25 #Number of lags to fed the neural network

# Parameters of the neural network
qrnn_par = {
    'activation': 'tanh', 'dropout': 0.2, 'reg': 1e-05, 'lr': 3e-05, 'batch_size': 128,
    'initializer': 'glorot_normal', 'optimizer': 'rmsprop', 'reg_type': 'l1',
    'n_epochs': 15000, 'patience': 500, 'theta': 0.05, 'n_points': 10,
    'layers': [x_lags_Q, 16, 128, 128, 10]}

# Prepare the data for the neural models
x = np.concatenate([
    y.reshape(-1,1)[k:-x_lags_Q+k] for k in range(x_lags_Q)], axis=1) #Create lagged data
x = torch.tensor(x, dtype=torch.float64).to(device) #x contains the past values of y
y_torch = torch.tensor(
    y.reshape(-1,1)[x_lags_Q:], dtype=torch.float64).to(device) #y contains the target
x_train, y_train = x[:ti-x_lags_Q], y_torch[:ti-x_lags_Q] #Train data
x_val, y_val = x[ti-x_lags_Q:tv-x_lags_Q], y_torch[ti-x_lags_Q:tv-x_lags_Q] #Val data
x_test = x[tv-x_lags_Q:] #Test data

mdl = K_QRNN(theta, qrnn_par, device, verbose=False) # Initialize the model
mdl.fit(x_train, y_train, x_val, y_val) # Fit the model

res = mdl.predict(x_test) #Predict
q_pred = res['qf'] #Quantile forecast
es_pred = res['ef'] #Expected shortfall forecast

Methods:

fit(x_train, y_train, x_val=None, y_val=None)[source]

Fit the model. With early stopping and batch training. INPUT:

  • x_train: torch.Tensor

    model’s train input of shape (batch_size, n_features).

  • y_train: torch.Tensor

    model’s train output of shape (batch_size, 1).

  • x_val: torch.Tensor, optional

    model’s validation input of shape (batch_size, n_features). Default is None.

  • y_val: torch.Tensor, optional

    model’s validation output of shape (batch_size, 1). Default is None.

OUTPUT:
  • None.

predict(x_test)[source]

Predict the quantile forecast and the expected shortfall. INPUT:

  • x_test: torch.Tensor

    input of the model; shape (batch_size, n_features).

OUTPUT:
  • qf: ndarray

    quantile forecast of the model.

  • ef: ndarray

    expected shortfall predicted by the model.

models.special module

class models.special.B_CAESar(theta, spec='AS', lambdas={})[source]

Bases: object

CAESar model for Expected Shortfall estimation - optimization only with Barrera loss. See [1], Supplementary Material B, for further details.

[1] Gatta, F., Lillo, F., & Mazzarisi, P. (2024). CAESar: Conditional Autoregressive Expected Shortfall. arXiv preprint arXiv:2407.06619.

Parameters:

  • theta: float

    desired confidence level.

  • spec: str, optional

    specification of the model (SAV, AS, GARCH). Default is AS.

  • lambdas: dict, optional

    lambdas for the soft constraints. Default is {‘r’:10}.

Example of usage

import numpy as np
from models.special import B_CAESar #Import the model

y = np.random.randn(1500)  #Replace with your data
tv = 1250 #Training set length
theta = 0.05 #Set the desired confidence level

mdl = B_CAESar(theta, 'AS') # Initialize the model
res = mdl.fit_predict(y, tv, seed=2) # Fit and predict

q_pred = res['qf'] #Quantile forecast
es_pred = res['ef'] #Expected shortfall forecast

Methods:

fit(yi, seed=None, return_train=False, q0=None, nV=102, n_init=3, n_rep=5)[source]

Fit the CAESar model. INPUTS:

  • yi: ndarray

    target time series.

  • seed: int or None, optional

    random seed. Default is None.

  • return_train: bool, optional

    if True, the function returns the fitted values. Default is False.

  • q0: list of float or None, optional

    [initial quantile, initial expected shortfall]. If None, the initial quantile is computed as the empirical quantile in the first 10% of the training set; the initial expected shortfall as the tail mean in the same subset. Default is None.

  • nV: int, optional

    number of random initializations of the model coefficients. Default is 102.

  • n_init: int, optional

    number of best initializations to work with. Default is 3.

  • n_rep: int, optional

    number of repetitions for the optimization. Default is 5.

OUTPUTS:
  • qi: ndarray

    Quantile forecast in the training set (if return_train=True).

  • ei: ndarray

    Expected Shortfall forecast in the training set (if return_train=True).

  • beta: ndarray

    optimized coefficients of the model. The shape is (2, n_parameters) (if return_train=True).

fit_predict(y, ti, seed=None, return_train=True, q0=None, nV=102, n_init=3, n_rep=5)[source]

Fit and predict the CAESar model. INPUTS:

  • y: ndarray

    target time series.

  • ti: int

    train set length.

  • seed: int or None, optional

    random seed. Default is None.

  • return_train: bool, optional

    return the train set. Default is True.

  • q0: list of float or None, optional

    [initial quantile, initial expected shortfall]. If None, the initial quantile is computed as the empirical quantile in the first 10% of the training set; the initial expected shortfall as the tail mean in the same subset. Default is None.

  • nV: int, optional

    number of random initializations of the model coefficients. Default is 102.

  • n_init: int, optional

    number of best initializations to work with. Default is 3.

  • n_rep: int, optional

    number of repetitions for the optimization. Default is 5.

OUTPUTS:
  • qi: ndarray

    Quantile forecast in the training set (if return_train=True).

  • ei: ndarray

    Expected Shortfall forecast in the training set (if return_train=True).

  • qf: ndarray

    Quantile forecast in the test set.

  • ef: ndarray

    Expected Shortfall forecast in the test set.

  • beta: ndarray

    optimized coefficients of the model. The shape is (2, n_parameters).

predict(yf=array([], dtype=float64))[source]

Predict the quantile. INPUTS:

  • yf: ndarray, optional

    test data. If yf is not empty, the internal state is updated with the last observation. Default is an empty list.

OUTPUTS:
  • qf: ndarray

    Quantile forecast in the test set.

  • ef: ndarray

    Expected Shortfall forecast in the test set.

class models.special.CAESar_No_Cross(theta, spec='AS', lambdas={})[source]

Bases: object

CAESar model for Expected Shortfall estimation - No cross term ^q <-> ^e. See [1], Supplementary Material A, for further details.

[1] Gatta, F., Lillo, F., & Mazzarisi, P. (2024). CAESar: Conditional Autoregressive Expected Shortfall. arXiv preprint arXiv:2407.06619.

Parameters:

  • theta: float

    desired confidence level.

  • spec: str, optional

    specification of the model (SAV, AS, GARCH). Default is AS.

  • lambdas: dict, optional

    lambdas for the soft constraints. Default is {‘q’:10, ‘e’:10}.

Example of usage

import numpy as np
from models.special import CAESar_No_Cross #Import the model

y = np.random.randn(1500)  #Replace with your data
tv = 1250 #Training set length
theta = 0.05 #Set the desired confidence level

mdl = CAESar_No_Cross(theta, 'AS') # Initialize the model
res = mdl.fit_predict(y, tv, seed=2) # Fit and predict

q_pred = res['qf'] #Quantile forecast
es_pred = res['ef'] #Expected shortfall forecast

Methods:

fit(yi, seed=None, return_train=False, q0=None, nV=102, n_init=3, n_rep=5)[source]

Fit the CAESar model. INPUTS:

  • yi: ndarray

    target time series.

  • seed: int or None, optional

    random seed. Default is None.

  • return_train: bool, optional

    if True, the function returns the fitted values. Default is False.

  • q0: list of float or None, optional

    [initial quantile, initial expected shortfall]. If None, the initial quantile is computed as the empirical quantile in the first 10% of the training set; the initial expected shortfall as the tail mean in the same subset. Default is None.

  • nV: int, optional

    number of random initializations of the model coefficients. Default is 102.

  • n_init: int, optional

    number of best initializations to work with. Default is 3.

  • n_rep: int, optional

    number of repetitions for the optimization. Default is 5.

OUTPUTS:
  • qi: ndarray

    Quantile forecast in the training set (if return_train=True).

  • ei: ndarray

    Expected Shortfall forecast in the training set (if return_train=True).

  • beta: ndarray

    optimized coefficients of the model. The shape is (2, self.n_parameters) (if return_train=True).

fit_predict(y, ti, seed=None, return_train=True, q0=None, nV=102, n_init=3, n_rep=5)[source]

Fit and predict the CAESar model. INPUTS:

  • y: ndarray

    target time series.

  • ti: int

    train set length.

  • seed: int or None, optional

    random seed. Default is None.

  • return_train: bool, optional

    return the train set. Default is True.

  • q0: list of float or None, optional

    [initial quantile, initial expected shortfall]. If None, the initial quantile is computed as the empirical quantile in the first 10% of the training set; the initial expected shortfall as the tail mean in the same subset. Default is None.

  • nV: int, optional

    number of random initializations of the model coefficients. Default is 102.

  • n_init: int, optional

    number of best initializations to work with. Default is 3.

  • n_rep: int, optional

    number of repetitions for the optimization. Default is 5.

OUTPUTS:
  • qi: ndarray

    Quantile forecast in the training set (if return_train=True).

  • ei: ndarray

    Expected Shortfall forecast in the training set (if return_train=True).

  • qf: ndarray

    Quantile forecast in the test set.

  • ef: ndarray

    Expected Shortfall forecast in the test set.

  • beta: ndarray

    optimized coefficients of the model. The shape is (2, n_parameters).

predict(yf=array([], dtype=float64))[source]

Predict the quantile. INPUTS:

  • yf: ndarray, optional

    test data. If yf is not empty, the internal state is updated with the last observation. Default is an empty list.

OUTPUTS:
  • qf: ndarray

    Quantile forecast in the test set.

  • ef: ndarray

    Expected Shortfall forecast in the test set.

class models.special.P_CAESar(theta, spec='AS', lambdas={})[source]

Bases: object

CAESar model for Expected Shortfall estimation - optimization only with Patton loss. See [1], Supplementary Material B, for further details.

[1] Gatta, F., Lillo, F., & Mazzarisi, P. (2024). CAESar: Conditional Autoregressive Expected Shortfall. arXiv preprint arXiv:2407.06619.

Parameters:

  • theta: float

    desired confidence level.

  • spec: str, optional

    specification of the model (SAV, AS, GARCH). Default is AS.

  • lambdas: dict, optional

    lambdas for the soft constraints. Default is {‘q’:10, ‘e’:10}.

Example of usage

import numpy as np
from models.special import P_CAESar #Import the model

y = np.random.randn(1500)  #Replace with your data
tv = 1250 #Training set length
theta = 0.05 #Set the desired confidence level

mdl = P_CAESar(theta, 'AS') # Initialize the model
res = mdl.fit_predict(y, tv, seed=2) # Fit and predict

q_pred = res['qf'] #Quantile forecast
es_pred = res['ef'] #Expected shortfall forecast

Methods:

fit(yi, seed=None, return_train=False, q0=None, nV=102, n_init=3, n_rep=5)[source]

Fit the CAESar model. INPUTS:

  • yi: ndarray

    target time series.

  • seed: int or None, optional

    random seed. Default is None.

  • return_train: bool, optional

    if True, the function returns the fitted values. Default is False.

  • q0: list of float or None, optional

    [initial quantile, initial expected shortfall]. If None, the initial quantile is computed as the empirical quantile in the first 10% of the training set; the initial expected shortfall as the tail mean in the same subset. Default is None.

  • nV: int, optional

    number of random initializations of the model coefficients. Default is 102.

  • n_init: int, optional

    number of best initializations to work with. Default is 3.

  • n_rep: int, optional

    number of repetitions for the optimization. Default is 5.

OUTPUTS:
  • qi: ndarray

    Quantile forecast in the training set (if return_train=True).

  • ei: ndarray

    Expected Shortfall forecast in the training set (if return_train=True).

  • beta: ndarray

    optimized coefficients of the model. The shape is (2, n_parameters) (if return_train=True).

fit_predict(y, ti, seed=None, return_train=True, q0=None, nV=102, n_init=3, n_rep=5)[source]

Fit and predict the CAESar model. INPUTS:

  • y: ndarray

    target time series.

  • ti: int

    train set length.

  • seed: int or None, optional

    random seed. Default is None.

  • return_train: bool, optional

    return the train set. Default is True.

  • q0: list of float or None, optional

    [initial quantile, initial expected shortfall]. If None, the initial quantile is computed as the empirical quantile in the first 10% of the training set; the initial expected shortfall as the tail mean in the same subset. Default is None.

  • nV: int, optional

    number of random initializations of the model coefficients. Default is 102.

  • n_init: int, optional

    number of best initializations to work with. Default is 3.

  • n_rep: int, optional

    number of repetitions for the optimization. Default is 5.

OUTPUTS:
  • qi: ndarray

    Quantile forecast in the training set (if return_train=True).

  • ei: ndarray

    Expected Shortfall forecast in the training set (if return_train=True).

  • qf: ndarray

    Quantile forecast in the test set.

  • ef: ndarray

    Expected Shortfall forecast in the test set.

  • beta: ndarray

    optimized coefficients of the model. The shape is (2, n_parameters).

predict(yf=array([], dtype=float64))[source]

Predict the quantile. INPUTS:

  • yf: ndarray, optional

    test data. If yf is not empty, the internal state is updated with the last observation. Default is an empty list.

OUTPUTS:
  • qf: ndarray

    Quantile forecast in the test set.

  • ef: ndarray

    Expected Shortfall forecast in the test set.

Module contents