Documente Academic
Documente Profesional
Documente Cultură
A MAT-file is a binary MATLAB file format with a .mat extension. MAT-files save only the data in the workspace, not
the commands that created them.
You can save and load MAT-files programmatically using the save and load commands.
Creates myData.mat containing current workspace save('myData.mat')
variables.
Loads variables from myData.mat into current load('myData.mat')
workspace.
Instead of saving the entire MATLAB workspace, you can selectively save individual variables.
Saves x to someFile.mat. save('someFile.mat','x')
Saves x and y to someFile.mat. save('someFile.mat','x','y')
When you save data to a MAT-file, what does the MAT- It save workspace variables
file contain?
2.7 Plots Tab
Plot(Variable) or Plot(Date, Variable)
Add plot dùng hold on and hold off
Exporting Figures
You can save, copy, and export MATLAB figures to applications such as word processors, presentation software, and
web pages.
By default, MATLAB figures are saved as FIG-files, which is a binary format specific to MATLAB. These files contain all
the information about a figure to allow you to reopen them in MATLAB.
You can also export a figure to a standard image format, such as: BMP, PNG, JPG, EPS, and more.
Clear variable Dùng để xóa cái variable ra khỏi workspace. Cái clc là dẹp
màn hình
3.4 Using Built-in Functions and Constants:
Consider the following mathematical formulas that are commonly used in quantitative finance:
Log Returns
If you want to implement these formulas, you will need to compute commonly used mathematical functions such as the
logarithm function and the exponential function. Also useful will be the mean and the standard deviation functions.
MATLAB provides built-in support for calculating these and many other mathematical functions.
p = sqrt(2)/2 Lấy căn hai/2
3.5 Vectors, Matrices, and Arrays: (1/5) Introduction
>> load stockData; When you import the stock data into MATLAB, the prices
of each individual stock are stored in a vector.
Many arithmetic operators in MATLAB behave in an Not all of the common arithmetic operators behave in an
elementwise manner, meaning that the operation is elementwise manner. For these, MATLAB contains
applied to each of the corresponding elements. additional elementwise versions of the operators.
varName = [2 8]
is the same as
varName = [2;8] vector cột
4.3 Indexing into Vectors: You can extract a single value from a vector by entering a command having the form:
(2/4) Scalar Indexing >> variableName(elementNumber)
Here, elementNumber refers to the position of the element in the vector and is
commonly referred as the index. Note that in MATLAB, the index always starts from
1.
For example, v(4) extracts the fourth element of the vector v.
last = BARC(end)
Có mấy cái cơ bản mà hay secondToLast = BARC(end-1)
nhầm You can directly use a vector containing element numbers as an index without storing
it first in another variable.
>> result = v([1 3 4]);
result contains the first, third and fourth elements of v.
BARCsubset2 = BARC([end-2 end-1 end])
4.4 Creating Evenly-Spaced Vectors: (1/9) Introduction
Creating Evenly-Spaced Vectors
Suppose you want to extract the FTSE values for the first 22 days. You can create an index by typing all the numbers
from 1 through 22.
>> idx = [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22];
Creating a vector like this could be tedious. In this lesson, you will learn to create vectors containing evenly spaced
elements using the colon operator and the function linspace.
>> x = a:dx:b
>> x = linspace(a,b,n)
A nice feature of linspace is that it guarantees the resulting vector will contain both the start and end point specified.
Some examples:
If the number of elements is omitted, linspace defaults to creating a vector with 100 elements.
Note that both the colon operator and linspace create row vectors.
Now, if you enter the command for creating the area plot area(cumsum(BARCReurns))
of the cumulative returns, the histogram is overwritten
with the area plot.
How can you create two separate axes containing these >> histogram(BARCReturns)
two plots? >> figure
>> area(cumsum(BARCReturns))
4.7 Creating Multiple Figures and Axes: (4/5) Multiple Axes
Multiple Axes
You can create multiple axes within a single window using the subplot function.
The char function converts a number to a string according title(['Barclays Stock Prices in ' char(163)])
to the Unicode decimal value.
>> char(8364) In here, only a variable pound is out of the
ans = bracket.
€
Here is a list of commonly used special symbols.
MATLAB text annotation functions also support basic TeX title('Volatility (\sigma) is 0.02')
markup interpretation. You can create markup characters
using the backslash followed by the name of the character.
>> xlabel('\beta')
will create the xlabel string: β
The command The correct approach is to:
1. Convert the numbers stored in var into a string using
title('Value at risk = var') the function num2str.
num2str(var)
does not recognize that 'var' is also a name of the variable.
2. Use the resulting string in the title by concatenating it
with the rest of the title string.
title(['Value at risk = ' num2str(var)])
4.11 Creating Arrays of Text: (1/2) Introduction
Creating Arrays of Text
When analyzing or visualizing textual data, you might need
to create a variable containing several separate words. In
such cases, it is useful and sometimes necessary to store
these words distinctly instead of combining them in a
single vector. You can do this using a new data type called
a cell array.
extracts the value in the jth row and kth column of A and assigns it to
the variable x.
x = b(4,[2 3]) y = b([3 4],[2 3])
z=b(1:5,2)
Instead of using
>> output = M(1:9,2)
you can use a more convenient syntax:
>> output = M(:,2)
Nov6 = prices(10,:);
Tóm lại
Arithmetic Operators
minReturnRows = min(returns,[],2);
5.7 Array Creation Functions: (1/4) Introduction
Array Creation Functions
Suppose that you want to estimate the future stock prices of BAE Systems (ticker BA) assuming that the prices follow
geometric Brownian motion (GBM).
S(t)Stock Price at time t
μMean return
σVolatility (standard deviation)
εNormally distributed random variable
epsilon = randn(22,1);
TASK
Using the variables mu, sigma, deltaT, and epsilon calculate the factors = exp((mu-sigma^2/2)*deltaT +
highlighted part of the above formula and store the result in factors. sigma*epsilon*sqrt(deltaT));
In the previous tasks, you created a vector of random numbers and TASK
calculated the factors based on that vector. Create a matrix of normally distributed
random numbers of size 22-by-100 and
To predict multiple paths of the stock price, you can start by creating a store the result in epsilon2.
matrix of random numbers. epsilon2 = randn(22,100);
You can compute the factors TASK
(highlighted below) using the Using the variables mu, sigma, deltaT, and epsilon2 calculate the highlighted part
matrix of random numbers as ε. of the above formula and store the result in factors2 (Run the command from Task
2 again with epsilon2 replacing epsilon).
factors2 = exp((mu-sigma^2/2)*deltaT +
sigma*epsilon2*sqrt(deltaT));
5.8 Manually Creating and Concatenating Arrays: (2/9) Create and Concatenate Arrays
5.8 Manually Creating and Concatenating Arrays: (8/9) Predict Future Price Path
The code in the command window calculates the TASK
highlighted portion of the formula. To predict the future values of the stock price, first extract
the price of BA on the last trading day and store the result in
S0.
One way to create a new blank script is to use the You can also provide the filename as a part of the edit
command edit. command.
creates a blank script named untitled.m. creates a blank script named fileName.m.
TASK load stockData
Enter the following commands in the script stock = BA;
futurePrices.m. (You can copy and paste these commands stockReturns = diff(log(stock));
mu = mean(stockReturns);
as well.) sigma = std(stockReturns);
deltaT = 1;
S0 = stock(end);
epsilon = randn(22,100);
factors = exp((mu-sigma^2/2)*deltaT +
sigma*epsilon*sqrt(deltaT));
lastPriceVector = ones(1,100)*S0;
factors2 = [lastPriceVector;factors];
paths = cumprod(factors2);
plot(paths)
6.2 Create and Run a Script: (4/6) Run Script from Command Line
TASK
Run the script futurePrices.m from the Command Window.
futurePrices
run futurePrices.m
One advantage of working with scripts is that it is easy to load stockData
change a variable and run the sequence of commands stock = BA;
again. Modify the script such that path contains 200 stockReturns = diff(log(stock));
mu = mean(stockReturns);
possible future paths instead of 100. sigma = std(stockReturns);
deltaT = 1;
S0 = stock(end);
epsilon = randn(22,200);
factors = exp((mu-sigma^2/2)*deltaT +
sigma*epsilon*sqrt(deltaT));
lastPriceVector = ones(1,200)*S0;
factors2 = [lastPriceVector;factors];
paths = cumprod(factors2);
plot(paths)
6.3 Comments: (1/3) Introduction
6.4 Code Sections: (1/3) Adding Code Sections
6.5 Publishing Code: (2/4) Publishing Options
Publishing Options
You can output the published results to any of several formats, including HTML, XML, TEX, and PDF.
To specify the published format, follow the steps below.
Click Publish → Edit Publishing Options...
In the Edit Configurations window, specify the output
format. You can also set other preferences, such as
whether to include or exclude the code from the output.
To control how a particular sentence or comment appears, you can use the markup controls on the Publish tab. These
controls help you to insert markup symbols in the file's comments. These markup symbols allow you to specify
numbered lists, format equations in TEX, and insert hyperlinks and images.
One way to calculate the value at risk is to simulate the future prices using the Monte-Carlo simulation and report the
VaR as an expected loss in terms of percentage returns.
The first step, then, is to simulate the future prices and calculate the returns over the desired time horizon.
Plot a histogram of the possible returns with 20 bins.
The script shown simulates the closing prices of the BAE % Load data and identify the stock of
Systems stock for 22 days after the last recorded price. interest load stockData
Each possible path is stored in an individual column of the stock = BA;
paths matrix.
In the script, extract the simulated final prices of the BAE % Calculate the daily log returns and the
Systems (from the variable paths) stock and store them in statistics
finalPrices. stockReturns = diff(log(stock));
Task 1 mu = mean(stockReturns);
sigma = std(stockReturns);
Using these prices, calculate the log returns of each path
% Simulate prices for 22 days in future
over the 22 days by subtracting the log of the initial price
based on GBM
(S0) from the log of the final prices. Store the returns deltaT = 1;
vector in possibleReturns. S0 = stock(end);
finalPrices = paths(end,:); epsilon = randn(22,200);
possibleReturns = log(finalPrices) - factors = exp((mu-sigma^2/2)*deltaT +
log(S0); sigma*epsilon*sqrt(deltaT));
histogram(possibleReturns,20); lastPriceVector = ones(1,200)*S0;
factors2 = [lastPriceVector;factors];
Task 2 paths = cumprod(factors2);
Calculate the 5% VaR using the possibleReturns and the Task 2
function prctile. Store the result in var5. var5 = prctile(possibleReturns,5);
Visualize the VaR by plotting a red colored line on top of hold on
the histogram as shown below: plot([var5 var5],[0 40],'r')
hold off
Specify the InputFormat option to correctly interpret >> t = datetime('21 Oct 2005','InputFormat','dd
the date. MMM yyyy')
t =
21-Oct-2005
See the documentation for the datetime function for a list of all the available identifiers (e.g. dd, QQ, MMM) used to
specify the date format. Datetime create a datetime variable
The first three inputs represent, in order, the year, >> t = datetime(2005,10,21)
month, and day. t =
21-Oct-2005
The optional fourth through sixth inputs represent, in >> t = datetime(2005,10,21,17,10,0)
order, the hour, minute, and second t =
21-Oct-2005 17:10:00
7.2 Creating Dates and Times: (3/6) Creating Datetime Variables I
In the InputFormat, months are identified as MM whereas minutes are identified as mm.
TASK d = datetime('2015-09-30', 'InputFormat',
Convert the string '2015-09-30' to a datetime d,
'yyyy-MM-dd')
specifying the InputFormat option to the datetime
function.
Convert the string 'July 14 2015' to a datetime d, d = datetime('July 14 2015', 'InputFormat',
specifying the InputFormat option to the datetime
'MMMM dd yyyy')
function.
Use braces ({}) to create a 1-by-2 cell array of strings s s = {'Q1 2015', 'Q2 2015'}
containing the strings 'Q1 2015' and 'Q2 2015'. s = ({'Q1 2015', 'Q2 2015'})
Convert the cell array of strings s to a datetime d, d = datetime(s, 'InputFormat', 'QQ yyyy')
specifying the InputFormat option to the datetime
function.
7.2 Creating Dates and Times: (4/6) Creating Datetime Variables II
Creating Datetime Variables II
To create vectors and matrices of type datetime, you can specify array inputs to the datetime function.
Specify a 1-by-3 vector of years as the first input to the >> t = datetime([2001, 2003, 2006], 8, 17)
datetime function. t =
17-Aug-2001 17-Aug-2003 17-Aug-2006
Specify a 5-by-1 vector of months as the second input >> t = datetime(2007, [2;3;7;10;12], 1)
to the datetime function. t =
01-Feb-2007
01-Mar-2007
01-Jul-2007
01-Oct-2007
01-Dec-2007
As well as providing vector or matrix inputs to the datetime function, you can also create an array of dates using the
range operator (:) or the linspace function.
Create start and end dates using the datetime >> t1 = datetime(2005,10,21);
function. >> t2 = datetime(2008,6,23);
Create a daily vector. >> t = t1:t2
t = 21-Oct-2005 ... 22-Jun-2008 23-Jun-2008
Create a weekly vector >> t = t1:7:t2
t = 21-Oct-2005 ... 13-Jun-2008 20-Jun-2008
Create a vector of type datetime by specifying an array >> t = datetime(2001:2005, 5, 2)
input. t = 02-May-2001 ... 02-May-2004 02-May-2005
Create a vector of type datetime using the linspace >> t1 = datetime(2015, 1, 1);
function. >> t2 = datetime(2015, 1, 5);
>> t = linspace(t1, t2, 3)
t = 01-Jan-2015 03-Jan-2015 05-Jan-2015
Create a 3-by-1 column vector named d of type Create a 1-by-4 row vector named d of type
datetime as shown below. datetime representing the dates January 1st-4th,
01-Feb-1999 1975.
01-Feb-2000 d = datetime(1975, 1, 1:4)
01-Feb-2001
d = datetime([1999;2000;2001],2,1)
Show the date format of the variable. >> t.Format % Dot notation
ans =
You can also use the dot notation with assignment (=) dd-MMM-yyy
in order to change the date format:
Change the format of the variable. >> t.Format = 'dd/MMM/yy'
t=
21/Oct/05
Change the format again. >> t.Format = 'eee MM yyyy G'
t=
Fri 10 2005 CE
You can also set the Format property directly when >> y = datetime(2008,11,22,'Format','eee MMM dd
you create the variable. yy')
y =
Sat Nov 22 08
Create a datetime d representing the date January d = datetime(1989, 1, 11, 'Format', 'yyyy-MMM-
11th 1989 using the format yyyy-MMM-dd. dd')
Create a string variable s containing the date format of s = d.Format;
the variable d. s = ‘yyyy-MMM-dd’
Change the date format of d to MM/dd/yyyy. d.Format = 'MM/dd/yyyy';
7.4 Creating Duration Variables: (1/4) Introduction
Creating Duration Variables >> t = duration(6, 15, 30)
t =
You have seen how to create datetime variables, which represent points in time. 06:15:30
In many financial applications, you also need to represent durations of time (for
example, the difference between two dates). Time durations can either be of
fixed length (for example, seconds) or variable length (for example, calendar
months). In this lesson you will learn how to create duration variables, which are
used to represent fixed-length time durations.
The duration data type represents an elapsed time, such as 7 hours, 14 minutes, 42.3 seconds, without reference to a
specific date. Fixed lengths are used for all time units (1 day = 24 hours, 1 year = 365.2425 days).
This is in contrast to variables of type calendar duration, which will be discussed in the next section. Calendar
durations do not necessarily have a fixed length (for example, a calendar month may contain 28, 29, 30 or 31 fixed-
length days).
You can create durations directly by specifying the individual time duration components. Similar to datetimes,
durations also have a Format property that controls the display of the variable.
The three inputs represent, in order, the number of >> t = duration(12,0,2)
hours, minutes, and seconds. t =
12:00:02
The fourth input is optional and represents >> t = duration(12,0,2,500);
milliseconds. >> t.Format = 'mm:hh:ss.SSS'
t =
12:00:02.500
You can make arrays of duration variables by specifying vector or matrix input arguments.
Create a duration array with different hour values. >> t = duration([23;24;25],15,0)
t =
23:15:00
24:15:00
25:15:00
You can also create duration variables from a single unit, such as years or days, using the functions listed below.
Years : Create a duration array equivalent to the number of years specified by the values in the input array.
Note: One year is equivalent to 365.2425 days.
days: Create a duration array equivalent to the number of days specified by the input.
Hours: Create a duration array equivalent to the number of hours specified by the input.
Minutes: Create a duration array equivalent to the number of minutes specified by the input.
Seconds : Create a duration array equivalent to the number of seconds specified by the input.
Create a duration representing a fixed number of >> t = hours(5)
hours. t =
5 hrs
Create a duration representing 70 minutes in two >> t1 = minutes(70)
equivalent ways. t1 =
70 mins
>> t2 = hours(1) + minutes(10);
>> t2.Format = 'm'
t2 =
70 mins
Use the minutes function to create a 1-by-7 equally- t = minutes(0:10:60)
spaced duration vector t starting at 0 minutes and
finishing at 1 hour.
7.5 Creating Calendar Duration Variables: (1/5) Introduction
Creating Calendar Duration Variables
You have seen how to create datetimes, which represent points in time. In many financial
applications, you also need to represent durations of time (for example, the difference between
two dates). Time durations can either be of fixed length (for example, seconds) or variable
length (for example, calendar months). In this lesson you will learn how to create
calendarDuration variables, which are used to represent calendar time durations, which may have
variable length.
>> t = calendarDuration(1, 10, 15)
t =
1y 10mo 15d
Variables of data type calendar duration represent an elapsed time in calendar units, such as 3
years, 1 month and 4 days, without reference to a specific date. Importantly, the value of a
calendar time unit can change with context (for example, a calendar duration with a value of one
month would correspond to 30 days in April and 31 days in December.)
You can create calendarDuration variables directly by specifying the time components:
The first three inputs represent, in order, the year, >> t = calendarDuration(1,2,3)
month, and day. t =
1y 2mo 3d
The optional fourth through sixth inputs represent, in t = calendarDuration(1,2,3,4,5,6)
order, the hour, minute, and second. t =
1y 2mo 3d 4h 5m 6s
You can make arrays of calendarDuration variables:
Create a calendarDuration array with multiple values >> t = calendarDuration(3:5,1,4:6)
using the colon, :, operator. t =
3y 1mo 4d 4y 1mo 5d 5y 1mo 6d
You can also create calendarDuration variables from a single unit, such as months or weeks,
using the functions listed below.
calyears Create an array of calendar years as specified by the values in the input
array.
calquarters Create an array of calendar quarters as specified by the values in the input
array.
calmonths Create an array of calendar months as specified by the values in the input
array.
Create a 3-by-1 equally- t = calendarDuration([2;4;6], 6, 2)
spaced calendarDurationvector t as shown below.
2y 6mo 2d
4y 6mo 2d
6y 6mo 2d
Use the calyears function to create a 1-by-3 equally- t = calyears(1:3)
spaced calendarDuration vector t starting at 1
calendar year and finishing at 3 calendar years.
Use the calquarters function to create a 1-by-8 t = calquarters(1:8)
equally-spaced calendarDuration vector t starting at 1
calendar quarter and finishing at 2 calendar years.
Use the calyears, calmonths and caldays functions to t = calyears(4)+ calmonths(10) + caldays(27)
create a calendar duration t representing 4 calendar
years, 10 months and 27 days.
Summary of Date and Time Datatypes
You have now worked with all three date and time datatypes in MATLAB. These data types are
summarized in the table below.
Datetime Represent specific dates or points in time
duration Represent a fixed-length time duration
calendarDuration Represent a variable-length duration in calendar units
7.6 Datafeed Connections: (1/4) Introduction
Datafeed Connections
With MATLAB and Datafeed Toolbox™, you can download data from an external service provider such
as Bloomberg® or FRED®. The data is imported directly into the MATLAB Workspace without the need
for intermediate storage in spreadsheets, databases or text files. You can also use datafeed
connections to create real-time applications with automatic updates.
>> c = fred
c =
fred with properties:
url: 'https://fred.stlouisfed.org'
ip: []
port: []
Datafeed Basics
Datafeed providers supported for use with MATLAB and Datafeed Toolbox are shown in the table
below. You can find more information about supported service providers in the Datafeed Toolbox
documentation. Click on the connection functions below to explore their documentation.
url: 'https://fred.stlouisfed.org'
ip: []
port: []
Next, use the appropriate retrieval function to request data from the server. For FRED, you use
the fetch function. For other providers, refer to the documentation.
>> d = fetch(Connection,Security,StartDate,EndDate)
A retrieval function requires at least two inputs:
a connection and a character variable representing a security to look up. You can provide
further inputs to specify the type of data to return and, if supported, the required periodicity
of the data (e.g., weekly).
Request the >> tStart = datetime(2014,1,2);
U.S./Euro foreign >> tEnd = datetime(2014,6,30);
exchange rate over a >> d = fetch(c,'DEXUSEU',tStart,tEnd);
d =
6-month period from Title: 'U.S. / Euro Foreign Exchange Rate'
January 2nd 2014 to SeriesID: 'DEXUSEU'
June 30th 2014. Source: 'Board of Governors of the Fede...'
Release: 'H.10 Foreign Exchange Rates'
SeasonalAdjustment: 'Not Seasonally Adjusted'
Frequency: 'Daily'
Units: 'U.S. Dollars to One Euro'
DateRange: '1999-01-04 to 2018-04-20'
LastUpdated: '2018-04-23 3:51 PM CDT'
Notes: 'Noon buying rates in New York ...'
Data: [128×2 double]
You can access the >> data = d.Data
information in the data =
structure using dot 735601 1.3670
...
notation. 735780 1.3690
Finally, it is good practice to close the server connection and clear the connection variable
from the workspace.
Close the connection >> close(c)
and tidy up. >> clear c
7.7 Converting Datafeed Dates to Datetime Variables: (1/3) Introduction
Converting Datafeed Dates to Datetime Variables
When importing data from a datafeed service
provider, the dates are imported together with the
data in a numeric matrix. In particular, the dates (in
the first column) have a numeric serial number
representation, which is different from the datetime
format.
Call the intersect function with one output c to [c, idx1] = intersect(d1, d2)
determine the dates common to d1 and d2.
Call the intersect function with three outputs, c, idx1 [c, idx1, idx2] = intersect(d1, d2)
and idx2, to determine the indices of the dates in d2
present in the intersection.
Merging Distinct Data Sets
If you have two data sets with dates in common, you can merge them by extracting only the
observations corresponding to the common dates, and then concatenating the results. The code
below demonstrates this process, using two data sets downloaded from a datafeed.
Display data for the DJIA and NIKKEI225 indices.
Convert the dates to the datetime format. >> djiaDates = datetime(djiaData(:, 1), ...
'ConvertFrom', 'datenum');
>> nikkeiDates = datetime(nikkeiData(:, 1), ...
'ConvertFrom', 'datenum');
Notice that the two time series have different lengths. >> size(djiaDates)
ans =
5 1
>> size(nikkeiDates)
ans =
6 1
Determine the common dates. >> [commonDates, idxDJIA, idxNIKKEI] = ...
intersect(djiaDates,
nikkeiDates);
Extract the data corresponding to the common dates. >> commonDJIA = djiaData(idxDJIA, 2);
Notice that the series now have the same length. >> commonNIKKEI = nikkeiData(idxNIKKEI, 2);
>> size(commonDJIA)
ans =
4 1
>> size(commonNIKKEI)
ans =
4 1
Concatenate the results to produce a matrix of >> commonData = [commonDJIA, commonNIKKEI];
common data.
TASK [commonDates,idxDAX,idxSP500] =
Call the intersect function with three outputs
commonDates, idxDAX and idxSP500 to determine the intersect(daxDates,sp500Dates); n
dates common to the two time series daxDates and
sp500Dates.
TASK commonDAX = daxData(idxDAX,2);
Extract the data for the DAX series, found in the
second column of daxData, on the common dates
whose indices are given in idxDAX to create the
variable commonDAX.
TASK
Extract the data for the SP500 series, found in the
second column of sp500Data, on the common dates
whose indices are given in idxSP500 to create the
variable commonSP500.