Skip to content

td-uaf-forecast

Forecast in the database with Holt-Winters or ARIMA, and register the forecast as a recomputable feature.


name: "Teradata UAF forecasting: Holt-Winters and ARIMA as governed features" description: "Generate Python and SQL to forecast time series in the database with Teradata UAF (Holt-Winters and ARIMA), try the models with the teradataml wrappers (TDSeries, HoltWintersForecaster, ArimaEstimate, ArimaValidate, ArimaForecast), and register the forecast as a recomputable tdfs4ds feature: Holt-Winters inline in a view, ARIMA as a 'uaf art view'. Invoke when the user wants a statistical baseline forecast computed in Vantage. SKIP for a per-series diagnostic such as autocorrelation or stationarity (use td-uaf-feature), for ARIMA fit metrics or residual tests (use td-uaf-art), and for an ML model trained with tdstone2 (use fs-tdstone2)." argument-hint: "[source-table][series-id-column] [time-column][value-column]" allowed-tools: "Read, Edit, Write, Bash, Glob, Grep"


Generate code to forecast time series with Teradata's UAF (Unbounded Array Framework) operators and register the forecast as a governed tdfs4ds feature.

User context: $ARGUMENTS

Step Skill Why
Before fs-setup Open the session and select the feature store and data domain.
Before fs-filter Build the FilterManager when registering per partition.
Sibling td-uaf-feature The same inline view for diagnostics.
Sibling td-uaf-art The uaf art view process type used for ARIMA here, in detail.
After td-plot Draw actual against forecast, and the residuals.
After fs-document Business description of the process.

Ask for any missing values before generating code: - Source table or view: one row per (series, time). - Series ID column(s). - Row axis: TIMECODE for a date or timestamp, SEQUENCE for a number. - Value column to forecast. - Method: Holt-Winters (one operator, a good first baseline) or ARIMA (when residual autocorrelation remains, or the series needs differencing or AR/MA terms). - Horizon, and the seasonal period for seasonal data (7 weekly, 12 monthly).

Step 1: try the models with the wrappers

The wrappers are for exploring: they write temporary tables collected at the end of the session. Don't register their results (see Rules).

import teradataml as tdml

series = tdml.TDSeries(
    data=tdml.DataFrame.from_query("SELECT <SERIES_ID>, <SEQ_COLUMN>, <VALUE_COLUMN> FROM <DATABASE>.<SOURCE>"),
    id='<SERIES_ID>',
    row_index='<SEQ_COLUMN>',
    row_index_style='SEQUENCE',      # 'TIMECODE' for a date or timestamp column
    payload_field='<VALUE_COLUMN>',
    payload_content='REAL',
)

# Holt-Winters: one call
hw = tdml.HoltWintersForecaster(
    data=series,
    forecast_periods=28,
    model='ADDITIVE',                # 'MULTIPLICATIVE' when seasonal swings scale with the level
    seasonal_periods=7,              # omit for a non-seasonal series
    fit_percentage=80,
    prediction_intervals='BOTH',     # 'NONE', '80', '95' or 'BOTH'
    fit_metrics=True, selection_metrics=True, residuals=True,
)
hw.result         # <SERIES_ID>, ROW_I, OBSERVED_VALUE, FORECAST_VALUE, LO_80, HI_80, LO_95, HI_95
hw.fitmetadata    # R_SQUARE, ... per series (needs fit_metrics=True)
hw.selmetrics     # needs selection_metrics=True
hw.fitresiduals   # needs residuals=True

# ARIMA: estimate, validate, forecast. Each step takes the previous one's result in TDAnalyticResult.
estimate = tdml.ArimaEstimate(
    data1=series,
    nonseasonal_model_order=[1, 0, 0],
    seasonal_model_order=[1, 0, 0], seasonal_period=7,   # omit both for a plain ARIMA
    constant=False, algorithm='MLE',
    fit_percentage=80, fit_metrics=True, residuals=True,
)
validate = tdml.ArimaValidate(data=tdml.TDAnalyticResult(data=estimate.result), fit_metrics=True, residuals=True)
forecast = tdml.ArimaForecast(data=tdml.TDAnalyticResult(data=validate.result), forecast_periods=28)

forecast.result   # <SERIES_ID>, ROW_I, FORECAST_VALUE, LO_80, HI_80, LO_95, HI_95
validate.result   # AIC, SBIC, HQIC, ... per series: sort by AIC to rank the fits

show_query() on a wrapper gives its SQL, which is what Steps 3 and 4 write by hand.

Step 2: the series input view

The operators read this view. With a FilterManager, its scalar subquery goes here, so each partition computes its own forecast, and the filter column is part of the entity.

tdml.execute_sql(f"""
REPLACE VIEW <DATABASE>.<SERIES_VIEW> AS
LOCKING ROW FOR ACCESS
SELECT <SERIES_ID>, <STORE>,
       ROW_NUMBER() OVER (PARTITION BY <SERIES_ID>, <STORE> ORDER BY <DATE_COLUMN>) AS seq_no,
       <VALUE_COLUMN> AS val
FROM <SOURCE_DATABASE>.<SOURCE_TABLE>
WHERE <STORE> = (SELECT <STORE> FROM {fm.sql_view})
""")

The operator runs when the view is read, inside its own CTE, so nothing needs storing and run() recomputes it in any session.

tdml.execute_sql("""
REPLACE VIEW <DATABASE>.<VIEW_NAME> AS
LOCKING ROW FOR ACCESS
WITH hw AS (
    SELECT <SERIES_ID>, <STORE>, ROW_I AS horizon,
           CAST(FORECAST_VALUE AS FLOAT) AS forecast_value,
           CAST(LO_95 AS FLOAT) AS forecast_lo_95, CAST(HI_95 AS FLOAT) AS forecast_hi_95
    FROM ( EXECUTE FUNCTION TD_HOLT_WINTERS_FORECASTER(
             SERIES_SPEC(TABLE_NAME(<DATABASE>.<SERIES_VIEW>), ROW_AXIS(SEQUENCE(seq_no)),
                         SERIES_ID(<SERIES_ID>, <STORE>), PAYLOAD(FIELDS(val), CONTENT(REAL))),
             FUNC_PARAMS(FORECAST_PERIODS(28), MODEL(ADDITIVE), SEASONAL_PERIODS(7),
                         PREDICTION_INTERVALS(BOTH))) ) f
)
SELECT * FROM hw
""")

process_id = tdfs4ds.upload_features(
    tdml.DataFrame(tdml.in_schema('<DATABASE>', '<VIEW_NAME>')),
    entity_id=['<SERIES_ID>', '<STORE>', 'horizon'],
    feature_names=['forecast_value', 'forecast_lo_95', 'forecast_hi_95'],
    filtermanager=fm,                # run() goes through the partitions
    return_process_id=True,
)

The CTE is required: see td-uaf-feature for why a top-level derived table is not enough.

Step 4: ARIMA, as a uaf art view

ARIMA needs a real intermediate ART, which a single view cannot hold. Store the statements in art_sql. Their order matters: the forecast reads the estimate. Estimate on all the points (FIT_PERCENTAGE(100)) to forecast directly.

art_sql = [
    """EXECUTE FUNCTION INTO VOLATILE ART(arima_est)
       TD_ARIMAESTIMATE(SERIES_SPEC(TABLE_NAME(<DATABASE>.<SERIES_VIEW>), ROW_AXIS(SEQUENCE(seq_no)),
           SERIES_ID(<SERIES_ID>, <STORE>), PAYLOAD(FIELDS(val), CONTENT(REAL))),
         FUNC_PARAMS(NONSEASONAL(MODEL_ORDER(1,0,0)), CONSTANT(0), ALGORITHM(MLE), FIT_PERCENTAGE(100)))""",
    """EXECUTE FUNCTION INTO VOLATILE ART(arima_fc)
       TD_ARIMAFORECAST(ART_SPEC(TABLE_NAME(arima_est)), FUNC_PARAMS(FORECAST_PERIODS(28)))""",
]

# The view can only be created while the ART exists: materialise it once, for the first partition.
fm.update(filter_id=1)
for statement in art_sql:
    tdml.execute_sql(statement)

tdml.execute_sql("""
REPLACE VIEW <DATABASE>.<VIEW_NAME> AS
LOCKING ROW FOR ACCESS
SELECT <SERIES_ID>, <STORE>, ROW_I AS horizon, CAST(FORECAST_VALUE AS FLOAT) AS arima_forecast
FROM arima_fc
""")

process_id = tdfs4ds.upload_features(
    tdml.DataFrame(tdml.in_schema('<DATABASE>', '<VIEW_NAME>')),
    entity_id=['<SERIES_ID>', '<STORE>', 'horizon'],
    feature_names=['arima_forecast'],
    art_sql=art_sql,
    art_layers=['ARTPRIMARY'],
    filtermanager=fm,
    return_process_id=True,
)

The for above only prepares the view; it is not a loop around run(). See td-uaf-art.

Rules

  • Do not register a wrapper's result. crystallize_view(hw.result, ...) stops with Error 3854 ("is not a view"), because wrappers write tables, and those tables disappear with the session. Write the operator in the view (Step 3) or in art_sql (Step 4).
  • ARIMA wrappers chain through TDAnalyticResult: ArimaValidate and ArimaForecast take TDAnalyticResult(data=<previous>.result), not the raw .result and not the previous object.
  • row_index_style must match the column: 'TIMECODE' for a date or timestamp, 'SEQUENCE' for a number.
  • Horizon is part of the entity: one row per (series, horizon), so ROW_I has to be in entity_id. Rename it in the view.
  • Fit options fill their attribute only when asked: fit_metrics, residuals and selection_metrics for .fitmetadata, .fitresiduals and .selmetrics.
  • Back-transform with the same base: after log(x + c), use exp(y) - c, never 10**y - c, on FORECAST_VALUE and on every bound.
  • The AI steps follow your configuration. document and optimize_query default to None. See fs-upload.
  • One upload_features with filtermanager=fm. Never a loop over fm.update and run.