Metadata-Version: 2.4
Name: tempdisagg
Version: 0.6.4
Summary: Temporal disaggregation of time series: Chow-Lin, Fernandez, Litterman, Denton and more
Author-email: Jaime Vera-Jaramillo <jaimevera1107@gmail.com>
License: MIT
Project-URL: Homepage, https://github.com/jaimevera1107/tempdisagg
Project-URL: Issues, https://github.com/jaimevera1107/tempdisagg/issues
Keywords: temporal disaggregation,benchmarking,chow-lin,denton,time series,econometrics
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Mathematics
Classifier: Operating System :: OS Independent
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.23
Requires-Dist: pandas>=1.5
Requires-Dist: scipy>=1.9
Provides-Extra: plot
Requires-Dist: matplotlib>=3.5; extra == "plot"
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Requires-Dist: ruff>=0.4; extra == "dev"
Requires-Dist: mypy>=1.10; extra == "dev"
Requires-Dist: matplotlib>=3.5; extra == "dev"
Dynamic: license-file

<!--
  tempdisagg — project README
  Designed for GitHub's Markdown renderer. Detailed methodology remains in /docs.
  Visual asset: docs/images/readme_banner.svg
-->

<div align="center">

# tempdisagg

<p align="center">
  <a href="./docs/images/Tempdisagg Temporal Series Logo.png">
    <img
      src="./docs/images/Tempdisagg Temporal Series Logo.png"
      alt="tempdisagg logo"
      width="320"
    />
  </a>
</p>

<p align="center">
  <sub><sup><em>Logo generated with ChatGPT (OpenAI).</em></sup></sub>
</p>

**Temporal disaggregation of time series, in Python.**

Turn annual or quarterly observations into a finer time series, while preserving the published benchmarks.

[![PyPI](https://img.shields.io/pypi/v/tempdisagg?style=flat-square&label=PyPI&labelColor=15243B&color=29A88F)](https://pypi.org/project/tempdisagg/)
![Python](https://img.shields.io/badge/Python-3.10%2B-15243B?style=flat-square&labelColor=15243B&color=44648E)
[![License](https://img.shields.io/badge/License-MIT-15243B?style=flat-square&labelColor=15243B&color=44648E)](LICENSE)
[![R reference](https://img.shields.io/badge/R%20reference-validated-15243B?style=flat-square&labelColor=15243B&color=29A88F)](#validation-against-r)

[**Get started**](#get-started) · [**Explore methods**](#choose-a-method) · [**Use your data**](#bring-your-own-data) · [**Documentation**](#documentation)

</div>

---

`tempdisagg` estimates a high-frequency series (quarterly, monthly) from a
low-frequency one (annual, quarterly) and optional indicators, so that the
estimates **add up exactly to the published benchmarks**. It implements the
classical econometric methods (Chow–Lin, Litterman, Fernández, Denton) with
the same formulas and defaults as the R package `tempdisagg`, and it checks
that equivalence in CI against outputs generated by R.

Three things the library will not do: guess, hide a decision, or fit silently
when something is not identified. Missing values, incomplete periods, flat
likelihoods and conflicting constraints are reported, never patched over.

## Contents

1. [Install](#install)
2. [Five-minute workflow](#five-minute-workflow)
3. [Reading a result](#reading-a-result)
4. [Choosing a method](#choosing-a-method)
5. [Your own data](#your-own-data)
6. [Constraints, benchmarks and reconciliation](#constraints-benchmarks-and-reconciliation)
7. [Comparing models](#comparing-models)
8. [Validation against R](#validation-against-r)
9. [What the library does not do](#what-the-library-does-not-do)
10. [Documentation](#documentation), [development](#development), [license](#license)

## Install

```bash
pip install tempdisagg              # numpy, pandas, scipy
pip install "tempdisagg[plot]"      # plus matplotlib for result.plot()
```

Python 3.10 or newer.

## Five-minute workflow

The bundled Swiss pharmaceutical data has annual sales and quarterly trade
indicators (the example of the R package vignette).

```python
import tempdisagg as td
from tempdisagg.datasets import load_swisspharma

sales, trade = load_swisspharma()      # annual Series, quarterly DataFrame

result = td.TemporalDisaggregator("chow-lin-maxlog").fit(sales, trade[["exports"]])

quarterly = result.values              # pd.Series, quarterly PeriodIndex
print(result.summary())
```

```text
'chow-lin-maxlog' disaggregation with 'sum' conversion
36 low-freq. obs. converted to 158 high-freq. obs.

Coefficients:
             Estimate  Std. Error  t value    Pr(>|t|)
(Intercept)   12.4089     1.49303  8.31119 1.06081e-09  ***
exports     0.0133918 0.000167167  80.1106 2.53953e-40  ***

Residual std. error (GLS): 10.4417 on 34 degrees of freedom
Multiple R-squared: 0.9947   Adjusted R-squared: 0.9946
AR1-Parameter: 0.000000 (estimated by maxlog, truncated (unconstrained -0.306953))
Max. aggregation error: 3.411e-13
```

The quarterly values sum to the annual sales in every year (that is the
"aggregation error" line). The indicators run two years beyond the last
annual observation, so the last eight quarters are extrapolated and marked
as unconstrained in `result.to_frame()`.

When all you need is the series:

```python
quarterly = td.disaggregate(sales, trade[["exports"]])                 # same model
quarterly = td.disaggregate(sales, method="denton-cholette", high_freq="Q")  # no indicator
```

## Reading a result

`fit()` returns a `DisaggregationResult`. The parts you will use:

| Attribute | What it holds |
|---|---|
| `values` | The estimate, high-frequency `PeriodIndex` |
| `to_frame()` | Estimate, standard error, indicators, and flags for extrapolated or filled periods |
| `prediction_interval(0.95)` | Lower and upper bounds per period |
| `coefficients`, `regression` | GLS coefficients, standard errors, p-values, R², AIC/BIC, residual autocorrelation |
| `rho` | How the AR parameter was obtained: value, criterion, truncation, whether it is identified, the full profile |
| `preprocessing` | Every period that was completed or padded, so nothing artificial goes unnoticed |
| `aggregation_error` | Largest deviation from a benchmark; numerically zero by construction |

Two numbers deserve a second look before trusting a fit:

**`result.rho`.** The autoregressive parameter is estimated by maximum
likelihood over a grid plus a local search. `rho.identified` is `False` when
the likelihood is flat (then the estimate does not depend on ρ at all), and a
`MultipleOptimaWarning` tells you when the criterion has competing optima.
Negative estimates are truncated to zero by default, as in R; pass
`truncated_rho=-1` to keep them.

**`result.prediction_interval()`.** The variance accounts for both the
regression uncertainty and the distribution of the low-frequency residual
within each period. With a few dozen annual observations the intervals are
wide; that is the honest width, not a bug.

## Choosing a method

| Family | Residual process | Use when | Preset |
|---|---|---|---|
| Chow–Lin | stationary AR(1) | you have a good indicator and want the standard | `chow-lin-maxlog` (default) |
| Litterman | random walk with AR(1) innovations | residuals are very persistent | `litterman-maxlog` |
| Fernández | random walk | Litterman with ρ fixed at 0 | `fernandez` |
| OLS | white noise | residuals show no autocorrelation | `ols` |
| Denton / Denton–Cholette | none (movement preservation) | one indicator, no regression wanted | `denton`, `denton-cholette` |
| Uniform | none | no indicator at all | `uniform` |
| Dynamic Chow–Lin | lagged dependent variable | experimental | `dynamic-maxlog` |

Every preset is a dataclass whose fields are its settings, so the question
"does this method have an intercept, and can I change it?" is answered by
the object itself:

```python
from tempdisagg.methods import ChowLin, make_method

ChowLin().include_intercept                       # True
make_method("fernandez", include_intercept=False)  # Fernandez(include_intercept=False)
td.TemporalDisaggregator("chow-lin-fixed", fixed_rho=0.5)
td.TemporalDisaggregator("denton-cholette", criterion="additive", h=2)
```

A setting that exists but has no effect in the chosen configuration (for
example `fixed_rho` with `rho_method="maxlog"`) raises an
`IneffectiveParameterWarning` instead of being ignored. The full list of
presets (`chow-lin-minrss-ecotrim`, `chow-lin-minrss-quilis`, `litterman-fixed`,
`fast`, ...) and their R equivalents is in [configuration](docs/configuration.md).

`conversion` says how the high-frequency values relate to the benchmark:
`"sum"` (default), `"average"`, `"first"` or `"last"`.

## Your own data

Two ingredients: the low-frequency target and, optionally, the indicators.

```python
import numpy as np
import pandas as pd

years = pd.period_range("2016", periods=8, freq="Y")
quarters = pd.period_range("2016Q1", periods=32, freq="Q")

y_low = pd.Series([200, 230, 260, 280, 315, 345, 380, 415], index=years)
indicators = pd.DataFrame({"activity": np.linspace(30, 110, 32)}, index=quarters)

result = td.TemporalDisaggregator("chow-lin-maxlog").fit(y_low, indicators)
```

- **Indexes.** `PeriodIndex` is the reference. `DatetimeIndex` works when the
  frequency is set or inferable, including start-anchored ones
  (`pd.date_range(freq="QS")`, `"MS"`). Fiscal years (`freq="Y-JUN"`) are
  supported as targets.
- **No calendar?** `fit_arrays(y_low, indicators, frequency_ratio=4)` takes
  NumPy arrays with a fixed ratio. `fit_long_format(frame, x_cols=[...])`
  accepts the legacy long table (one row per high-frequency period, target
  repeated within its group).
- **Missing targets.** `NaN` in `y_low` means "no benchmark for this
  period", not zero; the period is estimated without a constraint and a
  `MissingTargetWarning` says so.
- **Missing or incomplete indicators.** By default (`completion=True`) gaps
  are filled by documented rules and listed in `result.preprocessing`
  (`ArtificialDataWarning`). Use `completion=False` to reject them instead.
  `padding=(before, after)` extends the grid beyond the indicators.
- **Validation.** Non-numeric, infinite, duplicated or unsorted inputs are
  rejected with an `InputValidationError`; a collinear indicator set raises
  `SingularDesignError` with the likely cause.

## Constraints, benchmarks and reconciliation

Beyond the aggregation constraint, you can impose what you already know.

```python
# A quarter whose value is published: keep it exactly.
known = td.known_values(pd.Series([30.0], index=pd.PeriodIndex(["1975Q1"], freq="Q")))
result = td.TemporalDisaggregator("chow-lin-maxlog").fit(
    sales, trade[["exports"]], constraints=known
)

# Benchmarks at an intermediate frequency (e.g. semesters between years and quarters).
semesters = td.aggregate_constraints(semester_totals, high_freq="Q")
```

Constraints that contradict each other or the benchmarks raise an
`InfeasibleConstraintError` listing the periods involved.

```python
# Several series that must add up to a known high-frequency total.
reconciled = td.CrossSectionalReconciler().reconcile_results(
    {"domestic": result_a, "foreign": result_b}, total=high_freq_total
)
reconciled.values              # DataFrame; rows sum to the total, each column keeps its benchmarks

# A series that must not go negative.
non_negative = td.NonNegativeReconciler().reconcile(result)
```

Both reconcilers refuse impossible requests rather than returning the
closest thing: a negative benchmark cannot be met by a non-negative series,
and a total whose annual sums differ from the series' benchmarks is
rejected with the mismatch per year.

Other building blocks: `td.disaggregate_ratio` for rates and shares,
`td.level_shift` and `td.impulse` to build dummy indicators, and
`td.SeriesSplicer` to join series across a methodological break.

## Comparing models

`backtest` re-estimates each candidate on a shrinking sample and measures the
error on the held-out benchmarks, so the comparison is out of sample.

```python
from tempdisagg import Candidate, backtest

report = backtest(
    sales,
    {
        "exports": Candidate(td.TemporalDisaggregator("chow-lin-maxlog"), trade[["exports"]]),
        "both": Candidate(td.TemporalDisaggregator("chow-lin-maxlog"), trade),
        "fernandez": Candidate(td.TemporalDisaggregator("fernandez"), trade[["exports"]]),
    },
    holdout=5,
)
print(report.summary())
```

```text
           n_origins       bias        MAE       RMSE    MAPE_%
exports            5  11.211825  57.754352  63.657024  5.892067
both               5  -5.055192  62.151090  70.788436  6.313198
fernandez          5  10.511914  70.616875  78.823176  7.080570
```

`report.predictions`, `report.errors` and `report.failures` hold the detail;
a candidate that cannot be fitted at some origin is reported, not dropped.

## Validation against R

The reference implementation is the R package `tempdisagg` (Sax and Steiner,
2013). Two layers of tests enforce the equivalence:

- the coefficients, standard errors and R² printed in the R vignette are
  asserted directly in `tests/test_r_parity.py`;
- 29 cases covering every method, criterion and conversion are generated by
  `tests/reference/generate_r_reference.R`; the CI workflow installs R,
  regenerates them and compares predictions and statistics, with tolerances
  of 1e-8 for fixed ρ and a documented protocol for estimated ρ (R's
  `optimize()` stops at about 1e-4, so the two optima are compared on the
  criterion itself and then re-fitted at R's ρ).

The reference files ship with the repository, so `pytest` runs the
comparison locally too.

## What the library does not do

- It does not interpolate benchmarks: a missing target stays unconstrained.
- It does not fall back to another method when the requested one fails.
- It does not extrapolate without telling you: periods beyond the last
  benchmark are flagged in `to_frame()` and carry wider intervals.
- It does not pick ρ silently: truncation, boundary solutions and flat
  likelihoods are reported in `result.rho` and as warnings.
- It does not offer Bayesian or state-space disaggregation, nor seasonal
  adjustment; combine it with other tools for that.

## Documentation

| Learn | Go to |
|---|---|
| End-to-end examples | [Example notebook](examples/tempdisagg_examples.ipynb) · [quickstart.py](examples/quickstart.py) |
| Statistical methods and equations | [Methodology](docs/methodology.md) |
| Every statistic in a result | [Statistics and diagnostics](docs/statistics.md) |
| All settings, with the R equivalents | [Configuration](docs/configuration.md) |
| Under the hood | [Architecture](docs/architecture.md) · [Testing](docs/testing.md) |
| Upgrading from 0.2.x | [Migration guide](MIGRATION.md) |

## Development

```bash
pip install -e ".[dev]"
pytest -q                 # 374 tests, including the R parity cases
ruff check .
mypy tempdisagg           # the package ships py.typed
```

Regenerating the R references needs R with the `tempdisagg` package:
`Rscript tests/reference/generate_r_reference.R`.

## License

MIT. Methodology after Chow and Lin (1971), Fernández (1981), Litterman
(1983), Denton (1971), Dagum and Cholette (2006), Santos Silva and Cardoso
(2001), and Sax and Steiner (2013), *Temporal Disaggregation of Time Series*,
The R Journal 5(2).
