MATLAB Examples

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

Connect to Bloomberg® and retrieve current and historical Bloomberg® market data. For details about Bloomberg® connection requirements, see docid:datafeed_ug.bq4htf5. To ensure a

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.

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

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

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

Conduct the Ljung-Box Q-test for autocorrelation.

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

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.

Estimate a seasonal ARIMA model:

Use arima to specify a multiplicative seasonal ARIMA model (for monthly data) with no constant term.

Specify a composite conditional mean and variance model using arima .

Conduct a likelihood ratio test to choose the number of lags in a GARCH model.

Calculate the required inputs for conducting a Lagrange multiplier (LM) test with lmtest . The LM test compares the fit of a restricted model against an unrestricted model by testing whether

Check whether a linear time series is a unit root process in several ways. You can assess unit root nonstationarity statistically, visually, and algebraically.

Conduct Engle's ARCH test for conditional heteroscedasticity.

Estimate the parameters of a vector error-correction (VEC) model. Before estimating VEC model parameters, you must determine whether there are any cointegrating relations (see

Apply both nonseasonal and seasonal differencing using lag operator polynomial objects. The time series is monthly international airline passenger counts from 1949 to 1960.

Specify an ARIMAX model using arima .

Generate data from a known model, specify a state-space model containing unknown parameters corresponding to the data generating process, and then fit the state-space model to the data.

Specify a conditional variance model for daily Deutschmark/British pound foreign exchange rates observed from January 1984 to December 1991.

Compare two competing, conditional variance models using a likelihood ratio test.

Calculate the required inputs for conducting a Wald test with waldtest . The Wald test compares the fit of a restricted model against an unrestricted model by testing whether the restriction

Simulate responses from a regression model with nonstationary, exponential, unconditional disturbances. Assume that the predictors are white noise sequences.

In this script we will produce a number of visuals for the simulated rates when using HW model.

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.

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

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

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

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

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 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 six methods in the Financial Instruments Toolbox™. This example demonstrates four closed form approximations (Kemna-Vorst, Levy, Turnbull-Wakeman,

Consider an American call option with an exercise price of $120. The option expires on Jan 1, 2018. The stock has a volatility of 14% per annum, and the annualized continuously compounded

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

Model prepayment in MATLAB® using functionality from the Financial Instruments Toolbox™. Specifically, a variation of the Richard and Roll prepayment model is implemented using a two

Bootstrap an interest-rate curve, often referred to as a swap curve, using the IRDataCurve object. The static bootstrap method takes as inputs a cell array of market instruments (which can

Construct a Diebold Li model of the US yield curve for each month from 1990 to 2010. This example also demonstrates how to forecast future yield curves by fitting an autoregressive model to the

Use objects to model the term structure of interest rates (also referred to as the yield curve). This can be contrasted with modeling the term structure with vectors of dates and data and

Price Bermudan swaptions using interest-rate models in Financial Instruments Toolbox™. Specifically, a Hull-White one factor model, a Linear Gaussian two-factor model, and a LIBOR

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

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

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

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.

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

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

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 profile your code to find the performance bottlenecks, or areas for improvement, as well as the capability to generate C-Code from MATLAB.

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

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

We seek to try out ga and patternsearch functions of the Genetic Algorithm and Direct Search Toolbox. We consider the unconstrained mean-variance portfolio optimization problem, handled

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

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

The following sequence of examples highlights features of the Portfolio object in the Financial Toolbox™. Specifically, the examples show how to set up mean-variance portfolio

Use the setBudget function for the Portfolio class to define the limits on the sum(AssetWeight _ i ) in risky assets.

Perform portfolio optimization using the Portfolio object in Financial Toolbox™.

Analyze the characteristics of a portfolio of equities, and then compares them with the efficient frontier. This example seeks to answer the question of how much closer can you get to the

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

Illustrates implementation of the Capital Asset Pricing Model (CAPM) in the presence of missing data.

Use the basic workflow for life tables.

Use timetables to visualize and calculate weekly statistics from simulated daily stock data.

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

Construct a bond portfolio to hedge the interest-rate risk of a Treasury bond maturing in 20 years. Key rate duration enables you to determine the sensitivity of the price of a bond to

Uses Financial Toolbox™ bond pricing functions to evaluate the impact of time-to-maturity and yield variation on the price of a bond portfolio. Also, this example shows how to visualize the

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.

A common workflow for using a creditMigrationCopula object for a portfolio of counterparty credit ratings.

An expected shortfall (ES) backtesting workflow using the esbacktestbysim object. The tests supported in the esbacktestbysim object require as inputs not only the test data ( Portfolio ,

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

An expected shortfall (ES) backtesting workflow and the use of ES backtesting tools. The esbacktest class supports two tests -- unconditional normal and unconditional t -- which are based

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.

Work with consumer (retail) credit panel data to visualize observed probabilities of default (PDs) at different levels. It also shows how to fit a Cox proportional hazards (PH) model, also

Perform estimation and backtesting of Expected Shortfall models.

Calculate capital requirements and value-at-risk (VaR) for a credit sensitive portfolio of exposures using the asymptotic single risk factor (ASRF) model. This example also shows how to

Demonstrates techniques to calibrate a one-factor model for estimating portfolio credit losses using the creditDefaultCopula or creditMigrationCopula classes.

Simulate random portfolios with different distributions and compare their concentration indices. For illustration purposes, a lognormal and Weibull distribution are used. The

Compare the Merton model approach, where equity volatility is provided, to the time series approach.

Sweep through a range of values for an existing exposure from 0 to double the current value and plot the corresponding values. This could be used as one criterion (among others) for assessing

Create a connection to the IB Trader Workstation℠ and create a market order based on historical and current data for a security. You can also create orders for a different instrument, such as a

Connect to Wind Data Feed Services (WDS) and retrieve current and historical WDS data. The example then shows how to trigger a buy decision for a single security using the current high price.

Choose a web site 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 web site from the following list:

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

Contact your local office