Data#
Primitives for loading and representing price time series.
DataLoader#
- class spreadpy.data.dataLoader.DataLoader(base_path: str | Path = '.')[source]#
Loads price time series from CSV, Parquet, or Feather files.
File lookup is by name:
base_path/<name>.<ext>where<ext>is tried in order.csv,.parquet,.feather. All loaded series are returned asPriceTimeSeriesobjects.- Parameters:
base_path (Union[str, Path]) – Root directory that contains the data files.
- load(name: str, date_col: str = 'Date', price_col: str = 'Close', freq: str | None = None) PriceTimeSeries[source]#
Load a single asset by name, auto-detecting csv / parquet / feather.
The file is searched under
base_path/<name>.<ext>where<ext>is tried in order.csv,.parquet,.feather.- Parameters:
name (str) – Asset identifier used as the file stem and series name.
date_col (str) – Column (or index) that contains the timestamps.
price_col (str) – Column that contains the price series.
freq (Optional[str]) – If given, the series is resampled to this pandas offset alias (e.g.
'W','ME') using the last price.
- Returns:
Cleaned price series for the asset.
- Return type:
- Raises:
FileNotFoundError – If no file matching
nameis found.
- load_from_dataframe(df: DataFrame, name: str, date_col: str = 'Date', price_col: str = 'Close') PriceTimeSeries[source]#
Load a price series directly from an existing DataFrame.
If
date_colis a column ofdf, it is set as the index. Otherwisedf.indexis assumed to already be the DatetimeIndex.- Parameters:
df (pd.DataFrame) – Source DataFrame.
name (str) – Label assigned to the resulting series.
date_col (str) – Column name holding timestamps (ignored if already the index).
price_col (str) – Column name holding the price series.
- Returns:
Cleaned price series.
- Return type:
- load_from_series(series: Series, name: str) PriceTimeSeries[source]#
Wrap an existing pandas Series as a
PriceTimeSeries.- Parameters:
series (pd.Series) – Raw price series with a DatetimeIndex (or an index coercible to DatetimeIndex).
name (str) – Label assigned to the series.
- Returns:
Cleaned price series.
- Return type:
- load_pair(name_y: str, name_x: str, date_col: str = 'Date', price_col: str = 'Close', freq: str | None = None) Tuple[PriceTimeSeries, PriceTimeSeries][source]#
Load two assets and align them on their common timestamps.
Each asset is loaded via
load()then the two series are inner-joined on their DatetimeIndex, so the returned pair shares an identical index with no missing observations.- Parameters:
name_y (str) – File stem for the dependent leg y.
name_x (str) – File stem for the independent leg x.
date_col (str) – Column (or index) that contains the timestamps.
price_col (str) – Column that contains the price series.
freq (Optional[str]) – If given, each series is resampled before alignment.
- Returns:
Aligned pair
(ts_y, ts_x)sharing a common DatetimeIndex.- Return type:
Tuple[PriceTimeSeries, PriceTimeSeries]
- validate(ts: PriceTimeSeries, min_obs: int = 252) None[source]#
Run basic sanity checks on a loaded series.
Raises
ValueErrorif any of the following conditions hold:Fewer than
min_obsobservations.Non-positive prices (prices ≤ 0).
Duplicate timestamps.
- Parameters:
ts (PriceTimeSeries) – Series to validate.
min_obs (int) – Minimum number of observations required (default 252).
- Raises:
ValueError – If any sanity check fails.
PriceTimeSeries#
- class spreadpy.data.priceTimeSeries.PriceTimeSeries(prices: Series, name: str | None = None, fill_method: str = 'ffill')[source]#
Thin wrapper around a pandas Series for price data.
Guarantees a clean, well-formed series at construction time: sorted DatetimeIndex, no NaN values, and a consistent name. NaNs are either forward-filled or dropped depending on
fill_method.- Parameters:
prices (pd.Series) – Raw price series. A non-DatetimeIndex is coerced to DatetimeIndex automatically.
name (str) – Optional label for the series (used in repr and downstream labelling).
fill_method (str) – NaN handling strategy —
'ffill'(forward-fill, then drop any leading NaNs) or'drop'(remove all NaN rows entirely).
- align(other: PriceTimeSeries) Tuple[PriceTimeSeries, PriceTimeSeries][source]#
Inner-join two series on their common timestamps.
Only observations present in both series are kept. The resulting pair shares an identical DatetimeIndex with no missing values.
- Parameters:
other (PriceTimeSeries) – Second price series to align with.
- Returns:
Pair
(self_aligned, other_aligned)restricted to the intersection of their DatetimeIndex.- Return type:
Tuple[PriceTimeSeries, PriceTimeSeries]
- log_returns() Series[source]#
Compute continuously compounded log-returns.
The log-return at bar \(t\) is defined as:
\[r_t = \log\!\left(\frac{P_t}{P_{t-1}}\right)\]The first observation is dropped (NaN from the lag).
- Returns:
Log-return series aligned with
self.index[1:].- Return type:
pd.Series
- resample(freq: str) PriceTimeSeries[source]#
Resample to a lower frequency, keeping the last price in each period.
Uses
pd.Series.resample(freq).last()then drops any resulting NaN bins (e.g. empty periods).- Parameters:
freq (str) – Pandas offset alias for the target frequency (e.g.
'W'for weekly,'ME'for month-end).- Returns:
Resampled price series.
- Return type:
- returns() Series[source]#
Compute simple (arithmetic) returns.
The return at bar \(t\) is defined as:
\[r_t = \frac{P_t - P_{t-1}}{P_{t-1}}\]The first observation is dropped (NaN from the lag).
- Returns:
Simple return series aligned with
self.index[1:].- Return type:
pd.Series
- slice(start, end) PriceTimeSeries[source]#
Extract a sub-series over the closed interval [start, end].
- Parameters:
start – Inclusive start timestamp (
pd.Timestampor any value accepted by pandas label-based indexing).end – Inclusive end timestamp.
- Returns:
Price sub-series restricted to [start, end].
- Return type: