tradeflow package

Subpackages

Submodules

tradeflow.ar_model module

class tradeflow.ar_model.AR(signs: Any, max_order: int | None = None, order_selection_method: Literal['pacf'] | None = None)[source]

Bases: TimeSeries

Autoregressive model for trade/order signs.

Parameters:
  • signs (array_like) – An array of signs where each element is either 1 (representing a buy) or -1 (representing a sell).

  • max_order (int, default None) – The maximum order of the autoregressive model. If None, the maximum order is set to 12*(nobs/100)^{1/4} as outlined in Schwert (1989).

  • order_selection_method ({'pacf'}, default None) –

    The method for selecting the order of the model. If None, the order of the model will be max_order.

    • ’pacf’ - Choose the model using the number of significant lags in the partial autocorrelation function of the time series of signs.

fit(method: Literal['yule_walker', 'burg', 'cmle_without_cst', 'cmle_with_cst', 'mle_without_cst', 'mle_with_cst'], significance_level: float = 0.05, check_stationarity: bool = True, check_residuals: bool = True) AR[source]

Estimate the model parameters.

If the chosen method estimates a constant term, the percentage of buy signs in the time series generated with these parameters will be close to the one from the training time series (‘ols_with_cst’, ‘mle_with_cst’).

Otherwise, the percentage of buy signs in the time series generated with these parameters will be close to 50% (‘yule_walker’, ‘burg’, ‘mle_without_cst’).

Parameters:
  • method ({'yule_walker', 'burg', 'ols_with_cst', 'mle_without_cst', 'mle_with_cst'}) –

    The method to use for estimating parameters.

    • ’yule_walker’ - Use the Yule Walker equations to estimate model parameters.

    • ’burg’ - Use Burg’s method to estimate model parameters.

    • ’cmle_without_cst’ - Use conditional maximum likelihood estimation without constant term to estimate model parameters.

    It can be solved with an OLS. * ‘cmle_with_cst’ - Use conditional maximum likelihood estimation with a constant term to estimate model parameters. It can be solved with an OLS. * ‘mle_without_cst’ - Use maximum likelihood estimation without constant term to estimate model parameters. * ‘mle_with_cst’ - Use maximum likelihood estimation with a constant term to estimate model parameters.

  • significance_level (float, default 0.05) – The significance level for stationarity (if check_stationarity is True) and residual autocorrelation (if check_residuals is True) tests.

  • check_stationarity (bool, default True) – If True, performs a stationarity check on the time series using the Augmented Dickey-Fuller unit root test. Raises an exception if the time series is not stationary according to the test.

  • check_residuals (bool, default True) – If True, performs a residual autocorrelation check using the Breusch-Godfrey test. Raises an exception if residuals are autocorrelated.

Returns:

The AR instance.

Return type:

AR

resid(seed: int | None = None) ndarray[source]

Estimate and return the residuals of the model.

Residuals are calculated as the difference between the observed values and the values predicted by the model using the fitted parameters.

Parameters:

seed (int, default None) – Seed used to initialize the pseudo-random number generator. If seed is None, then a random seed between 0 and 2^32 - 1 is used.

Returns:

The residuals of the AR model.

Return type:

np.ndarray

Raises:

ModelNotFittedException – If the model’s parameters are not set. This occurs if the model has not been fitted by calling fit().

simulate(size: int, seed: int | None = None) ndarray[source]

Simulate a time series of signs after the model has been fitted.

Parameters:
  • size (int) – The number of signs to simulate.

  • seed (int, default None) – Seed used to initialize the pseudo-random number generator. If seed is None, then a random seed between 0 and 2^32 - 1 is used.

Returns:

The simulated signs (+1 for buy, -1 for sell).

Return type:

np.ndarray

tradeflow.config module

tradeflow.enums module

class tradeflow.enums.FitMethodAR(value)[source]

Bases: Enum

BURG = 'burg'
CMLE_WITHOUT_CST = 'cmle_without_cst'
CMLE_WITH_CST = 'cmle_with_cst'
MLE_WITHOUT_CST = 'mle_without_cst'
MLE_WITH_CST = 'mle_with_cst'
YULE_WALKER = 'yule_walker'
class tradeflow.enums.OrderSelectionMethodAR(value)[source]

Bases: Enum

PACF = 'pacf'

tradeflow.exceptions module

exception tradeflow.exceptions.AutocorrelatedResidualsException[source]

Bases: Exception

Raised when the residuals are autocorrelated, based on the result of a hypothesis test

exception tradeflow.exceptions.IllegalNbLagsException[source]

Bases: Exception

Raised when the number of lags for a given time series is not valid

exception tradeflow.exceptions.IllegalValueException[source]

Bases: Exception

Raised when a value is not in a valid state

exception tradeflow.exceptions.ModelNotFittedException[source]

Bases: Exception

Raised when the model need the parameters, but it has not been fitted

exception tradeflow.exceptions.ModelNotSimulatedException[source]

Bases: Exception

Raised when the model need the simulated time series, but it has not been simulated

exception tradeflow.exceptions.NoConvergenceException[source]

Bases: Exception

Raised when the method used to estimate model parameters failed to converge

exception tradeflow.exceptions.NonStationaryTimeSeriesException[source]

Bases: Exception

Raised when the time series is not stationary

tradeflow.time_series module

class tradeflow.time_series.TimeSeries(signs: Any)[source]

Bases: ABC

Time series model for trade/order signs. Intended to be subclassed.

Parameters:

signs (array_like) – A 1-d endogenous response variable. The dependent variable.

static breusch_godfrey_test(resid: ndarray, nb_lags: int | None = None) Tuple[float, float][source]

Perform the Breusch-Godfrey test for residual autocorrelation.

Parameters:
  • resid (np.ndarray) – The residuals from a regression model. Must be a 1-dimensional array.

  • nb_lags (int, default None) – The number of lags to include in the test. If None, defaults to min(10, len(resid) // 5).

Returns:

  • lagrange_multiplier (float) – The value of the Lagrange Multiplier test statistic.

  • p_value (float) – The p-value for the test statistic.

calculate_acf(nb_lags: int, time_series: Any | None = None) ndarray[source]

Calculate the autocorrelation function of a time series of signs.

Parameters:
  • nb_lags (int) – Number of lags to return autocorrelation for.

  • time_series (array_like, default None) – The time series for which to compute the acf. If None, the original time series of the model is used.

Returns:

The autocorrelation for lags 0, 1, …, nlags. It includes the lag 0 autocorrelation (i.e., 1), thus the size is (nlags + 1,).

Return type:

np.ndarray

calculate_pacf(nb_lags: int, alpha: float | None = None, time_series: Any | None = None) ndarray | Tuple[ndarray, ndarray][source]

Calculate the partial autocorrelation function of a time series of signs.

Parameters:
  • nb_lags (int) – Number of lags to return autocorrelation for.

  • alpha (float, optional) – If a number is given, the confidence intervals for the given level are returned. For example, if alpha=0.05, 95 % confidence intervals are returned.

  • time_series (array_like, default None) – The time series for which to compute the pacf. If None, the original time series of the model is used.

Returns:

  • pacf (np.ndarray) – The partial autocorrelation for lags 0, 1, …, nb_lags. It includes the lag 0 autocorrelation (i.e., 1), thus the size is (nlags + 1,).

  • confint (ndarray, optional) – Confidence intervals for the pacf at lags 0, 1, …, nb_lags. The shape is (nlags + 1, 2). It is Returned if alpha is not None.

abstractmethod fit(method: str) TimeSeries[source]

Estimate the model parameters.

static is_time_series_stationary(time_series: Any, nb_lags: int | None = None, significance_level: float = 0.05, regression: Literal['c', 'ct', 'ctt', 'n'] = 'c') bool[source]

Test whether a time series is stationary at a given significance level using the Augmented Dickey-Fuller test.

Parameters:
  • time_series (array_like) – The time series to test for stationarity.

  • nb_lags (int, default None) – The number of lags to include in the test. If None, the default used by the test is applied.

  • significance_level (float, default 0.05) – The significance level for the test. If the p-value is less than or equal to this value, the time series is considered stationary.

  • regression ({'c', 'ct', 'ctt', 'n'}, default 'c') –

    Constant and trend order to include in regression.

    • ”c” : constant only (default).

    • ”ct” : constant and trend.

    • ”ctt” : constant, and linear and quadratic trend.

    • ”n” : no constant, no trend.

Returns:

True if the time series is stationary at the given significance level, False otherwise.

Return type:

bool

static percentage_buy(signs: Any) float[source]
plot_acf_and_pacf(nb_lags: int, log_scale: bool = True, time_series: Any | None = None) Figure[source]
abstractmethod resid() ndarray[source]

Estimate and return the residuals of the model.

abstractmethod simulate(size: int) ndarray[source]

Simulate a time series of signs after the model has been fitted.

simulation_summary(plot: bool = True, log_scale: bool = True, percentiles: Tuple[float, ...] = (50.0, 75.0, 95.0, 99.0, 99.9)) DataFrame[source]

Return a statistical summary comparing the original signs and the simulated ones.

The statistics are computed over the series counting the number of consecutive signs in a row.

The function is to be called after a model has been fitted and simulated.

Parameters:
  • plot (bool) – If True, plots two graphs. One comparing the autocorrelation function of the original and simulated time series, and another comparing the partial autocorrelation.

  • log_scale (bool, default true) – If True, use a log scale for plotting graphs, otherwise use a linear scale. It has no effect if plot is False.

  • percentiles (tuple of float) – The percentiles to use.

Returns:

A DataFrame containing the statistics for the original and simulated time series.

Return type:

pd.DataFrame

Module contents