Skip to main content

dfm-python

PyPI version Python versions CI License: MIT Downloads

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

Star history chart for minkeymouse/dfm-python

Metadata

Release files for dfm-python 0.8.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for dfm-python 0.8.2
File Size Uploaded Provenance Actions
dfm_python-0.8.2.tar.gz 3.3 MB With provenance Details for dfm_python-0.8.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for dfm-python 0.8.2
File Interpreter ABI Platform Actions
dfm_python-0.8.2-py3-none-any.whl Python 3 none any Details for dfm_python-0.8.2-py3-none-any.whl

Total release size: 3.6 MB

Release files / dfm_python-0.8.2.tar.gz

Download URL dfm_python-0.8.2.tar.gz
Size 3.3 MB
Tags Source
SHA-256 checksum
How to use checksums
02efe63870fbc04637db664ea9f582a338f5f81885c7e6910b51004c772abc24
BLAKE2b-256 checksum
How to use checksums
2aff5f24b017e1c0c5f05cbe77026f821b50277cf433e69db9170919d1c67d10
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 log

Release files / dfm_python-0.8.2-py3-none-any.whl

Download URL dfm_python-0.8.2-py3-none-any.whl
Size 311.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
950bb4ec054cf5bb80c80253077ac2cd03bf86594c29aac0f66616a1a50721eb
BLAKE2b-256 checksum
How to use checksums
d80f8841b725154b5aec4dcd4b4d05c859bef8bc8939dfc6f34905c29b6d7360
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 log

Security for dfm-python 0.8.2

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.

Select from 2 files

Attestation for dfm_python-0.8.2.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 log

A 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.

Release history Release notifications | RSS feed

This release

0.8.2 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page