### Load and Prepare Stock Data using Pandas Source: https://github.com/rjt1990/pyflux/blob/master/docs/source/getting_started.rst Loads historical stock data using pandas-datareader and calculates daily returns. It handles data fetching, transformation, and indexing for time series analysis. Dependencies include pandas and pandas_datareader. ```python import pandas as pd import numpy as np from pandas_datareader.data import DataReader from datetime import datetime a = DataReader('JPM', 'yahoo', datetime(2006,6,1), datetime(2016,6,1)) a_returns = pd.DataFrame(np.diff(np.log(a['Adj Close'].values))) a_returns.index = a.index.values[1:a.index.values.shape[0]] a_returns.columns = ["JPM Returns"] ``` -------------------------------- ### Load and Prepare Stock Data for Time Series Analysis Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/_sources/getting_started.txt Loads historical stock data for a given ticker symbol using pandas_datareader, calculates daily returns, and prepares the data for time series analysis. It requires pandas, numpy, pandas_datareader, and datetime. ```python import pandas as pd import numpy as np from pandas_datareader.data import DataReader from datetime import datetime a = DataReader('JPM', 'yahoo', datetime(2006,6,1), datetime(2016,6,1)) a_returns = pd.DataFrame(np.diff(np.log(a['Adj Close'].values))) a_returns.index = a.index.values[1:a.index.values.shape[0]] a_returns.columns = ["JPM Returns"] a_returns.head() ``` -------------------------------- ### Specify and Initialize GARCH Model with PyFlux Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/getting_started.html Initializes a GARCH(1,1) model with specified data. It also prints the latent variables and their default prior distributions. This is the first step in building a GARCH model for volatility analysis. ```python my_model = pf.GARCH(p=1, q=1, data=a_returns) print(my_model.latent_variables) ``` -------------------------------- ### Plotting Model Fit in PyFlux Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/_sources/getting_started.txt This code visualizes the fit of a GARCH model against the actual time series data using PyFlux. It helps assess how well the model captures the historical patterns, including volatility clustering. ```python my_model.plot_fit(figsize=(15,5)) ``` -------------------------------- ### Define and Inspect a GARCH Model Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/_sources/getting_started.txt Initializes a GARCH(1,1) model using pyflux for time series data and prints the latent variables, including their prior distributions and transformations. This step is part of the model proposal phase in time series analysis. It requires pyflux. ```python import pyflux as pf # Assuming a_returns is already loaded and prepared my_model = pf.GARCH(p=1, q=1, data=a_returns) print(my_model.latent_variables) ``` -------------------------------- ### Visualize Time Series Data with Matplotlib Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/getting_started.html This code snippet visualizes time series data using Matplotlib. It plots the prepared stock returns data to identify trends, seasonality, and other properties. The primary input is a pandas DataFrame containing the time series. Ensure Matplotlib is installed (`pip install matplotlib`). ```python import matplotlib.pyplot as plt plt.figure(figsize=(15, 5)) plt.ylabel("Returns") plt.plot(a_returns) plt.show() ``` -------------------------------- ### Define and Inspect GARCH Model with PyFlux Source: https://github.com/rjt1990/pyflux/blob/master/docs/source/getting_started.rst Initializes a GARCH(1,1) model for time series data using PyFlux and prints its latent variables and prior distributions. This step is part of proposing a model based on observed data properties like volatility clustering. Requires PyFlux. ```python import pyflux as pf my_model = pf.GARCH(p=1, q=1, data=a_returns) print(my_model.latent_variables) ``` -------------------------------- ### Install PyFlux using pip Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/_sources/index.txt Installs the latest release version of PyFlux from PyPi. This command requires pip to be installed and accessible in your environment. Python 2.7 and 3.5+ are supported. ```bash pip install pyflux ``` -------------------------------- ### Plotting Latent Variables in PyFlux Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/_sources/getting_started.txt This snippet visualizes the latent variables (alpha and beta) of a GARCH model fitted using PyFlux. It helps in understanding the dynamics captured by the model. ```python my_model.plot_z([1,2]) ``` -------------------------------- ### Performing Metropolis-Hastings Inference in PyFlux Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/_sources/getting_started.txt This code performs approximate inference for a GARCH model using the Metropolis-Hastings algorithm within PyFlux. It includes setting the number of simulations and provides feedback on the acceptance rate. ```python result = my_model.fit('M-H', nsims=20000) ``` -------------------------------- ### Plotting Posterior Predictive Samples in PyFlux Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/_sources/getting_started.txt This snippet plots samples from the posterior predictive density of a PyFlux model. It allows comparison between the generated data samples and the actual observed data points. ```python my_model.plot_sample(nsims=10, figsize=(15,7)) ``` -------------------------------- ### Adjusting Priors in PyFlux Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/_sources/getting_started.txt This snippet demonstrates how to adjust prior distributions for model parameters in PyFlux using TruncatedNormal distributions. It is useful for setting specific constraints on parameter values. ```python my_model.adjust_prior(1, pf.TruncatedNormal(0.01, 0.5, lower=0.0, upper=1.0)) my_model.adjust_prior(2, pf.TruncatedNormal(0.97, 0.5, lower=0.0, upper=1.0)) ``` -------------------------------- ### Install PyFlux using pip Source: https://github.com/rjt1990/pyflux/blob/master/README.md This command installs the PyFlux library using pip, the standard package installer for Python. Ensure you have pip installed and configured correctly for your Python environment. ```bash pip install pyflux ``` -------------------------------- ### Visualize Time Series Data and Autocorrelation Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/_sources/getting_started.txt Visualizes time series data using matplotlib and plots autocorrelation functions (ACF) for both the series and its squared values using pyflux. This helps in understanding data properties, trends, and volatility clustering. It requires matplotlib and pyflux. ```python import matplotlib.pyplot as plt import pyflux as pf import numpy as np # Assuming a_returns is already loaded and prepared plt.figure(figsize=(15, 5)) plt.ylabel("Returns") plt.plot(a_returns) plt.show() pf.acf_plot(a_returns.values.T[0]) pf.acf_plot(np.square(a_returns.values.T[0])) ``` -------------------------------- ### Perform Metropolis-Hastings Inference with PyFlux Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/getting_started.html Executes approximate Bayesian inference for the GARCH model using the Metropolis-Hastings algorithm. It also plots the latent variables (alpha and beta) after inference. Requires specifying the number of simulations (nsims). ```python result = my_model.fit('M-H', nsims=20000) my_model.plot_z([1,2]) ``` -------------------------------- ### SEGARCHM Model Initialization and Fitting Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/_sources/segarchm.txt This section describes how to initialize and fit a Beta Skew-t EGARCH in-mean model using the pyflux library. It includes example Python code for loading data, creating the model instance, fitting it to the data, and displaying a summary of the results. ```APIDOC ## SEGARCHM Model Initialization and Fitting ### Description This endpoint describes the initialization and fitting of the Beta Skew-t EGARCH in-mean model. It covers data preparation, model instantiation, and the fitting process using Maximum Likelihood Estimation (MLE). ### Method `pf.SEGARCHM(p, q, data, target)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **data** (pd.DataFrame or np.ndarray) - Required - Contains the univariate time series data. * **p** (int) - Required - The number of autoregressive lags for the conditional variance (ARCH terms). * **q** (int) - Required - The number of GARCH terms for the conditional variance. * **target** (string or int) - Required - The name or index of the column in the data to be used as the dependent variable. ### Request Example ```python import pyflux as pf import pandas as pd import numpy as np from pandas.io.data import DataReader from datetime import datetime # Load sample financial data aapl = DataReader('AAPL', 'yahoo', datetime(2006,1,1), datetime(2016,3,10)) returns = pd.DataFrame(np.diff(np.log(aapl['Adj Close'].values))) returns.index = aapl.index.values[1:aapl.index.values.shape[0]] returns.columns = ['AAPL Returns'] # Initialize and fit the SEGARCHM model skewt_model = pf.SEGARCHM(p=1, q=1, data=returns, target='AAPL Returns') x = skewt_model.fit() ``` ### Response #### Success Response (200) Upon successful fitting, the `fit()` method returns a model object which contains the fitted parameters and summary statistics. #### Response Example ``` SEGARCHM(1,1) ======================================== ================================================= Dependent Variable: AAPL Returns Method: MLE Start Date: 2006-01-05 00:00:00 Log Likelihood: 6547.0586 End Date: 2016-03-10 00:00:00 AIC: -13080.1172 Number of observations: 2562 BIC: -13039.1774 ========================================================================================== Latent Variable Estimate Std Error z P>|z| 95% C.I. ========================= ========== ========== ======== ======== ======================== Vol Constant -0.2917 0.0074 -39.3318 0.0 (-0.3063 | -0.2772) p(1) 0.9653 q(1) 0.1354 Skewness 0.9201 v 6.7153 Returns Constant 0.0028 0.0001 19.4147 0.0 (0.0025 | 0.0031) GARCH-M 0.362 0.1235 2.9323 0.0034 (0.12 | 0.604) ========================================================================================== ``` ### Error Handling - If data is not provided or is in an incorrect format, an error will be raised. - If `p` or `q` are not positive integers, an error will be raised. - If the `target` column is not found in the data, an error will be raised. ``` -------------------------------- ### PyFlux Non-Gaussian State Space Model Examples Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/ngssm.html Demonstrates initializing and preparing non-Gaussian state space models using PyFlux. It shows how to load data and instantiate models like Poisson for local level and t-distribution for dynamic regression. ```python import numpy as np import pyflux as pf import pandas as pd leicester = pd.read_csv('http://www.pyflux.com/notebooks/leicester_goals_scored.csv') leicester.columns= ["Time","Leicester Goals Scored"] model = pf.NLLEV.Poisson(data=leicester,target='Leicester Goals Scored') fb = DataReader('FB', 'yahoo', datetime(2015,5,1), datetime(2016,5,10)) returns = pd.DataFrame(np.diff(np.log(fb['Open'].values))) returns.index = fb.index.values[1:fb.index.values.shape[0]] returns.columns = ['Facebook Returns'] model2 = pf.NLLEV.t(data=returns,target='Close') ``` -------------------------------- ### Initialize GAS Local Linear Trend Model Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/gasssm.html Initializes a GAS Local Linear Trend model using US GDP growth data. This example shows how to load and prepare log-transformed GDP data, set the index to datetime, and then instantiate the GASLLT model with a GAS-t family. Dependencies include numpy, pyflux, and pandas. ```python import numpy as np import pyflux as pf import pandas as pd USgrowth = pd.DataFrame(np.log(growthdata['VALUE'])) USgrowth.index = pd.to_datetime(growthdata['DATE']) USgrowth.columns = ['Logged US Real GDP'] model2 = pf.GASLLT(data=USgrowth, family=pf.GASt()) # local linear trend model ``` -------------------------------- ### Plotting Future Predictions in PyFlux Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/_sources/getting_started.txt This snippet generates and plots forward predictions for a fitted PyFlux model. It is used to forecast future values of the time series. ```python my_model.plot_predict(h=30, figsize=(15,5)) ``` -------------------------------- ### Plot Autocorrelation Functions with PyFlux Source: https://github.com/rjt1990/pyflux/blob/master/docs/source/getting_started.rst Generates autocorrelation plots (ACF) for raw returns and squared returns using PyFlux. This helps in identifying autocorrelation, particularly in volatility clustering. Requires PyFlux and NumPy. ```python import pyflux as pf import matplotlib.pyplot as plt import numpy as np pf.acf_plot(a_returns.values.T[0]) pf.acf_plot(np.square(a_returns.values.T[0])) ``` -------------------------------- ### GARCH Model Initialization and Fitting Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/garch.html Demonstrates how to initialize a GARCH model with specified returns, autoregressive (p), and ARCH (q) lags, and then fit the model using Maximum Likelihood Estimation (MLE). ```APIDOC ## GARCH Model Initialization and Fitting ### Description Initializes a GARCH(p,q) model and fits it to the provided time series data using a specified estimation method. The `fit` method returns a results object and updates the model's latent variables. ### Method `model.fit()` ### Parameters #### Request Body - **returns** (pd.DataFrame or np.ndarray) - Required - The univariate time series data. - **p** (int) - Required - The number of autoregressive lags for \(\sigma^{2}\). - **q** (int) - Required - The number of ARCH terms for \(\epsilon^{2}\). - **target** (string or int) - Optional - The column name or index to use if `returns` is a DataFrame. - **method** (str) - Optional - The inference option for estimation (e.g., 'MLE', 'M-H'). Defaults to 'MLE'. ### Request Example ```python import pyflux as pf # Assuming 'returns' is your time series data model = pf.GARCH(returns, p=1, q=1) x = model.fit(method='MLE') ``` ### Response #### Success Response (200) - **Results Instance** (pf.Results) - An object containing information on the estimated latent variables. #### Response Example ```json { "summary": "Model Summary String" } ``` ``` -------------------------------- ### Initialize GAS Local Level Model Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/gasssm.html Initializes a GAS Local Level model using the Nile river data. This example demonstrates loading data, setting the target variable, and specifying the GAS-t distribution for the model. Dependencies include numpy, pyflux, and pandas. ```python import numpy as np import pyflux as pf import pandas as pd nile = pd.read_csv('https://vincentarelbundock.github.io/Rdatasets/csv/datasets/Nile.csv') nile.index = pd.to_datetime(nile['time'].values,format='%Y') model = pf.GASLLEV(data=nile, target='Nile', family=pf.GASt()) # local level ``` -------------------------------- ### ARIMAX Model Fitting Example in Python Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/arimax.html This Python code snippet demonstrates how to fit an ARIMAX model using the PyFlux library. It includes data loading, preprocessing for intervention variables, model definition with AR and MA components, and fitting using Maximum Likelihood Estimation (MLE). The code requires pandas, pyflux, and matplotlib for data manipulation, modeling, and visualization. ```python import numpy as np import pandas as pd import pyflux as pf from datetime import datetime import matplotlib.pyplot as plt %matplotlib inline data = pd.read_csv("https://vincentarelbundock.github.io/Rdatasets/csv/MASS/drivers.csv") data.index = data['time']; data.loc[(data['time']>=1983.05), 'seat_belt'] = 1; data.loc[(data['time']<1983.05), 'seat_belt'] = 0; data.loc[(data['time']>=1974.00), 'oil_crisis'] = 1; data.loc[(data['time']<1974.00), 'oil_crisis'] = 0; plt.figure(figsize=(15,5)); plt.plot(data.index,data['drivers']); plt.ylabel('Driver Deaths'); plt.title('Deaths of Car Drivers in Great Britain 1969-84'); plt.plot(); model = pf.ARIMAX(data=data, formula='drivers~1+seat_belt+oil_crisis', ar=1, ma=1, family=pf.Normal()) x = model.fit("MLE") x.summary() ``` -------------------------------- ### Performing Posterior Predictive Check (PPC) in PyFlux Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/_sources/getting_started.txt This code performs a posterior predictive check (PPC) on a feature of the generated series, such as kurtosis, using a user-defined function (e.g., from scipy.stats). It helps evaluate model assumptions. ```python from scipy.stats import kurtosis my_model.plot_ppc(T=kurtosis) ``` -------------------------------- ### Initialize LLEV and LLT Models in Python Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/_sources/ssm.txt Demonstrates how to initialize Local Level (LLEV) and Local Linear Trend (LLT) models using PyFlux. It shows data loading and preparation, including time series conversion, for both models. ```python import numpy as np import pyflux as pf import pandas as pd nile = pd.read_csv('https://vincentarelbundock.github.io/Rdatasets/csv/datasets/Nile.csv') nile.index = pd.to_datetime(nile['time'].values,format='%Y') model = pf.LLEV(data=nile,target='Poisson') # local level USgrowth = pd.DataFrame(np.log(growthdata['VALUE'])) USgrowth.index = pd.to_datetime(growthdata['DATE']) USgrowth.columns = ['Logged US Real GDP'] model2 = pf.LLT(data=USgrowth) # local linear trend model ``` -------------------------------- ### ARIMA Model Fitting Example in Python Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/arima.html This Python code demonstrates how to load sunspot data, define an ARIMA model with specified orders (p, d, q), and fit the model using Maximum Likelihood Estimation (MLE) in PyFlux. It includes data loading, visualization, model instantiation, and fitting. Dependencies include numpy, pandas, pyflux, datetime, and matplotlib. ```python import numpy as np import pandas as pd import pyflux as pf from datetime import datetime import matplotlib.pyplot as plt %matplotlib inline data = pd.read_csv('https://vincentarelbundock.github.io/Rdatasets/csv/datasets/sunspot.year.csv') data.index = data['time'].values plt.figure(figsize=(15,5)) plt.plot(data.index,data['sunspot.year']) plt.ylabel('Sunspots') plt.title('Yearly Sunspot Data'); model = pf.ARIMA(data=data, ar=4, ma=4, target='sunspot.year', family=pf.Normal()) x = model.fit("MLE") x.summary() ``` -------------------------------- ### Fit GASX(1,1) Model with Skew-t Distribution in PyFlux Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/_sources/gasx.txt This Python code snippet demonstrates how to instantiate and fit a GASX(1,1) model using the PyFlux library. It specifies the model formula, exogenous variables, autoregressive (ar) and smooth conditional (sc) orders, and uses a Skew-t distribution for the model. Ensure PyFlux is installed. ```python import pyflux as pf # Assuming 'final_returns' DataFrame is already prepared as shown in the previous example model = pf.GASX(formula="Amazon~SP500",data=final_returns,ar=1,sc=1,family=pf.GASSkewt()) x = model.fit() x.summary() ``` -------------------------------- ### Plot Autocorrelation Functions with PyFlux Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/getting_started.html Generates plots for the autocorrelation function (ACF) of series returns and squared returns. This helps identify autoregressive effects and volatility clustering. Requires pyflux and matplotlib libraries. ```python import pyflux as pf import matplotlib.pyplot as plt pf.acf_plot(a_returns.values.T[0]) pf.acf_plot(np.square(a_returns.values.T[0])) ``` -------------------------------- ### Initializing GASX Model in PyFlux Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/gasx.html Shows the constructor for the GASX model, detailing the required parameters such as data, formula, autoregressive lags, score function lags, differencing, target column, and the distribution family. ```python GASX(data, formula, ar, sc, integ, target, family) ``` -------------------------------- ### GASX Methods Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/gasx.html Documentation for the methods available on a GASX model instance, including adjusting priors, fitting the model, and plotting results. ```APIDOC ## GASX Methods ### Description This section details the methods available for a fitted GASX model. ### Method `adjust_prior` ### Description Adjusts the priors for the model latent variables. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **index** (int) - Required - Index of the latent variable to change - **prior** (pf.Family instance) - Required - Prior distribution, e.g. `pf.Normal()` ### Request Example ```json { "index": 0, "prior": "pf.Normal()" } ``` ### Response #### Success Response (200) - **void**: Changes the model `latent_variables` attribute. #### Response Example ```json { "message": "Prior adjusted successfully" } ``` --- ### Method `fit` ### Description Estimates latent variables for the model. User chooses an inference option and the method returns a results object, as well as updating the model’s `latent_variables` attribute. ### Parameters #### Path Parameters None #### Query Parameters - **method** (str) - Required - Inference option: e.g. ‘M-H’ or ‘MLE’. See Bayesian Inference and Classical Inference sections of the documentation for the full list of inference options. Optional parameters can be entered that are relevant to the particular mode of inference chosen. #### Request Body None ### Request Example ```json { "method": "MLE" } ``` ### Response #### Success Response (200) - **pf.Results instance**: With information for the estimated latent variables. #### Response Example ```json { "model_fit_summary": "..." } ``` --- ### Method `plot_fit` ### Description Plots the fit of the model against the data. ### Parameters #### Path Parameters None #### Query Parameters - **figsize** (tuple) - Optional - The dimensions of the figure to plot. #### Request Body None ### Request Example ```json { "figsize": "(15, 10)" } ``` ### Response #### Success Response (200) - **void**: Shows a matplotlib plot. #### Response Example ```json { "message": "Plot displayed successfully" } ``` --- ### Method `plot_ppc` ### Description Plots Posterior Predictive Checks for the model. ### Parameters #### Path Parameters None #### Query Parameters - **T** (int) - Required - Number of simulations to plot. - **nsims** (int) - Required - Number of posterior draws to use. #### Request Body None ### Request Example ```json { "T": 100, "nsims": 500 } ``` ### Response #### Success Response (200) - **void**: Shows a matplotlib plot. #### Response Example ```json { "message": "Plot displayed successfully" } ``` ``` -------------------------------- ### Initialize and Fit PyFlux VAR Model Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/_sources/var.txt Demonstrates the initialization of a Vector Autoregression (VAR) model in PyFlux and its subsequent fitting. The VAR class requires data, number of lags, and optionally integration order and target variable. The fit method estimates model parameters using a specified inference method (e.g., 'M-H' or 'MLE'). ```python from pyflux import VAR # Assuming 'data', 'lags', 'integ', 'target', 'use_ols_covariance' are defined model = VAR(data=data, lags=lags, integ=integ, target=target, use_ols_covariance=use_ols_covariance) results = model.fit(method='MLE') # or method='M-H' print(results) ``` -------------------------------- ### Instantiate and Fit Dynamic Regression Models (Python) Source: https://github.com/rjt1990/pyflux/blob/master/docs/source/dyn_lin.rst This snippet shows how to instantiate a Dynamic Linear Regression model using the PyFlux library, both with a formula interface and a more general DynamicGLM wrapper. It also demonstrates fitting the model and viewing a summary of the results. ```python model = pf.DynReg('Amazon ~ SP500', data=final_returns) x = model.fit() x.summary() ``` ```python model = pf.DynamicGLM('Amazon ~ SP500', data=USgrowth, family=pf.Normal()) x = model.fit() x.summary() ``` -------------------------------- ### GASX Class Initialization Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/gasx.html Initializes a GASX model with specified data, formula, and model parameters. ```APIDOC ## GASX Class ### Description Generalized Autoregressive Score Exogenous Variable Models (GASX). ### Method __init__ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (pd.DataFrame or np.ndarray) - Required - Contains the univariate time series - **formula** (string) - Required - Patsy notation specifying the regression - **ar** (int) - Required - The number of autoregressive lags - **sc** (int) - Required - The number of score function lags - **integ** (int) - Optional - How many times to difference the data (default: 0) - **target** (string or int) - Optional - Which column of DataFrame/array to use. - **family** (pf.Family instance) - Required - The distribution for the time series, e.g `pf.Normal()` ### Request Example ```json { "data": "...", "formula": "...", "ar": 1, "sc": 1, "integ": 0, "target": "...", "family": "pf.Normal()" } ``` ### Response #### Success Response (200) - **GASX instance**: A GASX model instance is returned upon successful initialization. #### Response Example ```json { "message": "GASX model initialized successfully" } ``` ``` -------------------------------- ### Initialize and Fit VAR Model (Python) Source: https://github.com/rjt1990/pyflux/blob/master/docs/source/var.rst This snippet demonstrates how to initialize and fit a Vector Autoregression (VAR) model using the pyflux library. It specifies the model with a dataset, the number of lags, and the integration order. The `fit()` method is called to estimate the model parameters. ```python model = pf.VAR(data=opening_prices, lags=2, integ=1) x = model.fit() x.summary() ``` -------------------------------- ### GARCH Class Source: https://github.com/rjt1990/pyflux/blob/master/docs/source/garch.rst Documentation for the GARCH class, including its parameters for initializing a GARCH model. ```APIDOC ## GARCH Class ### Description Generalized Autoregressive Conditional Heteroskedasticity Models (GARCH). ### Parameters #### Path Parameters - **data** (pd.DataFrame or np.ndarray) - Contains the univariate time series - **p** (int) - The number of autoregressive lags :math:`\sigma^{2}` - **q** (int) - The number of ARCH terms :math:`\epsilon^{2}` - **target** (string or int) - Which column of DataFrame/array to use. ``` -------------------------------- ### SEGARCH Model Initialization and Fitting Source: https://github.com/rjt1990/pyflux/blob/master/docs/source/segarch.rst Demonstrates how to initialize a SEGARCH model with specified order (p, q) and target variable, add a leverage term, fit the model, and display a summary of the results. ```APIDOC ## SEGARCH Model Initialization and Fitting ### Description Initializes a SEGARCH model, adds a leverage term to account for asymmetric volatility responses, fits the model to the provided data, and displays a summary of the model parameters and statistics. ### Method POST ### Endpoint /api/pyflux/segarch/fit ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (DataFrame or ndarray) - Required - The time series data. - **p** (int) - Required - The number of autoregressive lags for the conditional variance. - **q** (int) - Required - The number of ARCH terms for the conditional variance. - **target** (string or int) - Required - The column name or index of the target variable in the data. ### Request Example ```json { "data": [ [0.1], [0.2], [-0.1], [0.3] ], "p": 1, "q": 1, "target": "JPM Returns" } ``` ### Response #### Success Response (200) - **model_summary** (string) - A string containing the summary of the fitted SEGARCH model. #### Response Example ```json { "model_summary": "SEGARCH(1,1) ======================================== ... ================" } ``` ``` -------------------------------- ### Estimate GASX(1,1) Model with PyFlux Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/gasx.html This snippet shows how to fit a GASX(1,1) model to the prepared financial data using PyFlux. It specifies the model formula, exogenous variables, autoregressive and static components, and the GASSkewt family. The output includes a summary of the fitted model. ```python model = pf.GASX(formula="Amazon~SP500",data=final_returns,ar=1,sc=1,family=pf.GASSkewt()) x = model.fit() x.summary() ``` -------------------------------- ### GASLLEV Model Initialization Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/_sources/gasssm.txt Initializes a GAS local level model with specified data and parameters. ```APIDOC ## GASLLEV Model ### Description Initializes a GAS local level model. ### Method Constructor ### Endpoint `GASLLEV(data, integ=0, target=None, family=GASNormal())` ### Parameters #### Class Arguments - **data** (pd.DataFrame or array-like) - The time-series data. - **integ** (int) - How many times to difference the time series (default: 0). - **target** (string or int) - Which column to use as the time series. If None, the first column will be chosen as the data. - **family** (GAS family object) - A GAS family object; choices include GASExponential(), GASLaplace(), GASNormal(), GASPoisson(), GASSkewt(), GASt(). ### Request Example ```python import pyflux as pf import pandas as pd nile = pd.read_csv('https://vincentarelbundock.github.io/Rdatasets/csv/datasets/Nile.csv') nile.index = pd.to_datetime(nile['time'].values,format='%Y') model = pf.GASLLEV(data=nile, target='Nile', family=pf.GASt()) ``` ``` -------------------------------- ### Get Model Predictions Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/dyn_glm.html Returns a DataFrame containing model predictions for a specified future period. ```APIDOC ## Get Model Predictions ### Description Returns a DataFrame of model predictions. Note that intervals shown may not reflect latent variable uncertainty for Maximum Likelihood or Variational Inference methods. ### Method GET (Implied) ### Endpoint `/model/predict` (Implied) ### Parameters #### Path Parameters None #### Query Parameters - **h** (int) - Required - How many steps to forecast ahead. - **oos_data** (pd.DataFrame) - Required - Exogenous variables in a DataFrame for `h` steps. Must be in the same format as the initial data. ### Request Example ```json { "h": 10, "oos_data": "" } ``` ### Response #### Success Response (200) - **predictions** (pd.DataFrame) - A DataFrame containing the model predictions. #### Response Example ```json { "predictions": "" } ``` ``` -------------------------------- ### Model Initialization Source: https://github.com/rjt1990/pyflux/blob/master/docs/source/arimax.rst Parameters for initializing a PyFlux model. ```APIDOC ## Model Initialization Parameters ### Description Initializes a PyFlux model with specified parameters for time series analysis. ### Parameters #### Required Parameters - **ma** (int) - The number of moving average lags. - **integ** (int) - How many times to difference the data (default: 0). - **target** (string or int) - Which column of DataFrame/array to use. - **family** (pf.Family instance) - The distribution for the time series, e.g. ``pf.Normal()``. ``` -------------------------------- ### Getting Predictions in DataFrame Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/gas.html Retrieves model predictions in a pandas DataFrame format. ```APIDOC ## Get Predictions as DataFrame ### Description Retrieves the model's predictions in a pandas DataFrame. ### Method model.predict() ### Endpoint N/A (Method call) ### Parameters None ### Request Example ```json { "example": "predictions_df = model.predict()" } ``` ### Response #### Success Response (200) - **predictions** (pd.DataFrame) - DataFrame containing the model predictions. #### Response Example ```json { "example": "DataFrame with prediction values" } ``` ``` -------------------------------- ### Get Model Predictions Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/_sources/egarchm.txt Returns a DataFrame containing model predictions. ```APIDOC ## predict ### Description Returns a DataFrame of model predictions. ### Method Not applicable (method of a model object) ### Endpoint Not applicable (method of a model object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **h** (int) - Required - How many steps to forecast ahead. - **intervals** (boolean) - Optional - Whether to include prediction intervals (default is False). ### Request Example ```python # Assuming 'model' is a fitted PyFlux model object predictions_df = model.predict(h=10, intervals=True) print(predictions_df) ``` ### Response #### Success Response (200) - **DataFrame** - A pandas DataFrame containing the model predictions. Columns may include 'mean', 'lower_bound', and 'upper_bound' if intervals are requested. #### Response Example ```json { "Date": ["2023-01-01", "2023-01-02"], "mean": [100.5, 101.2], "lower_bound": [99.1, 100.0], "upper_bound": [101.9, 102.4] } ``` ``` -------------------------------- ### Fit VAR(2) Model using PyFlux Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/_sources/var.txt This Python code initializes and fits a Vector Autoregression (VAR) model of order 2 using the PyFlux library. The model is applied to the provided 'opening_prices' data, with the 'integ' parameter set to 1, indicating first-order differencing. The fitting is done using Ordinary Least Squares (OLS). ```python model = pf.VAR(data=opening_prices, lags=2, integ=1) x = model.fit() ``` -------------------------------- ### Get Model Predictions in Python Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/_sources/gpnar.txt Returns a DataFrame containing model predictions for a specified number of future steps (h). ```python import pyflux as pf # model = ... (specify a model) # model.fit(...) predictions_df = model.predict(h=15) ``` -------------------------------- ### SEGARCH Model Plotting Source: https://github.com/rjt1990/pyflux/blob/master/docs/source/segarch.rst Provides examples for plotting the fit of a fitted SEGARCH model and for plotting future predictions. ```APIDOC ## SEGARCH Model Plotting ### Description These endpoints allow visualization of the fitted SEGARCH model and its future predictions. ### Method GET ### Endpoint /api/pyflux/segarch/{model_id}/plot_fit /api/pyflux/segarch/{model_id}/plot_predict ### Parameters #### Path Parameters - **model_id** (string) - Required - The unique identifier for the fitted SEGARCH model. #### Query Parameters - **h** (int) - Optional - The number of periods to predict ahead (for `plot_predict`). - **figsize** (tuple) - Optional - The size of the figures (e.g., "(15,5)"). #### Request Body None ### Request Example ```http GET /api/pyflux/segarch/model123/plot_fit?figsize=(15,5) GET /api/pyflux/segarch/model123/plot_predict?h=30&figsize=(15,5) ``` ### Response #### Success Response (200) - **plot_fit_url** (string) - URL to the plot of the model fit. - **plot_predict_url** (string) - URL to the plot of the future predictions. #### Response Example ```json { "plot_fit_url": "http://www.pyflux.com/notebooks/SkewtEGARCH/output_19_0.png" } ``` ```json { "plot_predict_url": "http://www.pyflux.com/notebooks/SkewtEGARCH/output_21_0.png" } ``` ``` -------------------------------- ### Model Methods Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/_sources/gasssm.txt Common methods available for GAS State Space models. ```APIDOC ## Model Methods ### Description Provides a summary of common methods for GAS State Space models. ### Methods #### `adjust_prior(index, prior)` ##### Description Adjusts the priors of the model. `index` can be an int or a list. `prior` is a prior object, such as Normal(0,3). ##### Endpoint `model.adjust_prior(index, prior)` ##### Request Example ```python import pyflux as pf # model = ... (specify a model) model.list_priors() model.adjust_prior(2,pf.Normal(0,1)) ``` #### `fit(method, **kwargs)` ##### Description Estimates latent variables for the model. Returns a Results object. `method` is an inference/estimation option. ##### Endpoint `model.fit(method, **kwargs)` ##### Request Example ```python import pyflux as pf # model = ... (specify a model) model.fit("M-H", nsims=20000) ``` #### `plot_fit(intervals, **kwargs)` ##### Description Graphs the fit of the model. `intervals` is a boolean; if true shows 95% C.I. intervals for the states. ##### Endpoint `model.plot_fit(intervals, **kwargs)` #### `plot_z(indices, figsize)` ##### Description Returns a plot of the latent variables and their associated uncertainty. `indices` is a list referring to the latent variable indices that you want to plot. `figsize` specifies how big the plot will be. ##### Endpoint `model.plot_z(indices, figsize)` #### `plot_predict(h, past_values, intervals, **kwargs)` ##### Description Plots predictions of the model. `h` is an int of how many steps ahead to predict. `past_values` is an int of how many past values of the series to plot. `intervals` is a bool on whether to include confidence/credibility intervals or not. ##### Endpoint `model.plot_predict(h, past_values, intervals, **kwargs)` #### `plot_predict_is(h, fit_once, **kwargs)` ##### Description Plots in-sample rolling predictions for the model. `h` is an int of how many previous steps to simulate performance on. `fit_once` is a boolean specifying whether to fit the model once at the beginning of the period (True), or whether to fit after every step (False). ##### Endpoint `model.plot_predict_is(h, fit_once, **kwargs)` #### `predict(h)` ##### Description Returns DataFrame of model predictions. `h` is an int of how many steps ahead to predict. ##### Endpoint `model.predict(h)` #### `predict_is(h, fit_once)` ##### Description Returns DataFrame of in-sample rolling predictions for the model. `h` is an int of how many previous steps to simulate performance on. `fit_once` is a boolean specifying whether to fit the model once at the beginning of the period (True), or whether to fit after every step (False). ##### Endpoint `model.predict_is(h, fit_once)` ``` -------------------------------- ### GASRank Model Initialization and Fitting Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/_sources/gas_rank.txt Initializes a GASRank model using pyflux, specifying the data, team identifiers, score difference column, and the distribution family (Normal in this case). It then fits the model to the data using Maximum Likelihood Estimation (MLE) and displays a summary of the results. ```python model = pf.GASRank(data=data,team_1="HomeTeam", team_2="AwayTeam", score_diff="PointsDiff", family=pf.Normal()) x = model.fit() x.summary() ``` -------------------------------- ### Getting GARCH Future Predictions as DataFrame Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/garch.html Retrieves predictions of future conditional volatility in a pandas DataFrame format. ```APIDOC ## Getting GARCH Future Predictions as DataFrame ### Description Provides predictions of future conditional volatility directly as a pandas DataFrame, allowing for further programmatic analysis or integration. ### Method `model.predict()` ### Parameters #### Query Parameters - **h** (int) - Required - The number of periods ahead to predict. ### Request Example ```python # Assuming 'model' is a fitted GARCH model instance predictions_df = model.predict(h=10) print(predictions_df) ``` ### Response #### Success Response (200) - **pd.DataFrame** - A DataFrame containing the predicted future conditional volatility values. #### Response Example ```json { "Date": ["2016-03-11", ...], "h=1": [0.001, ...], "h=2": [0.0011, ...] } ``` ``` -------------------------------- ### PyFlux ARIMA with Exponential Family Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/families.html Example of initializing an ARIMA model in PyFlux using the Exponential family for model measurement densities. ```python model = pf.ARIMA(ar=1, ma=0, data=my_data, family=pf.Exponential()) ``` -------------------------------- ### Model Initialization Parameters Source: https://github.com/rjt1990/pyflux/blob/master/docs/source/gas_reg.rst Parameters used when initializing a PyFlux model. ```APIDOC ## Model Initialization Parameters ### Description Parameters that can be provided when initializing a PyFlux model. ### Parameters #### Request Body - **data** (pd.DataFrame or np.ndarray) - Contains the univariate time series - **formula** (string) - Patsy notation specifying the regression - **target** (string or int) - Which column of DataFrame/array to use. - **family** (pf.Family instance) - The distribution for the time series, e.g ``pf.Normal()`` ``` -------------------------------- ### PyFlux ARIMA with Normal Family Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/families.html Example of using the Normal family for model measurement densities or priors when initializing an ARIMA model in PyFlux. ```python model = pf.ARIMA(ar=1, ma=0, data=my_data, family=pf.Normal(mu=0, sigma=1)) ``` -------------------------------- ### PyFlux Model Prior Adjustment with InverseGamma Family Source: https://github.com/rjt1990/pyflux/blob/master/docs/build/families.html Example of setting a prior distribution using the InverseGamma family for a model parameter in PyFlux. ```python model.adjust_prior(0, pf.InverseGamma(1, 1)) ```