Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
Python time series libraries store, transform, and analyze observations indexed by time. Analysis libraries add seasonal decomposition, change point detection, and automatic feature extraction on top of time-indexed tables. These libraries let analysts, monitoring tools, and AI agents find trends and changes in metrics and sensor data.
Popularity
pandas has the most monthly downloads in this comparison, at 706.0M, a count that covers all its data analysis work.
def ohlcv_fill_up_missing_data(
dataframe: DataFrame,
timeframe: str,
pair: str,
candle_type: CandleType = CandleType.SPOT,
) -> DataFrame:
"""
Fills up missing data with 0 volume rows,
using the previous close as price for "open", "high", "low" and "close", volume is set to 0
Candle types that carry a single value (e.g. funding rates) have no candle to fabricate -
inventing one would silently make up rates - so they are returned unchanged.
"""
if not candle_type_is_ohlcv(candle_type):
logger.debug(f"Skipping fillup for {pair}, {timeframe} - not applicable to {candle_type}.")
return dataframe
from freqtrade.exchange import timeframe_to_resample_freq
ohlcv_dict = {"open": "first", "high": "max", "low": "min", "close": "last", "volume": "sum"}
resample_interval = timeframe_to_resample_freq(timeframe)
# Resample to create "NAN" values df = dataframe.resample(resample_interval, on="date").agg(ohlcv_dict)
# Forwardfill close for missing columns df["close"] = df["close"].ffill()
# Use close for "open, high, low" df.loc[:, ["open", "high", "low"]] = df[["open", "high", "low"]].fillna(
value={
"open": df["close"],
"high": df["close"],
"low": df["close"],
}
)
df = df.reset_index()
len_before = len(dataframe)
len_after = len(df)
pct_missing = (len_after - len_before) / len_before if len_before > 0 else 0
if len_before != len_after:
message = (
f"Missing data fillup for {pair}, {timeframe}: "
f"before: {len_before} - after: {len_after} - {pct_missing:.2%}"
)
if pct_missing > 0.01:
logger.info(message)
else:
# Don't be verbose if only a small amount is missing logger.debug(message)
return df
Statsmodels
Provides statistical methods for modeling and analyzing related time series.
Downloads / mo
40.4M
Stars
11.8K
Last release
0.15.0
License
BSD-3-Clause
Strengths
Separates seasonal components.Return trend, seasonal, and residual components with seasonal_decompose.
Models related series together.Use VAR to estimate relationships between series and their lagged values.
Limitations
VAR expects stationary series.Transform trending series before fitting a standard stable VAR model.
def extract_trend_and_seasonality(
ts: TimeSeries,
freq: int | Sequence[int] | None = None,
model: Literal["additive", "multiplicative"] = MULTIPLICATIVE,
method: str = "naive",
return_residual: bool = False,
**kwargs,
) -> tuple[TimeSeries, TimeSeries] | tuple[TimeSeries, TimeSeries, TimeSeries]:
"""
Extracts trend, seasonality and residual from a TimeSeries instance using `statsmodels.tsa`.
Parameters
---------- ts
The series to decompose
freq
The seasonality period to use.
model
The type of decomposition to use: ``"additive"`` or ``"multiplicative"``. Defaults to ``"multiplicative"``.
method
The method to be used to decompose the series.
- "naive" : Seasonal decomposition using moving averages [1]_.
- "STL" : Season-Trend decomposition using LOESS [2]_. Only compatible with ``ADDITIVE`` model type.
- "MSTL" : Season-Trend decomposition using LOESS with multiple seasonalities [3]_.
Only compatible with ``ADDITIVE`` model type.
return_residual
If ``False`` (default), return only the trend and seasonal parts. If ``True``, also return the residual
part as a third time series.
kwargs
Other keyword arguments are passed down to the decomposition method.
Returns
------- Tuple[TimeSeries, TimeSeries] | Tuple[TimeSeries, TimeSeries, TimeSeries]
A tuple ``(trend, seasonal)`` when ``return_residual=False``, otherwise
``(trend, seasonal, residual)``.
References
---------- .. [1] https://www.statsmodels.org/devel/generated/statsmodels.tsa.seasonal.seasonal_decompose.html
.. [2] https://www.statsmodels.org/devel/generated/statsmodels.tsa.seasonal.STL.html
.. [3] https://www.statsmodels.org/devel/generated/statsmodels.tsa.seasonal.MSTL.html
"""
model = validate_mode(model, param="model", allowed={ADDITIVE, MULTIPLICATIVE})
if isinstance(freq, Sequence) and method != "MSTL":
raise_log(
ValueError(
f"{method} decomposition cannot be performed with more than one seasonality, received {freq}."
),
)
values = ts.to_series(copy=False)
if np.isnan(values).any():
raise_log(ValueError("`ts` must not contain missing values."))
if method == "naive":
decomp = seasonal_decompose(
values, period=freq, model=model, extrapolate_trend="period"
)
elif method == "STL":
if model != ADDITIVE:
raise_log(
ValueError(
f"Only ADDITIVE model is compatible with the STL method. Current model is {model}."
),
)
decomp = STL(endog=values, period=freq, **kwargs).fit()
elif method == "MSTL":
if model != ADDITIVE:
raise_log(
ValueError(
f"Only ADDITIVE model is compatible with the MSTL method. Current model is {model}."
),
)
decomp = MSTL(endog=values, periods=freq, **kwargs).fit()
else:
raise_log(ValueError(f"Unknown value for `method`: {method}."))
# keep components, ... only if the number of components matches season_shape = decomp.seasonal.shape
if len(season_shape) == 1:
season_shape = (season_shape[0], 1)
if season_shape[1] == ts.n_components:
components = ts.components
static_covariates = ts.static_covariates
hierarchy = ts.hierarchy
else:
components = None
static_covariates = None
hierarchy = None
season = TimeSeries(
times=ts.time_index,
values=decomp.seasonal,
components=components,
static_covariates=static_covariates,
hierarchy=hierarchy,
metadata=ts.metadata,
copy=False,
)
trend = TimeSeries(
times=ts.time_index,
values=decomp.trend,
components=ts.components,
copy=False,
**ts._attrs,
)
if not return_residual:
return trend, season
residual = TimeSeries(
times=ts.time_index,
values=decomp.resid,
components=ts.components,
copy=False,
**ts._attrs,
)
return trend, season, residual
import numpy as np
import ruptures as rpt
signal = np.r_[np.zeros(20), np.ones(20)]
model = rpt.Binseg(model='l2').fit(signal)
breakpoints = model.predict(n_bkps=1)
print(breakpoints)
def bootstrapping(
X,
kind="stationary",
q=0.05,
n_sim=6000,
window=3,
diag=False,
threshold=1e-15,
seed=0,
):
r"""
Estimates the uncertainty sets of mean and covariance matrix through the selected
bootstrapping method.
Parameters
---------- X : DataFrame of shape (n_samples, n_assets)
Assets returns DataFrame, where n_samples is the number of
observations and n_assets is the number of assets.
kind : str, optional
The bootstrapping method. The default value is 'stationary'. Possible values are:
- 'stationary': stationary bootstrapping method, see `StationaryBootstrap <https://bashtage.github.io/arch/bootstrap/generated/arch.bootstrap.StationaryBootstrap.html#arch.bootstrap.StationaryBootstrap>`_ for more details.
- 'circular': circular bootstrapping method, see `CircularBlockBootstrap <https://bashtage.github.io/arch/bootstrap/generated/arch.bootstrap.CircularBlockBootstrap.html#arch.bootstrap.CircularBlockBootstrap>`_ for more details.
- 'moving': moving bootstrapping method, see `MovingBlockBootstrap <https://bashtage.github.io/arch/bootstrap/generated/arch.bootstrap.MovingBlockBootstrap.html#arch.bootstrap.MovingBlockBootstrap>`_ for more details.
q : float, optional
Significance level for box and elliptical constraints.
The default is 0.05.
n_sim : int, optional
Number of simulations of the bootstrapping method.
The default is 6000.
window : int, optional
Block size of the bootstrapping method. Must be greather than 1
and lower than the n_samples - n_factors + 1
The default is 3.
diag : bool, optional
If consider only the main diagonal of covariance matrices of estimation
errors following :cite:`b-fabozzi2007robust`. The default is False.
threshold : float, optional
Parameter used to fix covariance matrices in case they are not positive semidefinite.
The default is 1e-15.
seed : int, optional
Seed used to generate random numbers for bootstrapping method.
The default is 0.
Returns
------- mu_l : DataFrame
The q/2 percentile of mean vector obtained through the selected
bootstrapping method.
mu_u : DataFrame
The 1-q/2 percentile of mean vector obtained through the selected
bootstrapping method.
cov_l : DataFrame
The q/2 percentile of covariance matrix obtained through the selected
bootstrapping method.
cov_u : DataFrame
The 1-q/2 percentile of covariance matrix obtained through the selected
bootstrapping method.
cov_mu : DataFrame
The covariance matrix of estimation errors of mean vector obtained
through the selected bootstrapping method.
cov_sigma : DataFrame
The covariance matrix of estimation errors of covariance matrix
obtained through the selected bootstrapping method.
k_mu : DataFrame
The square root of size of elliptical constraint of mean vector
estimation error based on 1-q percentile.
k_sigma : DataFrame
The square root of size of elliptical constraint of covariance matrix
estimation error based on 1-q percentile.
Raises
------ ValueError
When the value cannot be calculated.
"""
if not isinstance(X, pd.DataFrame):
raise TypeError("X must be a DataFrame")
if window >= X.shape[0] - window + 1:
raise ValueError("block must be lower than n_samples - window + 1")
elif window <= 1:
raise ValueError("block must be greather than 1")
cols = X.columns.tolist()
cols_2 = [i + "-" + j for i in cols for j in cols]
T, n = X.shape
mu = X.mean().to_numpy().reshape(1, n)
vec_Sigma = X.cov().to_numpy().reshape((1, n**2), order="F")
mus = np.zeros((n_sim, 1, n))
covs = np.zeros((n_sim, n, n))
if kind == "stationary":
gen = bs.StationaryBootstrap(window, X, seed=seed)
elif kind == "circular":
gen = bs.CircularBlockBootstrap(window, X, seed=seed)
elif kind == "moving":
gen = bs.MovingBlockBootstrap(window, X, seed=seed)
else:
raise ValueError("kind only can be 'stationary', 'circular' or 'moving'")
i = 0
for data in gen.bootstrap(n_sim):
A = data[0][0]
mus[i] = A.mean().to_numpy().reshape(1, n)
covs[i] = A.cov().to_numpy()
i += 1
# Box Constraint for Mean mu_l = np.percentile(mus, q=q / 2 * 100, axis=0, keepdims=True).reshape(1, n)
mu_u = np.percentile(mus, q=(1 - q / 2) * 100, axis=0, keepdims=True).reshape(1, n)
mu_l = pd.DataFrame(mu_l, index=[0], columns=cols)
mu_u = pd.DataFrame(mu_u, index=[0], columns=cols)
# Box Constraint for Covariance cov_l = np.percentile(covs, q=q / 2 * 100, axis=0, keepdims=True).reshape(n, n)
cov_u = np.percentile(covs, q=(1 - q / 2) * 100, axis=0, keepdims=True).reshape(
n, n
)
cov_l = pd.DataFrame(cov_l, index=cols, columns=cols)
cov_u = pd.DataFrame(cov_u, index=cols, columns=cols)
# Check and fix if upper and lower bound for Covariance are positive # semidefinite and fix when they are not if af.is_pos_def(cov_l) is False:
cov_l = af.cov_fix(cov_l, method="clipped", threshold=threshold)
if af.is_pos_def(cov_u) is False:
cov_u = af.cov_fix(cov_u, method="clipped", threshold=threshold)
# Elliptical Constraint for Mean A_mu = mus.reshape(n_sim, n) - np.repeat(mu, n_sim, axis=0)
cov_mu = np.cov(A_mu, rowvar=False)
if diag is True:
cov_mu = np.diag(np.diag(cov_mu))
k_mus = np.diag(A_mu @ inv(cov_mu) @ A_mu.T)
k_mu = np.percentile(k_mus, q=(1 - q) * 100) ** 0.5
cov_mu = pd.DataFrame(cov_mu, index=cols, columns=cols)
# Elliptical Constraint for Covariance A_Sigma = covs.reshape((n_sim, n**2), order="F")
A_Sigma = A_Sigma - np.repeat(vec_Sigma, n_sim, axis=0)
cov_sigma = np.cov(A_Sigma, rowvar=False)
cov_sigma = af.cov_fix(cov_sigma, method="clipped", threshold=threshold)
if diag is True:
cov_sigma = np.diag(np.diag(cov_sigma))
if af.is_pos_def(cov_sigma) is False:
cov_sigma = af.cov_fix(cov_sigma, method="clipped", threshold=threshold)
k_sigmas = np.diag(A_Sigma @ inv(cov_sigma) @ A_Sigma.T)
k_sigma = np.percentile(k_sigmas, q=(1 - q) * 100) ** 0.5
cov_sigma = pd.DataFrame(cov_sigma, index=cols_2, columns=cols_2)
return mu_l, mu_u, cov_l, cov_u, cov_mu, cov_sigma, k_mu, k_sigma
sktime
Provides a unified framework for machine learning with time series.
import stumpy
import numpy as np
if __name__ == "__main__":
your_time_series = np.random.rand(10000)
window_size = 50 # Approximately, how many data points might be found in a pattern
matrix_profile = stumpy.stump(your_time_series, m=window_size)
def _transform(self, X, y=None):
"""Transform X and return a transformed version.
private _transform containing core logic, called from transform
Parameters
---------- X : 3D np.ndarray of shape (n_cases, n_channels, n_timepoints)
or list of np.ndarray of shape [n_cases], where each array is a
2D np.ndarray of shape = [n_channels, n_timepoints_i]
input time series collection.
y : ignored argument for interface compatibility
Returns
------- Xt : np.ndarray of shape (n_cases, n_features)
Transformed data.
"""
Xt = _from_collection_to_long(X)
# lazy imports to avoid hard dependency from tsfresh import extract_features
Xt = extract_features(
Xt,
column_id="index",
column_value="value",
column_kind="column",
column_sort="time_index",
**self.default_fc_parameters_,
)
return Xt.to_numpy()
FAQ
pandas suits time-indexed data, resampling, and rolling calculations. statsmodels suits seasonal decomposition and models of related series. ruptures suits change point detection. tsfresh suits automatic feature extraction.
STUMPY is a library for a variety of time series data mining tasks.
pandas resamples timestamped observations to another frequency. Rolling windows can also apply an arbitrary function to each window.
tsfresh automates feature engineering from time series and other ordered data and selects features against target labels.
sktime is a unified framework for machine learning with time series.
For coding agents
Found your time-series library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.