MATLAB Examples

Copyright 2016 - 2016 The MathWorks, Inc.

Connect to FRED®, retrieve historical foreign exchange rates, and determine when the highest rate occurred.

Compute the sample autocorrelation function (ACF) and partial autocorrelation function (PACF) to qualitatively assess autocorrelation.

Specify an AR(p) model with constant term equal to zero. Use name-value syntax to specify a model that differs from the default model.

Prepare exogenous data for several seemingly unrelated regression (SUR) analyses. The response and exogenous series are random paths from a standard Gaussian distribution.

Inspect a squared residual series for autocorrelation by plotting the sample autocorrelation function (ACF) and partial autocorrelation function (PACF). Then, conduct a Ljung-Box

Assess whether a time series is a random walk. It uses market data for daily returns of stocks and cash (money market) from the period January 1, 2000 to November 7, 2005.

Use the Box-Jenkins methodology to select an ARIMA model. The time series is the log quarterly Australian Consumer Price Index (CPI) measured from 1972 and 1991.

Estimate long-term trend using a symmetric moving average function. This is a convolution that you can implement using conv. The time series is monthly international airline passenger

Compute and plot the impulse response function for an autoregressive (AR) model. The AR(p) model is given by

Use Akaike Information Criterion (AIC) to select the nonseasonal autoregressive and moving average lag polynomial degrees for a regression model with ARMA errors.

To illustrate assigning property values, consider specifying the AR(2) model

Simulate sample paths from a stationary AR(2) process without specifying presample observations.

Do goodness of fit checks. Residual diagnostic plots help verify model assumptions, and cross-validation prediction checks help assess predictive performance. The time series is

Implement the capital asset pricing model (CAPM) using the Econometrics Toolbox™ multivariate time series framework.

Plot the impulse response function for an autoregressive moving average (ARMA) model. The ARMA(p, q) model is given by

Conduct the Ljung-Box Q-test for autocorrelation.

The Engle-Granger method has several limitations. First of all, it identifies only a single cointegrating relation, among what might be many such relations. This requires one of the

Estimate a multivariate time series model that contains lagged endogenous and exogenous variables, and how to simulate responses. The response series are the quarterly:

Calculate and plot the impulse response function for a moving average (MA) model. The MA(q) model is given by

Specify a GARCH model with a Student's t innovation distribution.

Test a univariate time series for a unit root. It uses wages data (1900-1970) in the manufacturing sector. The series is in the Nelson-Plosser data set.

Specify a multiplicative seasonal ARIMA model (for quarterly data) with known parameter values. You can use such a fully specified model as an input to simulate or forecast.

Simulate sample paths from a stationary MA(12) process without specifying presample observations.

As another illustration, consider specifying the GARCH(1,1) model

Use an underlying mortgage-backed security (MBS) pool for a 30-year fixed-rate mortgage of 6% to define a PAC bond, and then define a sequential CMO from the PAC bond. Analyze the CMO by

Use ZeroRates for a zero curve that is hard-coded. You can also create a zero curve by bootstrapping the zero curve from market data (for example, deposits, futures/forwards, and swaps)

Price a single-name CDS option using cdsoptprice. The function cdsoptprice is based on the Black's model as described in O'Kane (2008). The optional knockout argument for cdsoptprice

Demonstrates optimizing a storage facility and valuing a storage contract using intrinsic valuation. The optimization involves finding the optimal positions in a set of forward natural

Price a swaption using the SABR model. First, a swaption volatility surface is constructed from market volatilities. This is done by calibrating the SABR model parameters separately for

Compute risk neutral standardized moments of an asset's return distribution from volatility smile interpolation. Part of the IMOMBOX.

Compute risk-neutral prices of a contract paying an asset's return or powers thereof from traded options. Part of the IMOMBOX.

Compute risk neutral standardized moments of an asset's return distribution from traded options. Part of the IMOMBOX.

Compute risk-neutral prices of a contract paying an asset's return or powers thereof from volatility smile interpolation. Part of the IMOMBOX.

This file replicates cross-currency forward pricing using covered interest parity (CIP). It generates and plots CIP-implied forward exchange rates and calculates forward contract

Compute the unilateral credit value (valuation) adjustment (CVA) for a bank holding a portfolio of vanilla interest rate swaps with several counterparties. CVA is the expected loss on an

An approach to modeling wrong-way risk for Counterparty Credit Risk using a Gaussian copula.

Simulate electricity prices using a mean-reverting model with seasonality and a jump component. The model is calibrated under the real-world probability using historical electricity

Different hedging strategies to minimize exposure in the Energy market using Crack Spread Options.

Price a swing option using a Monte Carlo simulation and the Longstaff-Schwartz method. A risk-neutral simulation of the underlying natural gas price is conducted using a mean-reverting

Price and calculate sensitivities for European and American spread options using various techniques. First, the price and sensitivities for a European spread option is calculated using

Price first-to-default (FTD) swaps under the homogeneous loss assumption.

Illustrates how the Financial Toolbox™ and Financial Instruments Toolbox™ are used to price a level mortgage backed security using the BDT model.

Illustrates how the Financial Instruments Toolbox™ is used to price European vanilla call options using different equity models.

Illustrates how MATLAB® can be used to create a portfolio of interest rate derivatives securities, and price it using the Black-Karasinski interest rate model. The example also shows some

Illustrates how the Financial Instruments Toolbox™ is used to create a Black-Derman-Toy (BDT) tree and price a portfolio of instruments using the BDT model.

Price a European Asian option using four methods in the Financial Instruments Toolbox™. This example demonstrates two closed form approximations (Levy and Kemna-Vorst), a lattice model

Hedge the interest rate risk of a portfolio using bond futures.

The bolling function in Financial Toolbox™ software produces a Bollinger band chart using all the closing prices in an IBM® stock price matrix. A Bollinger band chart plots actual data along

This script will demonstrate some simple examples related to creating, routing and managing orders from MATLAB via Bloomberg EMSX.

The Relative Strength Index (RSI) is a momentum indicator that measures an equity's price relative to itself and its past performance. The function name is rsindex. The rsindex function

This demo is an introduction to using MATLAB to develop and test a simple trading strategy using an exponential moving average.

A practical use of financial time series objects, predicting the return of a stock from a given set of data. The data is a series of closing stock prices, a series of dividend payments from the

Moving Average Convergence/Divergence (MACD) is an oscillator function used by technical analysts to spot overbought and oversold conditions. Use the IBM® stock price data contained in

Set up a basic asset allocation problem that uses mean-variance portfolio optimization to estimate efficient portfolios.

This demo uses MATLAB and the Technical Analysis (TA) Developer Toolbox to create and test a pairs trading strategy. The TA Developer toolbox complements the existing computational

In AlgoTradingDemo2.m we saw how to add two signals together to get improved results. In this demo we'll use evolutionary learning (genetic algorithm) to select our signals and the logic

Load the data and set up matrix dimensions. load and size are standard MATLAB® functions.

Creates a three-dimensional plot showing how gamma changes relative to price for a Black-Scholes option.

In AlgoTradingDemo3.m we saw how to add two signals together to get improved results using evolutionary learning. In this demo we'll use extend the approach to three signals: MA, RSI, and

This demo develops and tests a simple exponential moving average trading strategy. It encorporates obtaining data from the Bloomberg BLP datafeed and executing trades in EMSX, based on the

On-Balance Volume (OBV) relates volume to price change. The function onbalvol requires you to have the closing price (Close) series and the volume traded (Volume) series. First, create a

This demo uses our simple intraday moving average strategy to develop a trading system. Based on historical and current data, the decision engine decides whether or not to trade, and sends

Demonstrates calibrating an Ornstein-Uhlenbeck mean reverting stochastic model from historical data of natural gas prices. The model is then used to simulate the spot prices into the

This demo extends work done in AlgoTradingDemo1.m and adds an RSI technical indicator to the mix. Copyright 2010, The MathWorks, Inc. All rights reserved.

Use the basic workflow for life tables.

DISCLAIMER: THE SAMPLE FILES ENCLOSED IN THIS DOWNLOAD ARE FOR ILLUSTRATION PURPOSES ONLY. USE THE INFORMATION CONTAINED IN THIS DOWNLOAD AT YOUR OWN RISK.

This demo shows how to price a GMWB rider. Yi Wang, MathWorks, 2010

This demo shows how to profile your code to find the performance bottlenecks, or areas for improvement, as well as the capability to generate C-Code from MATLAB.

Williams %R is an indicator that measures overbought and oversold levels. The function willpctr is from the stochastics category. All the technical analysis functions can accept a

Plots gamma as a function of price and time for a portfolio of 10 Black-Scholes options.

A common workflow for using a creditCopula object for a portfolio of credit instruments.

A value-at-risk (VaR) backtesting workflow and the use of VaR backtesting tools. For a more comprehensive example of VaR backtesting, see docid:risk_ug.bvejh6e-1.

Estimate the value-at-risk (VaR) using three methods, and how to perform a VaR backtesting analysis. The three methods are:

Work with consumer (retail) credit panel data to visualize observed default rates at different levels. It also shows how to fit a model to predict probabilities of default and perform a

Explores how to simulate correlated counterparty defaults using a multifactor copula model.

Choose your country to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a location from the following list:

See all countries