quantlab.label.predefined.fret.Volatility#

class quantlab.label.predefined.fret.Volatility(factor_config)[source]#

Bases: _OpenToOpenLabel

Forward n-bar open-to-open volatility label.

At signal timestamp t the label is the sample standard deviation (ddof=1) of the one-bar returns adjOpen[k] / adjOpen[k - 1] - 1 for k in t + 2 .. t + n + 1, times sqrt(n): the volatility over the n bars a position entered at the next bar’s adjusted open is held, on the same span scale as Return of the same n. Like Return it is a Forward label with span = n and delay = 1, so lookahead_bars() is n + 1. It is NaN where any open in the window is missing and at timestamps without n + 1 later bars.

The output column is vol_{n}. Its kind is "volatility", so a model predicting it on the label’s own scale also reports the level metrics qlike and variance_ratio (see quantlab.model.evaluation.volatility_level_metrics).

Parameters:
factor_configFactorConfig

The KunQuant factor config of the trailing volatility. Set data_columns to ["adjOpen"] and kwargs["n_forward_periods"] to the horizon n, at least 2 (one return has no sample standard deviation).

Raises:
ValueError

If n_forward_periods is below 2.

Examples

One symbol whose opens alternate between two one-bar returns. Every window of two returns then holds one of each.

>>> import numpy as np, pandas as pd, xarray as xr
>>> from quantlab.backend.zarr import XrBackend
>>> from quantlab.factor.config import FactorConfig
>>> from quantlab.dataset.config import DatasetConfig
>>> from quantlab.dataset.stock import StockDataset
>>> from quantlab.label.predefined.fret import Volatility
>>> opens = 10.0 * np.cumprod([1.0, 1.1, 0.9, 1.1, 0.9, 1.1, 0.9, 1.1])
>>> XrBackend().to_internal(xr.Dataset(
...     {"adjOpen": (["timestamp", "symbol"], opens[:, None])},
...     coords={"timestamp": pd.date_range("2024-01-01", periods=8), "symbol": ["A"]},
... )).write("data/stock.zarr")
XrBackend()
>>> dataset = StockDataset(DatasetConfig(
...     raw_data_dir_path="data/raw", zarr_file_path="data/stock.zarr",
...     market="us_equity", frequency="1d",
... ))
>>> vol = Volatility(FactorConfig(
...     warmup_bars=3, dataset=dataset, mode="batch", data_columns=["adjOpen"],
...     kwargs={"n_forward_periods": 2}, njobs=1, file_path="data/vol.zarr",
... ))
>>> vol.lookahead_bars(), vol.span_bars(), vol.get_factor_names()
(3, 2, ('vol_2',))
>>> vol.compute("2024-01-01", "2024-01-08")["vol_2"].values[:, 0].round(4)
array([0.2, 0.2, 0.2, 0.2, 0.2, nan, nan, nan], dtype=float32)
kind = 'volatility'#

What the label measures: "return", or "volatility" for a label whose predicted level is used as a volatility. Model evaluation reads it to add level metrics, never the label’s class.