> ## Documentation Index
> Fetch the complete documentation index at: https://nixtla.io/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# SDK Reference

***

[source](https://github.com/Nixtla/nixtla/blob/main/nixtla/nixtla_client.py#LNone)

## NixtlaClient

> ```text theme={null}
>  NixtlaClient (api_key:Optional[str]=None, base_url:Optional[str]=None,
>                timeout:Optional[int]=60, max_retries:int=6,
>                retry_interval:int=10, max_wait_time:int=360)
> ```

*Client to interact with the Nixtla API.*

| | **Type** | **Default** | **Details** |
| - | - | - | - |
| api\_key | Optional | None | The authorization api\_key interacts with the Nixtla API. If not provided, will use the NIXTLA\_API\_KEY environment variable. |
| base\_url | Optional | None | Custom base\_url. If not provided, will use the NIXTLA\_BASE\_URL environment variable. |
| timeout | Optional | 60 | Request timeout in seconds. Set this to `None` to disable it. |
| max\_retries | int | 6 | The maximum number of attempts to make when calling the API before giving up. It defines how many times the client will retry the API call if it fails. Default value is 6, indicating the client will attempt the API call up to 6 times in total. Job submissions retry only connection failures and HTTP 429. Read timeouts and gateway errors are not retried because the server may already have accepted the job. |
| retry\_interval | int | 10 | The interval in seconds between consecutive retry attempts. This is the waiting period before the client tries to call the API again after a failed attempt. Default value is 10 seconds, meaning the client waits for 10 seconds between retries. |
| max\_wait\_time | int | 360 | The maximum total time in seconds that the client will spend on all retry attempts before giving up. This sets an upper limit on the cumulative waiting time for all retry attempts. If this time is exceeded, the client will stop retrying and raise an exception. Default value is 360 seconds, meaning the client will cease retrying if the total time spent on retries exceeds 360 seconds. The client throws a ReadTimeout error after 60 seconds of inactivity. If you want to catch these errors, use max\_wait\_time >> 60. |

How long the client waits for a server-side asynchronous job is set per call,
not on the client: pass `poll_interval` and `poll_timeout` to `simulate()`,
`explain()`, or `Job.wait()`. By default polling is adaptive -- the first status
check comes after half a second and the interval doubles up to one check every
15 seconds -- under a one-hour ceiling. An explicit `poll_interval` is a fixed
cadence instead, and `poll_timeout=None` waits until the server reports a
terminal status.

The `client.jobs` methods below submit the same work without waiting for it,
returning a `Job` handle.

Async partitioned requests run at most five jobs concurrently. A partition
failure cancels sibling jobs and stops queued submissions. Synchronous
partitioned requests also stop queued work after a failure.
Submission retry sleeps, including `Retry-After`, are limited to the remaining
`max_wait_time` budget; no further attempt starts once it expires. An in-flight
request remains governed by the HTTP `timeout`.

***

[source](https://github.com/Nixtla/nixtla/blob/main/nixtla/nixtla_client.py#LNone)

## NixtlaClient.validate\_api\_key

> ```text theme={null}
>  NixtlaClient.validate_api_key (log:bool=True)
> ```

*Check API key status.*

| | **Type** | **Default** | **Details** |
| - | - | - | - |
| log | bool | True | Show the endpoint’s response. |
| **Returns** | **bool** | | **Whether API key is valid.** |

***

[source](https://github.com/Nixtla/nixtla/blob/main/nixtla/nixtla_client.py#LNone)

## NixtlaClient.forecast

> ```text theme={null}
> NixtlaClient.forecast (
>     df, h, freq=None, id_col="unique_id", time_col="ds",
>     target_col="y", X_df=None, level=None, quantiles=None,
>     finetune_steps=0, finetune_depth=1, finetune_loss="default",
>     finetuned_model_id=None, clean_ex_first=True,
>     hist_exog_list=None, categorical_exog_list=None,
>     validate_api_key=False, add_history=False, date_features=False,
>     date_features_to_one_hot=False, model="timegpt-2.1",
>     num_partitions=None, feature_contributions=False,
>     model_parameters=None, multivariate=False,
>     feature_contributions_type="shapley"
> )
> ```

*Forecast your time series using TimeGPT.*

| | **Type** | **Default** | **Details** |
| - | - | - | - |
| df | AnyDFType | | The DataFrame on which the function will operate. Expected to contain at least the following columns: - time\_col:  Column name in `df` that contains the time indices of the time series. This is typically a datetime  column with regular intervals, e.g., hourly, daily, monthly data points. - target\_col:  Column name in `df` that contains the target variable of the time series, i.e., the variable we  wish to predict or analyze. Additionally, you can pass multiple time series (stacked in the dataframe) considering an additional column: - id\_col:  Column name in `df` that identifies unique time series. Each unique value in this column  corresponds to a unique time series. |
| h | Annotated | | Forecast horizon. |
| freq | Union | None | Frequency of the timestamps. If `None`, it will be inferred automatically. See [pandas’ available frequencies](https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases). |
| id\_col | str | unique\_id | Column that identifies each series. |
| time\_col | str | ds | Column that identifies each timestep, its values can be timestamps or integers. |
| target\_col | str | y | Column that contains the target. |
| X\_df | Optional | None | DataFrame with \[`unique_id`, `ds`] columns and `df`’s future exogenous. |
| level | Optional | None | Confidence levels between 0 and 100 for prediction intervals. |
| quantiles | Optional | None | Quantiles to forecast, list between (0, 1). `level` and `quantiles` should not be used simultaneously. The output dataframe will have the quantile columns formatted as TimeGPT-q-(100 \* q) for each q. 100 \* q represents percentiles but we choose this notation to avoid having dots in column names. |
| finetune\_steps | Annotated | 0 | Number of steps used to finetune learning TimeGPT in the new data. |
| finetune\_depth | Literal | 1 | The depth of the finetuning. Uses a scale from 1 to 5, where 1 means little finetuning, and 5 means that the entire model is finetuned. |
| finetune\_loss | Literal | default | Loss function to use for finetuning. Options are: `default`, `mae`, `mse`, `rmse`, `mape`, and `smape`. |
| finetuned\_model\_id | Optional | None | ID of previously fine-tuned model to use. |
| clean\_ex\_first | bool | True | Clean exogenous signal before making forecasts using TimeGPT. |
| hist\_exog\_list | Optional | None | Column names of the historical exogenous features. |
| categorical\_exog\_list | Optional | None | Column names of categorical exogenous features. |
| validate\_api\_key | bool | False | If True, validates api\_key before sending requests. |
| add\_history | bool | False | Return fitted values of the model. |
| date\_features | Union | False | Features computed from the dates. Can be pandas date attributes or functions that will take the dates as input. If True automatically adds most used date features for the frequency of `df`. |
| date\_features\_to\_one\_hot | Union | False | Apply one-hot encoding to these date features. If `date_features=True`, then all date features are one-hot encoded by default. |
| model | str | timegpt-2.1 | Model to use. Available models depend on your account. |
| num\_partitions | Optional | None | Number of partitions to use. If None, the number of partitions will be equal to the available parallel resources in distributed environments. |
| feature\_contributions | bool | False | Compute feature contributions and store them in `NixtlaClient.feature_contributions`. |
| model\_parameters | Optional | None | Optional model-specific settings. |
| multivariate | bool | False | Enable multivariate predictions for models that support them. |
| feature\_contributions\_type | Literal | shapley | Explanation used for feature contributions. Options are `shapley`, `intervention`, `granger`, and `transfer_entropy`. |
| **Returns** | **AnyDFType** | | **DataFrame with TimeGPT forecasts for point predictions and probabilistic predictions (if level is not None).** |

***

[source](https://github.com/Nixtla/nixtla/blob/main/nixtla/nixtla_client.py#LNone)

## NixtlaClient.simulate

> ```text theme={null}
> NixtlaClient.simulate (
>     df, h, freq=None, id_col="unique_id", time_col="ds",
>     target_col="y", X_df=None, n_paths=100, quantiles=None,
>     seed=None, finetuned_model_id=None, clean_ex_first=True,
>     hist_exog_list=None, categorical_exog_list=None,
>     validate_api_key=False, date_features=False,
>     date_features_to_one_hot=False, model="timegpt-2.1",
>     multivariate=False, num_partitions=None,
>     job_timeout_seconds=None, poll_interval=None, poll_timeout=3600.0
> )
> ```

*Generate temporally correlated forecast sample paths.*

The request runs as an asynchronous job on the server: the client submits it,
then polls its status until it finishes, so the call blocks until the paths are
available. Use `poll_interval` and `poll_timeout` to control the waiting
behavior, or `NixtlaClient.jobs.simulate` to get a `Job` handle back
immediately. A job that fails on the server
raises `nixtla.JobError`. If the job outlives `poll_timeout`,
the client requests cancellation and raises `nixtla.JobTimeoutError`.
Server-side cancellation raises `nixtla.JobCancelledError`. Invalid inputs,
including missing or duplicate timestamps, raise `ValueError`. HTTP failures
raise `nixtla.ApiError`, preserving the server's error body.

| | **Type** | **Default** | **Details** |
| - | - | - | - |
| df | pandas or polars DataFrame | | Historical time-series data containing the time and target columns. It may also contain an ID column and exogenous features. |
| h | int | | Number of future timesteps in every path. Must be greater than zero. |
| freq | str, int, or pandas offset | None | Frequency of the timestamps. If `None`, it is inferred from `df` (pandas only); pass it explicitly for polars. |
| id\_col | str | unique\_id | Column that identifies each series. |
| time\_col | str | ds | Column that identifies each timestep. |
| target\_col | str | y | Column that contains the target. |
| X\_df | pandas or polars DataFrame | None | Future exogenous values with the ID and time columns. |
| n\_paths | int | 100 | Number of paths returned for each series. Must be between 1 and 10,000. |
| quantiles | list\[float] | None | Strictly increasing quantile grid inside `(0, 1)`. The list must contain between 2 and 200 values. |
| seed | int | None | Random seed between `-2**63` and `2**64 - 1`. Reusing a seed with identical inputs returns identical paths. |
| finetuned\_model\_id | str | None | ID of a previously fine-tuned model. |
| clean\_ex\_first | bool | True | Clean exogenous signals before inference. |
| hist\_exog\_list | list\[str] | None | Names of historical-only exogenous features. |
| categorical\_exog\_list | list\[str] | None | Names of categorical exogenous features. |
| validate\_api\_key | bool | False | Validate the API key before sending the request. |
| date\_features | bool or list | False | Date-derived exogenous features to add. |
| date\_features\_to\_one\_hot | bool or list\[str] | False | Date features to one-hot encode. |
| model | str | timegpt-2.1 | Model used to generate the forecasts. |
| multivariate | bool | False | Request coherent paths across series. The returned `coupled` column reports whether cross-series coupling was applied. |
| num\_partitions | int | None | Split the series across this many concurrent requests to keep large jobs under the request size limit. Cannot be combined with `multivariate=True`. Each partition receives a distinct seed derived from `seed`, so the call stays reproducible, but a partitioned call returns different paths than an unpartitioned one for the same `seed`. |
| job\_timeout\_seconds | int | None | Maximum time in seconds the server may spend on the job (on each partition when `num_partitions` is set). It may not exceed the limit of the deployment. Defaults to the deployment's limit. |
| poll\_interval | float | None | Seconds between two status checks of the job, held fixed. By default the client polls on an adaptive cadence instead: the first check comes after half a second and the interval doubles up to one check every 15 seconds, so a short job returns promptly and a long one still polls cheaply. |
| poll\_timeout | float | 3600.0 | Maximum seconds to wait for the job to reach a terminal state, measured from a successful submission and including queueing time on the server. Submission retries are excluded; each partition gets its own timeout. When it elapses the client requests cancellation and raises `JobTimeoutError`. Set to `None` to wait until the server reports a terminal status. |
| **Returns** | **pandas or polars DataFrame** | | **Long-form paths containing the ID and time columns, `sample_id`, `TimeGPT`, and `coupled`. The dataframe contains `n_series * n_paths * h` rows. The ID column is omitted if `df` did not contain one.** |

See [Forecast Simulation](https://nixtla.io/docs/forecasting/probabilistic/simulation.md) for complete
examples, output interpretation, limits, and scenario analysis.

***

[source](https://github.com/Nixtla/nixtla/blob/main/nixtla/nixtla_client.py#LNone)

## NixtlaClient.explain

> ```text theme={null}
> NixtlaClient.explain (
>     df, method="granger", features=None, freq=None,
>     id_col="unique_id", time_col="ds", target_col="y",
>     categorical_exog_list=None, validate_api_key=False,
>     job_timeout_seconds=None, poll_interval=None, poll_timeout=3600.0
> )
> ```

*Compute model-independent historical feature importance weights.*

The request runs as an asynchronous job on the server: the client submits it,
then polls its status until it finishes, so the call blocks until the weights
are available. Use `poll_interval` and `poll_timeout` to control the waiting
behavior, or `NixtlaClient.jobs.explain` to get a `Job` handle back
immediately. A job that fails on the server
raises `nixtla.JobError`. If the job outlives `poll_timeout`,
the client requests cancellation and raises `nixtla.JobTimeoutError`.
Server-side cancellation raises `nixtla.JobCancelledError`. Invalid inputs,
including missing or duplicate timestamps, raise `ValueError`. HTTP failures
raise `nixtla.ApiError`, preserving the server's error body.

| | **Type** | **Default** | **Details** |
| - | - | - | - |
| df | pandas or polars DataFrame | | Historical time-series data containing the target and candidate feature columns. |
| method | str | granger | Analysis to run. Use `"granger"` for linear lagged relationships or `"transfer_entropy"` for potentially nonlinear relationships. |
| features | list\[str] | None | Features to analyze. By default, every column other than the ID, time, and target columns is used. Non-numeric features must be listed in `categorical_exog_list`. |
| freq | str, int or pandas offset | None | Frequency of the timestamps, used to verify that every series is complete and regularly spaced. Both methods are lag-based, so gaps or duplicate timestamps distort the weights. Inferred from `df` when None; required for polars. |
| id\_col | str | unique\_id | Column that identifies each series. |
| time\_col | str | ds | Column that identifies each timestep. |
| target\_col | str | y | Column that contains the target. |
| categorical\_exog\_list | list\[str] | None | Feature names to treat as categorical. Every name must also appear in `features`. |
| validate\_api\_key | bool | False | Validate the API key before sending the request. |
| job\_timeout\_seconds | int | None | Maximum time in seconds the server may spend on the job. It may not exceed the limit of the deployment. Defaults to the deployment's limit. |
| poll\_interval | float | None | Seconds between two status checks of the job, held fixed. By default the client polls on an adaptive cadence instead: the first check comes after half a second and the interval doubles up to one check every 15 seconds, so a short job returns promptly and a long one still polls cheaply. |
| poll\_timeout | float | 3600.0 | Maximum seconds to wait for the job to reach a terminal state, measured from a successful submission and including queueing time on the server. When it elapses the client requests cancellation and raises `JobTimeoutError`. Set to `None` to wait until the server reports a terminal status. |
| **Returns** | **pandas or polars DataFrame** | | **One row per feature with `feature`, `weight`, and `method` columns. Weights are nonnegative and sum to one.** |

The weights describe predictive relationships in historical data; they do not
establish causality. See
[Find predictive signals in history](https://nixtla.io/docs/forecasting/exogenous-variables/causal-explanations.md)
for interpretation guidance and examples.

***

[source](https://github.com/Nixtla/nixtla/blob/main/nixtla/nixtla_client.py#LNone)

## NixtlaClient.cross\_validation

> ```text theme={null}
>  NixtlaClient.cross_validation (df:~AnyDFType,
>                                 h:typing.Annotated[int,Gt(gt=0)], freq:Uni
>                                 on[str,int,pandas._libs.tslibs.offsets.Bas
>                                 eOffset,NoneType]=None,
>                                 id_col:str='unique_id', time_col:str='ds',
>                                 target_col:str='y', level:Optional[list[Un
>                                 ion[int,float]]]=None,
>                                 quantiles:Optional[list[float]]=None,
>                                 validate_api_key:bool=False, n_windows:typ
>                                 ing.Annotated[int,Gt(gt=0)]=1, step_size:O
>                                 ptional[Annotated[int,Gt(gt=0)]]=None, fin
>                                 etune_steps:typing.Annotated[int,Ge(ge=0)]
>                                 =0, finetune_depth:Literal[1,2,3,4,5]=1, f
>                                 inetune_loss:Literal['default','mae','mse'
>                                 ,'rmse','mape','smape']='default',
>                                 finetuned_model_id:Optional[str]=None,
>                                 refit:bool=True, clean_ex_first:bool=True,
>                                 hist_exog_list:Optional[list[str]]=None,
>                                 date_features:Union[bool,list[str]]=False,
>                                 date_features_to_one_hot:Union[bool,list[s
>                                 tr]]=False, model:Literal['azureai','timeg
>                                 pt-1','timegpt-1-long-
>                                 horizon']='timegpt-1', num_partitions:Opti
>                                 onal[Annotated[int,Gt(gt=0)]]=None)
> ```

*Perform cross validation in your time series using TimeGPT.*

| | **Type** | **Default** | **Details** |
| - | - | - | - |
| df | AnyDFType | | The DataFrame on which the function will operate. Expected to contain at least the following columns: - time\_col:  Column name in `df` that contains the time indices of the time series. This is typically a datetime  column with regular intervals, e.g., hourly, daily, monthly data points. - target\_col:  Column name in `df` that contains the target variable of the time series, i.e., the variable we  wish to predict or analyze. Additionally, you can pass multiple time series (stacked in the dataframe) considering an additional column: - id\_col:  Column name in `df` that identifies unique time series. Each unique value in this column  corresponds to a unique time series. |
| h | Annotated | | Forecast horizon. |
| freq | Union | None | Frequency of the timestamps. If `None`, it will be inferred automatically. See [pandas’ available frequencies](https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases). |
| id\_col | str | unique\_id | Column that identifies each series. |
| time\_col | str | ds | Column that identifies each timestep, its values can be timestamps or integers. |
| target\_col | str | y | Column that contains the target. |
| level | Optional | None | Confidence level between 0 and 100 for prediction intervals. |
| quantiles | Optional | None | Quantiles to forecast, list between (0, 1). `level` and `quantiles` should not be used simultaneously. The output dataframe will have the quantile columns formatted as TimeGPT-q-(100 \* q) for each q. 100 \* q represents percentiles but we choose this notation to avoid having dots in column names. |
| validate\_api\_key | bool | False | If True, validates api\_key before sending requests. |
| n\_windows | Annotated | 1 | Number of windows to evaluate. |
| step\_size | Optional | None | Step size between each cross validation window. If None it will be equal to `h`. |
| finetune\_steps | Annotated | 0 | Number of steps used to finetune TimeGPT in the new data. |
| finetune\_depth | Literal | 1 | The depth of the finetuning. Uses a scale from 1 to 5, where 1 means little finetuning, and 5 means that the entire model is finetuned. |
| finetune\_loss | Literal | default | Loss function to use for finetuning. Options are: `default`, `mae`, `mse`, `rmse`, `mape`, and `smape`. |
| finetuned\_model\_id | Optional | None | ID of previously fine-tuned model to use. |
| refit | bool | True | Fine-tune the model in each window. If `False`, only fine-tunes on the first window. Only used if `finetune_steps` > 0. |
| clean\_ex\_first | bool | True | Clean exogenous signal before making forecasts using TimeGPT. |
| hist\_exog\_list | Optional | None | Column names of the historical exogenous features. |
| date\_features | Union | False | Features computed from the dates. Can be pandas date attributes or functions that will take the dates as input. If True automatically adds most used date features for the frequency of `df`. |
| date\_features\_to\_one\_hot | Union | False | Apply one-hot encoding to these date features. If `date_features=True`, then all date features are one-hot encoded by default. |
| model | Literal | timegpt-1 | Model to use as a string. Options are: `timegpt-1`, and `timegpt-1-long-horizon`. We recommend using `timegpt-1-long-horizon` for forecasting if you want to predict more than one seasonal period given the frequency of your data. |
| num\_partitions | Optional | None | Number of partitions to use. If None, the number of partitions will be equal to the available parallel resources in distributed environments. |
| **Returns** | **AnyDFType** | | **DataFrame with cross validation forecasts.** |

***

[source](https://github.com/Nixtla/nixtla/blob/main/nixtla/nixtla_client.py#LNone)

## NixtlaClient.detect\_anomalies

> ```text theme={null}
>  NixtlaClient.detect_anomalies (df:~AnyDFType,
>                                 freq:Union[str,int,pandas._libs.tslibs.off
>                                 sets.BaseOffset,NoneType]=None,
>                                 id_col:str='unique_id', time_col:str='ds',
>                                 target_col:str='y',
>                                 level:Union[int,float]=99,
>                                 finetuned_model_id:Optional[str]=None,
>                                 clean_ex_first:bool=True,
>                                 validate_api_key:bool=False,
>                                 date_features:Union[bool,list[str]]=False,
>                                 date_features_to_one_hot:Union[bool,list[s
>                                 tr]]=False, model:Literal['azureai','timeg
>                                 pt-1','timegpt-1-long-
>                                 horizon']='timegpt-1', num_partitions:Opti
>                                 onal[Annotated[int,Gt(gt=0)]]=None)
> ```

*Detect anomalies in your time series using TimeGPT.*

| | **Type** | **Default** | **Details** |
| - | - | - | - |
| df | AnyDFType | | The DataFrame on which the function will operate. Expected to contain at least the following columns: - time\_col:  Column name in `df` that contains the time indices of the time series. This is typically a datetime  column with regular intervals, e.g., hourly, daily, monthly data points. - target\_col:  Column name in `df` that contains the target variable of the time series, i.e., the variable we  wish to predict or analyze. Additionally, you can pass multiple time series (stacked in the dataframe) considering an additional column: - id\_col:  Column name in `df` that identifies unique time series. Each unique value in this column  corresponds to a unique time series. |
| freq | Union | None | Frequency of the timestamps. If `None`, it will be inferred automatically. See [pandas’ available frequencies](https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases). |
| id\_col | str | unique\_id | Column that identifies each series. |
| time\_col | str | ds | Column that identifies each timestep, its values can be timestamps or integers. |
| target\_col | str | y | Column that contains the target. |
| level | Union | 99 | Confidence level between 0 and 100 for detecting the anomalies. |
| finetuned\_model\_id | Optional | None | ID of previously fine-tuned model to use. |
| clean\_ex\_first | bool | True | Clean exogenous signal before making forecasts using TimeGPT. |
| validate\_api\_key | bool | False | If True, validates api\_key before sending requests. |
| date\_features | Union | False | Features computed from the dates. Can be pandas date attributes or functions that will take the dates as input. If True automatically adds most used date features for the frequency of `df`. |
| date\_features\_to\_one\_hot | Union | False | Apply one-hot encoding to these date features. If `date_features=True`, then all date features are one-hot encoded by default. |
| model | Literal | timegpt-1 | Model to use as a string. Options are: `timegpt-1`, and `timegpt-1-long-horizon`. We recommend using `timegpt-1-long-horizon` for forecasting if you want to predict more than one seasonal period given the frequency of your data. |
| num\_partitions | Optional | None | Number of partitions to use. If None, the number of partitions will be equal to the available parallel resources in distributed environments. |
| **Returns** | **AnyDFType** | | **DataFrame with anomalies flagged by TimeGPT.** |

***

[source](https://github.com/Nixtla/nixtla/blob/main/nixtla/nixtla_client.py#LNone)

## NixtlaClient.usage

> ```text theme={null}
>  NixtlaClient.usage ()
> ```

*Query consumed requests and limits*

***

[source](https://github.com/Nixtla/nixtla/blob/main/nixtla/nixtla_client.py#LNone)

## NixtlaClient.list\_models

> ```text theme={null}
>  NixtlaClient.list_models ()
> ```

*List the models available to your API key.*

| | **Type** | **Details** |
| - | - | - |
| **Returns** | **list** | **Model names, sorted. Each can be passed as the `model` argument of `forecast`, `cross_validation`, `detect_anomalies` and the other forecasting methods; a model absent from this list is one those methods would reject.** |

***

[source](https://github.com/Nixtla/nixtla/blob/main/nixtla/nixtla_client.py#LNone)

## NixtlaClient.finetune

> ```text theme={null}
>  NixtlaClient.finetune
>                         (df:Union[pandas.core.frame.DataFrame,polars.dataf
>                         rame.frame.DataFrame], freq:Union[str,int,pandas._
>                         libs.tslibs.offsets.BaseOffset,NoneType]=None,
>                         id_col:str='unique_id', time_col:str='ds',
>                         target_col:str='y',
>                         finetune_steps:typing.Annotated[int,Ge(ge=0)]=10,
>                         finetune_depth:Literal[1,2,3,4,5]=1, finetune_loss
>                         :Literal['default','mae','mse','rmse','mape','smap
>                         e']='default', output_model_id:Optional[str]=None,
>                         finetuned_model_id:Optional[str]=None, model:Liter
>                         al['azureai','timegpt-1','timegpt-1-long-
>                         horizon']='timegpt-1')
> ```

*Fine-tune TimeGPT to your series.*

| | **Type** | **Default** | **Details** |
| - | - | - | - |
| df | Union | | The DataFrame on which the function will operate. Expected to contain at least the following columns: - time\_col:  Column name in `df` that contains the time indices of the time series. This is typically a datetime  column with regular intervals, e.g., hourly, daily, monthly data points. - target\_col:  Column name in `df` that contains the target variable of the time series, i.e., the variable we  wish to predict or analyze. Additionally, you can pass multiple time series (stacked in the dataframe) considering an additional column: - id\_col:  Column name in `df` that identifies unique time series. Each unique value in this column  corresponds to a unique time series. |
| freq | Union | None | Frequency of the timestamps. If `None`, it will be inferred automatically. See [pandas’ available frequencies](https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases). |
| id\_col | str | unique\_id | Column that identifies each series. |
| time\_col | str | ds | Column that identifies each timestep, its values can be timestamps or integers. |
| target\_col | str | y | Column that contains the target. |
| finetune\_steps | Annotated | 10 | Number of steps used to finetune learning TimeGPT in the new data. |
| finetune\_depth | Literal | 1 | The depth of the finetuning. Uses a scale from 1 to 5, where 1 means little finetuning, and 5 means that the entire model is finetuned. |
| finetune\_loss | Literal | default | Loss function to use for finetuning. Options are: `default`, `mae`, `mse`, `rmse`, `mape`, and `smape`. |
| output\_model\_id | Optional | None | ID to assign to the fine-tuned model. If `None`, an UUID is used. |
| finetuned\_model\_id | Optional | None | ID of previously fine-tuned model to use as base. |
| model | Literal | timegpt-1 | Model to use as a string. Options are: `timegpt-1`, and `timegpt-1-long-horizon`. We recommend using `timegpt-1-long-horizon` for forecasting if you want to predict more than one seasonal period given the frequency of your data. |
| **Returns** | **str** | | **ID of the fine-tuned model** |

***

[source](https://github.com/Nixtla/nixtla/blob/main/nixtla/nixtla_client.py#LNone)

## NixtlaClient.finetuned\_models

> ```text theme={null}
>  NixtlaClient.finetuned_models (as_df:bool=False)
> ```

*List fine-tuned models*

| | **Type** | **Default** | **Details** |
| - | - | - | - |
| as\_df | bool | False | Return the fine-tuned models as a pandas dataframe |
| **Returns** | **Union** | | **List of available fine-tuned models.** |

***

[source](https://github.com/Nixtla/nixtla/blob/main/nixtla/nixtla_client.py#LNone)

## NixtlaClient.finetuned\_model

> ```text theme={null}
>  NixtlaClient.finetuned_model (finetuned_model_id:str)
> ```

*Get fine-tuned model metadata*

| | **Type** | **Details** |
| - | - | - |
| finetuned\_model\_id | str | ID of the fine-tuned model to get metadata from. |
| **Returns** | **FinetunedModel** | **Fine-tuned model metadata.** |

***

[source](https://github.com/Nixtla/nixtla/blob/main/nixtla/nixtla_client.py#LNone)

## NixtlaClient.delete\_finetuned\_model

> ```text theme={null}
>  NixtlaClient.delete_finetuned_model (finetuned_model_id:str)
> ```

*Delete a previously fine-tuned model*

| | **Type** | **Details** |
| - | - | - |
| finetuned\_model\_id | str | ID of the fine-tuned model to be deleted. |
| **Returns** | **bool** | **Whether delete was successful.** |

***

[source](https://github.com/Nixtla/nixtla/blob/main/nixtla/nixtla_client.py#LNone)

## NixtlaClient.plot

> ```text theme={null}
>  NixtlaClient.plot (df:Union[pandas.core.frame.DataFrame,polars.dataframe.
>                     frame.DataFrame,NoneType]=None, forecasts_df:Union[pan
>                     das.core.frame.DataFrame,polars.dataframe.frame.DataFr
>                     ame,NoneType]=None, id_col:str='unique_id',
>                     time_col:str='ds', target_col:str='y', unique_ids:Unio
>                     n[list[str],NoneType,numpy.ndarray]=None,
>                     plot_random:bool=True, max_ids:int=8,
>                     models:Optional[list[str]]=None,
>                     level:Optional[list[Union[int,float]]]=None,
>                     max_insample_length:Optional[int]=None,
>                     plot_anomalies:bool=False,
>                     engine:Literal['matplotlib','plotly','plotly-
>                     resampler']='matplotlib',
>                     resampler_kwargs:Optional[dict]=None, ax:Union[Forward
>                     Ref('plt.Axes'),numpy.ndarray,ForwardRef('plotly.graph
>                     _objects.Figure'),NoneType]=None)
> ```

*Plot forecasts and insample values.*

| | **Type** | **Default** | **Details** |
| - | - | - | - |
| df | Union | None | The DataFrame on which the function will operate. Expected to contain at least the following columns: - time\_col:  Column name in `df` that contains the time indices of the time series. This is typically a datetime  column with regular intervals, e.g., hourly, daily, monthly data points. - target\_col:  Column name in `df` that contains the target variable of the time series, i.e., the variable we  wish to predict or analyze. Additionally, you can pass multiple time series (stacked in the dataframe) considering an additional column: - id\_col:  Column name in `df` that identifies unique time series. Each unique value in this column  corresponds to a unique time series. |
| forecasts\_df | Union | None | DataFrame with columns \[`unique_id`, `ds`] and models. |
| id\_col | str | unique\_id | Column that identifies each series. |
| time\_col | str | ds | Column that identifies each timestep, its values can be timestamps or integers. |
| target\_col | str | y | Column that contains the target. |
| unique\_ids | Union | None | Time Series to plot. If None, time series are selected randomly. |
| plot\_random | bool | True | Select time series to plot randomly. |
| max\_ids | int | 8 | Maximum number of ids to plot. |
| models | Optional | None | list of models to plot. |
| level | Optional | None | list of prediction intervals to plot if passed. |
| max\_insample\_length | Optional | None | Max number of train/insample observations to be plotted. |
| plot\_anomalies | bool | False | Plot anomalies for each prediction interval. |
| engine | Literal | matplotlib | Library used to plot. ‘matplotlib’, ‘plotly’ or ‘plotly-resampler’. |
| resampler\_kwargs | Optional | None | Kwargs to be passed to plotly-resampler constructor. For further customization (“show\_dash”) call the method, store the plotting object and add the extra arguments to its `show_dash` method. |
| ax | Union | None | Object where plots will be added. |

***

# Asynchronous jobs

Every long-running task can be started without waiting for it. The
`client.jobs` methods below send the same request their blocking counterparts
do and return a `Job` handle as soon as the server has accepted it, so
you can submit work, do something else, and collect the result later.

Each takes the same arguments as the method it mirrors, minus the ones that only
mean something to a call that blocks — there is no `num_partitions`, because a
partitioned call fans out across several jobs and has no single handle to give
back, and no `poll_interval` or `poll_timeout`, which belong to `Job.wait()`.
Use the blocking method when you want partitioning.

Submission is retried only for failures that are known to precede acceptance
(connection errors and HTTP 429); a read timeout or gateway error is not
retried, because the server may already have created the job.

***

[source](https://github.com/Nixtla/nixtla/blob/main/nixtla/nixtla_client.py#LNone)

## NixtlaClient.jobs.forecast

> ```text theme={null}
> NixtlaClient.jobs.forecast (
>     df, h, freq=None, id_col="unique_id", time_col="ds",
>     target_col="y", X_df=None, level=None, quantiles=None,
>     finetune_steps=0, finetune_depth=1, finetune_loss="default",
>     finetuned_model_id=None, clean_ex_first=True, hist_exog_list=None,
>     categorical_exog_list=None, validate_api_key=False,
>     date_features=False, date_features_to_one_hot=False,
>     model="timegpt-2.1", feature_contributions=False,
>     model_parameters=None, multivariate=False, job_timeout_seconds=None
> )
> ```

*Submit a forecasting job and return a handle to it without waiting.*

Arguments are those of `NixtlaClient.forecast`, except
that `add_history` and `num_partitions` are not supported.

| | **Type** | **Default** | **Details** |
| - | - | - | - |
| job\_timeout\_seconds | int | None | Maximum time in seconds the server may spend on the job. It may not exceed the limit of the deployment. Defaults to the deployment's limit. |
| **Returns** | **Job** | | **Handle to the submitted job. `job.wait()` returns the forecast as a pandas or polars DataFrame.** |

***

[source](https://github.com/Nixtla/nixtla/blob/main/nixtla/nixtla_client.py#LNone)

## NixtlaClient.jobs.cross\_validation

> ```text theme={null}
> NixtlaClient.jobs.cross_validation (
>     df, h, freq=None, id_col="unique_id", time_col="ds",
>     target_col="y", level=None, quantiles=None, validate_api_key=False,
>     n_windows=1, step_size=None, finetune_steps=0, finetune_depth=1,
>     finetune_loss="default", finetuned_model_id=None, refit=True,
>     clean_ex_first=True, hist_exog_list=None, date_features=False,
>     date_features_to_one_hot=False, model="timegpt-2.1",
>     model_parameters=None, multivariate=False,
>     categorical_exog_list=None, job_timeout_seconds=None
> )
> ```

*Submit a cross-validation job and return a handle to it without waiting.*

Arguments are those of
`NixtlaClient.cross_validation`, except that
`num_partitions` is not supported.

| | **Type** | **Default** | **Details** |
| - | - | - | - |
| job\_timeout\_seconds | int | None | Maximum time in seconds the server may spend on the job. It may not exceed the limit of the deployment. Defaults to the deployment's limit. |
| **Returns** | **Job** | | **Handle to the submitted job. `job.wait()` returns the cross-validation results as a pandas or polars DataFrame.** |

***

[source](https://github.com/Nixtla/nixtla/blob/main/nixtla/nixtla_client.py#LNone)

## NixtlaClient.jobs.detect\_anomalies

> ```text theme={null}
> NixtlaClient.jobs.detect_anomalies (
>     df, h, detection_size, threshold_method="univariate", freq=None,
>     id_col="unique_id", time_col="ds", target_col="y", level=99,
>     clean_ex_first=True, step_size=None, finetune_steps=0,
>     finetune_depth=1, finetune_loss="default", finetuned_model_id=None,
>     hist_exog_list=None, date_features=False,
>     date_features_to_one_hot=False, model="timegpt-2.1",
>     model_parameters=None, refit=False, multivariate=False,
>     job_timeout_seconds=None
> )
> ```

*Submit an online anomaly-detection job and return a handle to it without waiting.*

Arguments are those of `NixtlaClient.detect_anomalies_online`, except that
`num_partitions` is not supported.

| | **Type** | **Default** | **Details** |
| - | - | - | - |
| job\_timeout\_seconds | int | None | Maximum time in seconds the server may spend on the job. It may not exceed the limit of the deployment. Defaults to the deployment's limit. |
| **Returns** | **Job** | | **Handle to the submitted job. `job.wait()` returns the anomalies as a pandas or polars DataFrame.** |

***

[source](https://github.com/Nixtla/nixtla/blob/main/nixtla/nixtla_client.py#LNone)

## NixtlaClient.jobs.finetune

> ```text theme={null}
> NixtlaClient.jobs.finetune (
>     df, freq=None, id_col="unique_id", time_col="ds", target_col="y",
>     finetune_steps=10, finetune_depth=1, finetune_loss="default",
>     output_model_id=None, finetuned_model_id=None, model="timegpt-2.1",
>     job_timeout_seconds=None
> )
> ```

*Submit a fine-tuning job and return a handle to it without waiting.*

Arguments are those of `NixtlaClient.finetune`.

| | **Type** | **Default** | **Details** |
| - | - | - | - |
| job\_timeout\_seconds | int | None | Maximum time in seconds the server may spend on the job. It may not exceed the limit of the deployment. Defaults to the deployment's limit. |
| **Returns** | **Job** | | **Handle to the submitted job. `job.wait()` returns the fine-tuned model id as a string.** |

***

[source](https://github.com/Nixtla/nixtla/blob/main/nixtla/nixtla_client.py#LNone)

## NixtlaClient.jobs.simulate

> ```text theme={null}
> NixtlaClient.jobs.simulate (
>     df, h, freq=None, id_col="unique_id", time_col="ds",
>     target_col="y", X_df=None, n_paths=100, quantiles=None, seed=None,
>     finetuned_model_id=None, clean_ex_first=True, hist_exog_list=None,
>     categorical_exog_list=None, validate_api_key=False,
>     date_features=False, date_features_to_one_hot=False,
>     model="timegpt-2.1", multivariate=False, job_timeout_seconds=None
> )
> ```

*Submit a simulation job and return a handle to it without waiting.*

Arguments are those of `NixtlaClient.simulate`, except
that `num_partitions` is not supported — use `simulate()` to partition a large
request.

| | **Type** | **Default** | **Details** |
| - | - | - | - |
| job\_timeout\_seconds | int | None | Maximum time in seconds the server may spend on the job. It may not exceed the limit of the deployment. Defaults to the deployment's limit. |
| **Returns** | **Job** | | **Handle to the submitted job. `job.wait()` returns the sample paths as a pandas or polars DataFrame.** |

***

[source](https://github.com/Nixtla/nixtla/blob/main/nixtla/nixtla_client.py#LNone)

## NixtlaClient.jobs.explain

> ```text theme={null}
> NixtlaClient.jobs.explain (
>     df, method="granger", features=None, freq=None,
>     id_col="unique_id", time_col="ds", target_col="y",
>     categorical_exog_list=None, validate_api_key=False,
>     job_timeout_seconds=None
> )
> ```

*Submit a feature-importance job and return a handle to it without waiting.*

Arguments are those of `NixtlaClient.explain`.

| | **Type** | **Default** | **Details** |
| - | - | - | - |
| job\_timeout\_seconds | int | None | Maximum time in seconds the server may spend on the job. It may not exceed the limit of the deployment. Defaults to the deployment's limit. |
| **Returns** | **Job** | | **Handle to the submitted job. `job.wait()` returns the weights as a pandas or polars DataFrame.** |

***

[source](https://github.com/Nixtla/nixtla/blob/main/nixtla/nixtla_client.py#LNone)

## Job

*Handle to a server-side asynchronous job.*

Returned by every `client.jobs` method; not constructed directly. Importable
from the package root as `nixtla.Job`.

| | **Type** | **Details** |
| - | - | - |
| job\_id | str | Identifier of the job on the server. |
| task | str | Task the job runs, e.g. `"forecast"` or `"simulate"`. Labels the errors the job raises. |
| result | Any | The result, once `wait()` has returned it; `None` before that. |
| status | JobStatus | Current status. Queries the server unless a terminal status is already known, since a finished job's status cannot change again. |

### Job.wait

> ```text theme={null}
> Job.wait (poll_interval=None, poll_timeout=3600.0, cancel_on_timeout=True)
> ```

*Poll the job until it reaches a terminal state and return its result.*

| | **Type** | **Default** | **Details** |
| - | - | - | - |
| poll\_interval | float | None | Seconds between two status checks, held fixed. Must be finite and non-negative. By default the client polls on an adaptive cadence instead: the first check comes after half a second and the interval doubles up to one check every 15 seconds. |
| poll\_timeout | float | 3600.0 | Maximum seconds to wait for a terminal state before raising `JobTimeoutError`. Must be finite and positive, or `None` to poll until the server reports a terminal status. |
| cancel\_on\_timeout | bool | True | Whether to request cancellation when `poll_timeout` elapses, so a job you have given up on stops consuming server-side compute. Set to `False` to poll in short increments and call `wait()` again to resume. |
| **Returns** | **Any** | | **A DataFrame for forecast, cross-validation, anomaly-detection, simulate and explain jobs; a fine-tuned model id for finetune jobs.** |

Raises `JobError` if the job fails server-side, `JobCancelledError` if
it reaches the `cancelled` state, and `JobTimeoutError` if `poll_timeout`
elapses first. `poll_timeout` bounds the client's polling only: with
`cancel_on_timeout=False` the job keeps running server-side until its own
deadline. A run of transient status-check failures does not end the wait — the
client keeps polling while there is time left, and reports the last such failure
as the cause if the wait times out.

### Job.cancel

> ```text theme={null}
> Job.cancel ()
> ```

*Request cancellation of the job.*

### Job as a context manager

If an exception propagates out of the `with` block while the job is still
running, cancellation is requested automatically as best-effort cleanup. A block
left without an exception cancels nothing, and neither does an exception raised
by a job that has already reached a terminal state. An error raised by a
*different* job settles nothing about this one, so it is cleaned up as normal.

```python theme={null}
with client.jobs.forecast(df=df, h=12, freq="D") as job:
    fcst = job.wait()
```

***

## JobStatus

*Status of a server-side job.*

`PENDING`, `RUNNING`, `SUCCEEDED`, `FAILED` and `CANCELLED`. Each compares equal
to its lowercase string, so `job.status == "succeeded"` works. `SUCCEEDED`,
`FAILED` and `CANCELLED` are terminal.
