dfm-python
Dynamic factor models in Python, linear and deep, on one scikit-learn-style
estimator API: hyperparameters in the constructor, fit(data) on a
PanelData, DataFrame forecasts, fitted state in result_, pickle-free
save directories.
| Model | What it is | Backend |
|---|---|---|
DFM |
linear, mixed-frequency dynamic factor model, estimated by EM with Kalman filtering and smoothing | numpy |
DDFM |
deep dynamic factor model: a nonlinear encoder trained with MCMC denoising and a linear state space on its factors | PyTorch |
iVDFM |
identifiable variational dynamic factor model, trained on the ELBO with a context-conditioned innovation prior | PyTorch |
AFM |
Attention Factor Model of Epstein, Wang, Choi and Pelger (2025): a cross-sectional conditional factor model whose residuals are traded portfolios, with PCA and Avellaneda-Lee benchmarks | PyTorch |
Installation
pip install dfm-python # or: uv add dfm-python
Python 3.10 to 3.13. The dependencies are numpy, pandas, scipy, scikit-learn,
einops and torch 2.10 or newer; torch is required for the numpy DFM too. For
a CPU-only or a specific CUDA torch build, install torch from the
PyTorch index first.
| Extra | Adds | Needed for |
|---|---|---|
yaml |
omegaconf | YAML configs (load_yaml, XConfig.from_yaml), tutorial/ |
tune |
optuna | iVDFM hyperparameter search (dfm_python.tuning) |
metrics |
sktime | calculate_rmse, calculate_mae |
polars |
polars, pyarrow | passing polars DataFrames to PanelData |
all |
all of the above | |
dev |
pytest, ruff, build, twine, omegaconf, pyyaml, optuna, statsmodels | tests and packaging |
pip install "dfm-python[yaml,tune]"
Code that needs a missing extra raises ImportError naming it.
Quick start
A one-factor DFM on three monthly indicators and quarterly GDP growth, on a monthly clock. It runs in a few seconds.
import numpy as np
import pandas as pd
from dfm_python import DFM, PanelData
rng = np.random.default_rng(0)
f = np.zeros(120)
for t in range(1, 120):
f[t] = 0.8 * f[t - 1] + rng.standard_normal()
idx = pd.date_range("2015-01-31", periods=120, freq="ME", name="date")
df = pd.DataFrame({"ip": f, "sales": 0.7 * f, "jobs": -0.5 * f}, index=idx)
df += 0.5 * rng.standard_normal(df.shape)
df["gdp"] = np.convolve(f, [1, 2, 3, 2, 1])[:120] / 9 # tent-weighted monthly factor
df.loc[df.index.month % 3 != 0, "gdp"] = np.nan # quarterly: NaN between releases
data = PanelData(y=df, freq={"gdp": "q"}) # unlisted series run at the clock
model = DFM(n_factors=1, clock="m", tent_weights={"q:m": [1, 2, 3, 2, 1]},
scaler="standard", max_iter=100).fit(data)
model.result_.loglik, model.n_iter_, model.converged_
fc = model.predict(6) # DataFrame 6 x 4, every series at every month, data units
zf = model.predict_factors(6) # DataFrame 6 x state dimension
model.save("runs/quickstart", overwrite=True) # dfm_python.load() reads it back
Other models
DDFM: targets s0..s2, encoder covariates oil and fx in exog.
import numpy as np
import pandas as pd
from dfm_python import DDFM, PanelData
idx = pd.date_range("2010-01-31", periods=120, freq="ME", name="date")
df = pd.DataFrame(np.random.default_rng(0).standard_normal((120, 5)), index=idx,
columns=["s0", "s1", "s2", "oil", "fx"])
data = PanelData(y=df[["s0", "s1", "s2"]], exog=df[["oil", "fx"]])
model = DDFM(n_factors=2, max_iter=20, scaler="standard", random_state=3).fit(data)
fc = model.predict(6) # DataFrame 6 x 3, data units
iVDFM: the exog column is the context of the innovation prior, so a
forecast takes its future values.
import numpy as np
import pandas as pd
from dfm_python import iVDFM, PanelData
idx = pd.date_range("2010-01-31", periods=150, freq="ME", name="date")
df = pd.DataFrame(np.random.default_rng(0).standard_normal((150, 4)), index=idx,
columns=["s0", "s1", "s2", "policy_rate"])
data = PanelData(y=df[["s0", "s1", "s2"]].iloc[:144], exog=df[["policy_rate"]].iloc[:144])
model = iVDFM(n_factors=2, window=48, max_epochs=5, scaler="standard", random_state=3).fit(data)
fc = model.predict(6, futr_exog=df[["policy_rate"]].iloc[144:150]) # DataFrame 6 x 3
AFM: asset returns (T, N) and characteristics (T, N, M); it allocates
instead of forecasting.
import numpy as np
import pandas as pd
from dfm_python import AFM, PanelData
rng = np.random.default_rng(0)
T, N, M = 120, 20, 8
data = PanelData.from_arrays(y=0.01 * rng.standard_normal((T, N)),
series_exog=rng.standard_normal((T, N, M)),
index=pd.bdate_range("2020-01-01", periods=T, name="date"))
model = AFM(n_factors=3, hist_len=20, max_epochs=5, random_state=0).fit(data)
weights = model.allocate() # DataFrame (T - hist_len) x N
model.result_.sharpe, model.book_returns_
Documentation
| Page | Contents |
|---|---|
| User guide | PanelData, the estimator contract, update and predict(data=), saving and loading, YAML configs, reproducibility, logging, errors |
| Models | DFM, DDFM, iVDFM and AFM: full examples, hyperparameters, notes, method references |
| Migrating from 0.7 | the 0.7 to 0.8 API table |
| Development | setup, tests, lint, repository layout, golden tests, releases |
| CHANGELOG | release notes |
| SECURITY.md | trust model of run directories and YAML files; how to report a vulnerability |
The scripts in
tutorial/
fit DFM, DDFM and iVDFM to the three datasets in data/ from the YAML files
in config/ (repository only, not in the installed package).
Citing
Software citation metadata is in CITATION.cff; BibTeX entries and the method reference of each model are in docs/citing.md. Papers by the author that use dfm-python:
- Chang, M. and Kim, J.-Y. (2026). Conditionally Identifiable Latent Representation for Multivariate Time Series with Structural Dynamics. arXiv:2603.22886. Introduces iVDFM.
- Chang, M. (2026). Amortized Neural Filtering for Calibrated Posteriors in Statistical Arbitrage. 7th ACM International Conference on AI in Finance (ICAIF '26). arXiv:2610.25802. Uses AFM as a baseline; code in minkeymouse/nfe.
License
MIT. See LICENSE.
Star history
Metadata
Release files for dfm-python 0.8.3
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| dfm_python-0.8.3.tar.gz | 3.3 MB | With provenance | Details for dfm_python-0.8.3.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| dfm_python-0.8.3-py3-none-any.whl | Python 3 | none | any | Details for dfm_python-0.8.3-py3-none-any.whl |
Total release size: 3.7 MB
Release files / dfm_python-0.8.3.tar.gz
| Download URL | dfm_python-0.8.3.tar.gz |
|---|---|
| Size | 3.3 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
aae01c40bb1190fd5ecbd347d4ae1de90d2f202fabfbba513d911b7817468489
|
|
BLAKE2b-256 checksum How to use checksums |
73ade1f573f8cb9c59b0a4e70e6b31db7c461abe126dedc4f70cea145a853a7e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 23, 2026.
Transparency logRelease files / dfm_python-0.8.3-py3-none-any.whl
| Download URL | dfm_python-0.8.3-py3-none-any.whl |
|---|---|
| Size | 312.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
3d91e7f15446a376767001965496cd3cf505a67891447edd2879ce43c9a6284f
|
|
BLAKE2b-256 checksum How to use checksums |
753292fe9f412c0f4d930ce350d4a3696243f664ebc36f0a7a8e52e0ab94734b
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 23, 2026.
Transparency logSecurity for dfm-python 0.8.3
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for dfm_python-0.8.3.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 23, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.