American option pricing in MATLAB (Roll-Geske-Whaley)

Option pricing in MATLAB

MATLAB’s built-in finance toolbox allows one to quickly and easily calculate the price of options using a variety of models.  Here, we’ll focus on pricing a call option for Apple using the Roll-Geske-Whaley model.

Simple option problem: Apple, Inc

Calculate the price of a call option in Apple (AAPL) assuming the following parameters:

Exercise price of $600 on August 15, 2012

Expiration on December 15, 2012

Dividend of $15 on November 15, 2012

AAPL is trading at $581 today

Volatility of ~30% and risk free rate of 5% per annum.

MATLAB code

AssetPrice = 581;
Settle = ‘Aug-15-2012′;
Maturity = ‘Dec-15-2012′;
Strike = 600;
Rate = 0.05;
Sigma = 0.3;
DivAmount = 15;
DivDate = ‘Nov-15-2012′;

StockSpec = stockspec(Sigma, AssetPrice, {‘cash’}, DivAmount, DivDate);
RateSpec = intenvset(‘ValuationDate’, Settle, ‘StartDates’, Settle, ‘EndDates’, Maturity, ‘Rates’, Rate, ‘Compounding’, -1, ‘Basis’, 1);

OutSpec = {‘Price’, ‘Delta’, ‘Gamma’};

[Price, Delta, Gamma] = optstocksensbyrgw(RateSpec, StockSpec, Settle, Maturity, Strike,’OutSpec’, OutSpec)

 

Output

The output of the code gives:

Price =

31.4799
Delta =

0.4784
Gamma =

0.0043

 

so, the option would cost $31.48. Simple enough.

Adding Bollinger bands to stock charts in MATLAB

Bollinger bands

Bollinger band examples

Bollinger bands for US Steel and Sirius XM in 2011

Bollinger band code

clear; clc;
%% data to analyze
stock='siri';
start_date='2011-1-01';
end_date='2011-5-31';
wsize=20; % window size
nstd=2; % number of standard deviations to use for upper/lower bands
wts=0; % weight factor for moving average

%% download stock information
[datep, close, open, low, high, volume, closeadj] = StockQuoteQuery(stock, start_date, end_date, 'd');

%% find bollinger bands
[mid, uppr, lowr] = bollinger(close, wsize, wts, nstd);

%% make some plots
figure
plot(datep,close)
hold on;
title(['Bollinger bands - ', stock, ' - ', start_date, ' - ',end_date])
ylabel('Price ($)')
xlabel('Date')
datetick('x','mm/dd', 'keepticks')
plot(datep,uppr,'Color','k')
plot(datep,lowr,'Color','k')
plot(datep,mid,'Color','r')

 

Support and Resistance in MATLAB

Support and resistance levels

Support and resistance levels can be used to find historical trends of the turning points of a security.  The red, green and black horizontal lines represent the first, second and third support and resistance levels, respectfully.

Code example

Support and Resistance levels from MATLAB

Code to calculate support and resistance levels

Download a full copy of the code here: Download code
Read the rest of this entry »

Relative strength index (RSI) backtesting tool

Relative strength momentum algorithm

The relative strength index is calculated by

RSI=100-100/(1+RS)

where

RS=avg. gain/avg. loss

and each average is over the last n periods.

The trading strategy

This code uses the RSI index to buy when the stock is oversold and sell when the stock is overbought. Our definition of oversold here is when the RSI index has been less than 30 for two days straight and our definition of overbought is when the RSI index has exceeded 70 for two days straight. To protect profits, we use a 5% stop loss with a profit target of 3%, i.e., we close out our positions when we lose 5% or gain 3%.

Trading example

The following is an example of the code used with the default data for the stock XEL (start date: 1/1/2007, end date: 1/1/2009). The green stars are buy points and the red stars are sell points.

Backtesting RSI trading strategyRSI momentum trading strategy (index)

Code

Download a full copy of the code here: Download code
Read the rest of this entry »

Downloading daily stock data using MATLAB and Yahoo Finance

This code is based on GETSTOCKDATA by Peter Webb of Mathworks from the October 2002 MATLAB News and Notes article “Internet Enabled Data Analysis and Visualization with MATLAB”

 

Corrections and additions can be found in the comments at the beginning of the file.

 

Download the code here: StockQuoteQuery.m

 
Example:


>> [date1, close1, open1, low1, high1, volume, closeadj1] = StockQuoteQuery('siri', '2010-01-01', '2010-12-31', 'd');
Contacting YAHOO server using ...
url = java.net.URL(http://table.finance.yahoo.com/table.csv?a=0&b=1&c=2010&d=11&e=31&f=2010&s=SIRI&y=0&g=d)
Reading data for symbol SIRI...
Header Line
java.io.BufferedReader@209772b

... Finished, 252 lines of data
Converted stock data to dates, open, high, low, close, volume, close2
Dates: 04-Jan-2010 to 31-Dec-2010 252 observations
>> size(close1)

ans =

252 1
>> plot(close1)
xlabel('Day of the year')
ylabel('Price ($)')
title('SIRI - 2010-01-01 to 2010-12-31')

Read the rest of this entry »

The Financial Modelers’ Manifesto

Before using any of the models, codes or ideas presented on this site, one should take a minute to read The Financial Modelers’ Manifesto by Emanuel Derman and Paul Wilmott. Special attention should be paid to the Hippocratic Oath,

 

The Modelers’ Hippocratic Oath
~ I will remember that I didn’t make the world, and it doesn’t satisfy my equations.

~ Though I will use models boldly to estimate value, I will not be overly impressed by mathematics.

~ I will never sacrifice reality for elegance without explaining why I have done so.

~ Nor will I give the people who use my model false comfort about its accuracy. Instead, I will make explicit its assumptions and oversights.

~ I understand that my work may have enormous effects on society and the economy, many of them beyond my comprehension.

 

You can find the entire manifesto here:
The Financial Modelers’ Manifesto

 

and a discussion on the manifesto here:
Discussion of the The Financial Modelers’ Manifesto

 

The results presented on this site will be presented as purely an academic exercise and care should be taken when applying any codes or algorithms to the financial markets.