Sunteți pe pagina 1din 24

2.

6 Save and Load data


Workspace Variables
You can save variables in the current workspace to disk in a MAT-file. MAT-files provide a quick and easy way to save
and load data for use in MATLAB.

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.

3. Variables and Commands


3.1 Course Example - Explore Stock Prices Data with Commands
3.2 Entering Commands:
Format long Dùng để format number

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

Geometric Brownian Motion

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.

MATLAB performs scalar expansion when performing


arithmetic operations containing scalars

3.7 Using Mathematical Functions on Vectors: (1/3) Introduction


Using Mathematical Functions on Vectors

To calculate the daily log returns, we need to find the


difference between the log of the prices at two
successive time instants. We can use the function diff
which calculates differences between adjacent elements
of the input. bằng với
3.8 Obtaining Help: (1/4) Finding the Function's Documentation
Highlight the name of the function Ví dụ: Uniformly distributed pseudorandom integers là
Hoặc dùng câu lệnh doc + tên của function . hàm randi
Tạo một matrix 5 row, 7 cột chạy từ 1 – 20 x = randi(20,5,7)
Tick2ret Convert price series to return series
[Returns,Intervals] = tick2ret(Data) [Returns,Intervals] = tick2ret(Data) computes
[Returns,Intervals] = tick2ret(___,Name,Value) asset returns for NUMOBS price observations
of NASSETSassets.
[Returns,Intervals] =
tick2ret(___,Name,Value) adds optional name-value
pair arguments.
logReturns = tick2ret(BARC,[],'continuous'); Compute the log returns of BARC using the
function tick2ret.

Notice from the documentation that the second


input tickTimes is optional. Since the observation times
are not available, you should specify the third input without
specifying the second input.

To do this, you can provide empty array [] as the second


input.
Store the result in logReturns.
3.9 Plotting Vectors: (1/8) Introduction
3.9 Plotting Vectors: (4/8) Plot Cumulative Returns
load stockPrices.mat
L = log(BARC);
logReturns = diff(L);
cumReturns = cumsum(logReturns);

3.10 Modifying Plot Colors and Markers: (1/7) Introduction


Plot options
The plot function accepts an optional third argument that allows you to specify the line style, line color, and marker
style.
Plot red line with triangular markers
>> plot(x,y,'r-^')

The codes can be combined in any order.


plot(x,y,'k:o') plot(x,y,'ok:') plot(x,y,':ko')
All commands plot a black dotted line with circular
markers.

3.11 Creating Character Arrays: (1/5) Introduction


Creating Character Arrays
In many situations, you will need to use words or phrases in MATLAB commands. These are often referred as strings
or character arrays.
>> plot(x,y,'-b*')
The line specification is a string.
>> title('FTSE Index')
The title is a string.
This lesson focuses on creating character arrays.
3.11 Creating Character Arrays: (2/5) Character Arrays
MATLAB is not a function or variable name >> a = MATLAB;
Undefined function or
variable 'MATLAB'.
To specify characters as literal text, enclose them in single quotation marks.
Using single quotes causes MATLAB to produce character arrays, where each element of the array is an individual
letter of the word or phrase.
Because the arrays contain character data, they are of type char, not double.

a is a 1-by-6 character array >> a = 'MATLAB';


'M' 'A' 'T' 'L' 'A' 'B'
>> b = 'Hello';
b is a 1-by-5 character array
'H' 'e' 'l' 'l' 'o'
Call the load function and pass it a character array load('info.mat')
containing the letters info.mat.
3.12 Annotating Plots: (1/6) Introduction
Annotating Plots
You can add labels and a title to the plot to make it more understandable. This lesson focuses on adding annotations
to the plots.
>> title('Natural logarithm')
>> xlabel('t')
>> ylabel('y')
>> legend('y = ln(t)')

4.1 Course Example - Analyze and Visualize Stock Returns Vectors

4.2 Manually Entering >> varName = [2 8]


Vectors: (2/4) Creating varName =
Vectors 2 8 vector dòng
When creating vectors, commas behave the same as spaces.

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

Creates a vector that starts at 1, ends at 7, and elements >> x = 1:2:7


are separated by 2. x=
1 3 5 7
Creates a vector that starts at -4, ends at 8, and elements >> x = -4:3:8
are separated by 3. x=
-4 -1 2 5 8
To create a vector with spacing 1, you can omit the spacing >> x = 1:4
value in the syntax. MATLAB will use a default spacing of 1. x =
1 2 3 4
4.4 Creating Evenly-Spaced Vectors: (6/9) Indexing with Vectors
You can use the vector created using the colon operator as an index.
>> result = v(2:6);
The variable result contains elements 2 through 6 of the vector v.
4.4 Creating Evenly-Spaced Vectors: (7/9) Linspace
In some cases, when creating an evenly-spaced vector, you may know the number of elements you want the vector to
contain, and not the spacing between the elements. In these cases, you can use 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.

Creates a vector that starts at 1, ends at 7, and contains 5 >> x = linspace(1,7,5)


elements. x=
1.0000 2.5000 4.0000 5.5000 7.0000
Creates a vector that starts at -pi, ends at pi, and contains >> x = linspace(-pi,pi,4)
4 elements. x=
-3.1416 -1.0472 1.0472 3.1416
4.5 Calculating Statistics of Vectors: (1/4) Introduction
Statistical functions: MATLAB contains many functions that you can use to calculate statistics of vectors. Some of the
most common include
Use the min function to find the index of the minimum >> v = [31;12;8;29;36];
FTSE value. Store the result in a variable named idx. >> [m,idx] = min(v)
m=
8
idx =
3
Use the index of the minimum value idx to extract the date minFTSEDate = t(idx);
on which the FTSE value was minimum. Dates are stored in
a vector named t. Store the result in a variable named
minFTSEDate.
4.6 Identifying Available Vector Plot Types: (1/4) Introduction
Identifying Available Vector Plot Types
When exploring the stock data for determining
performance and key indicators, it is helpful to visualize the
data in different ways. You might want to use a bar chart to
visualize the stock prices or a histogram to visualize the log
returns.
Additional Vector Plot Types
MATLAB has many specialized plotting commands to allow you to visualize and present your data with the emphasis
on the data features you find important.

4.7 Creating Multiple Figures and Axes: (1/5) Introduction


Creating Multiple Figures and Axes
Suppose you want to visualize the returns and the cumulative returns of Barclays. You can create two separate figures
or two separate axes for visualizing the returns and cumulative returns.
You can start by creating the histogram of the returns. >> histogram(BARCReurns)

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.

subplot Creates or activate a set of axes at the location


specified by the user.

subplot(m,n,k) creates an active set of axes at the kth


position in an m-by-n grid (that is, m rows and n columns).
If axes already exist in this location, they are made active.
The axes in the grid are numbered sequentially left-to-
right, then top-to-bottom.
For example, a commonly used pattern is a figure with two
sets of axes.
To reset a window to a single set of axes, enter
subplot(1,1,1)

You can “merge” axes by specifying a vector of numbers as


input for the row or column numbers. MATLAB will create
a subplot which is the smallest possible rectangle that
contains the elements specified in the input vector.
>> subplot(3,3,[2 6])

4.8 Adding Plots: (1/5) Introduction


Adding Plots
You can make the visualizations more informative by
overlaying plots of different types or by plotting multiple
data sets together.

The function prctile(v,p) calculates the pth percentile of var = prctile(BARCReturns,5);


the values in the vector v.
To plot a vertical line, you can specify the x and y TASK
coordinates of the two ends of the line. Plot a vertical line at an x-coordinate that is equal to var.
For example, You can use the current y-axis limits as the y-
>> plot([2 2],[0 30]) coordinates of the end points of the line.
plots a vertical line at x = 2. plot([var var],[0 90])
4.9 Customizing Plot Properties: (1/5) Introduction
Customizing Plot Properties
Customizing the visualizations can not only make them more aesthetically appealing but also more informative and
user friendly. For example, in the following graph, the highlighting of the FTSE cumulative returns makes it easier to
compare the other stocks against the index.
Create a line width =3 plot(FTSELastMonth,'LineWidth',3)
Plot FTSELastMonth again with circular markers, solid line, plot(FTSELastMonth,'-
LineWidth set to 3, and MarkerEdgeColor set to [0.8 0.1
o','LineWidth',3,'MarkerEdgeColor',[0.8 0.1
0.2].
0.2])

In trying to create an overlay of the histograms of the histogram(GSKRetns,40,'EdgeColor','none')


returns of BA and GSK, the following commands were
tried.
>> histogram(BARetns,40)
>> hold on
>> histogram(GSKRetns,40)

4.10 Advanced Annotation Techniques: (1/4) Introduction


Advanced Annotation Techniques
You can make the annotations more informative by including special characters such as £ or σ. You can also include
numeric information calculated programmatically in the annotations.

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.

Such a cell array is useful for annotating graphs such as a


pie chart. Suppose the distributions of various assets in a
portfolio is given by the vector d. You can create a pie chart
as follows:
4.11 Creating Arrays of Text: (2/2) Annotate Using Cell pie(d,assetNames)
Arrays
4.12 Project - Working with Vectors
You can use the MATLAB function amortize to calculate [P,I,B] =
the amortization schedule.
amortize(monthlyRate,numPeriods,presentValu
Look up the documentation to see how it is used.
TASK e);
Use the amortize function with three inputs and three
outputs to capture the vectors of principle paid, interest
paid, and balance at the end of each period. Store them in
variables P, I, and B respectively.

Do not use the inputs FutureValue and Due.


The vector I contains the interest that will paid each I2total = sum(I(1:24));
month.
TASK
Calculate the total interest that will be paid in the first 2
years. Store the result in I2total.

5. Working with Matrices


Use matrices as mathematical objects or as containers for multiple vectors. Perform various mathematical operations
on matrices. Query and combine multiple matrices.
5.2 Programmatically Importing Data Using xlsread: (1/2) Introduction You can automate the data import from an
Excel file using the function xlsread.
Using xlsread >> [num,txt] = xlsread(filename,sheet)
You can use the function xlsread to import data from an Excel file.

Indexing into Arrays


A matrix is a good way to store aggregate numeric data. For example, the following matrix stockPrices stores the stock
prices of several companies.
Row, Column Indexing (Single Element) Row, Column Indexing (Multiple Elements)
Every element of a matrix can be identified by a combination of a row How can you extract multiple elements from
and a column number. a matrix?
Note that in MATLAB, the first row or column is identified by the Step 1 - Identify the row numbers of the
number 1 and not 0. elements to be extracted.
Step 2 - Identify the column numbers of the
You can extract one or more elements from a matrix using the elements to be extracted.
following syntax. Step 3 - Use the row and column numbers in
output = variableName(rowNumbers, columnNumbers) the command of the form:
Thus, the syntax output =
varName(rowNumbers,colNumbers)
>> x = A(j,k)

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

Extract a single element


output = M(2,3)
Extract multiple elements
output = M(2,[3 4])
Extract multiple contiguous elements
output = M(2,2:4)
Extract complete rows or columns
output = M(2,:)
5.4 Performing Matrix Operations: (1/7) Introduction
Elementwise Matrix Operations
There are many operators that behave in element-wise manner, i.e.,
the operation is performed on each element of the matrix individually.

Arithmetic Operators

Note that, for performing the arithmetic operations on two matrices,


they should have the identical dimensions.
Scalar Expansion
The command x^2 is the same as x*x when x is a square matrix. If you
want to take the square of each element of the matrix, use x.^2
instead.
5.5 Using Statistical Operations on Matrices: (1/4) Introduction
Find the average return of all the stocks on each trading day (compute avgDailyReturn = mean(returns,2);
the average row-wise) and store the resulting vector in
avgDailyReturn.
If you want to use the min function to find the miminum of each row, TASK
the syntax is slightly different from the other statistical functions. Find the minimum return for each of the
trading days (i.e., the minimum value in
Use the following syntax to find the minimum value in each row: each row). Store the resulting vector in
>> minRow = min(M,[],2) minReturnRows

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

You can create ε by picking a number randomly from a standard


S(t) 491.6
normal distribution using the function randn.
μ 0.00056
Using this random number in the above formula, you can predict the σ 0.0167
future stock prices.
ε 0.3852

Array Creation Functions


MATLAB has a large number
of array creation functions
that output arrays with
certain characteristics and
avoid time consuming
manual data entry.
Remember that x = ones(7,2) is to create a matrix 7x2 but x=ones(7 2)
is pick a value at row 7th and column 2nd.
The goal of this exercise is to find the highlighted part of the following As a first step, create a vector of normally
formula, which models geometric Brownian motion (GBM): distributed random numbers of size 22-by-1
and store the result in epsilon.

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

Horizontally Concatenate - Use comma (,) or space ( ) >> v = [4 15]


v=
4 15
Vertically Concatenate - Use semi-colon (;) >> v = [4;15]
v=
4
15
Each element in a row is horizontally concatenated. >> m = [4 15; 6 19]
Each row is vertically concatenated. m=
4 15
6 19
Concatenating Arrays
Using the syntax shown above, you can also
concatenate arrays. Suppose you have two matrices
named m1 and m2.
Horizontally Concatenate - Use comma (,) or space ( ) Vertically Concatenate - Use semi-colon (;)
>> m3 = [m1 m2] >> m3 = [m1;m2]
m3 = m3 =
8 10 2 9 8 10
3 0 13 4 3 0
4 9 21 7 4 9
2 9
13 4
21 7

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.

Now, concatenate S0 and factors vertically. Store the factors2 = [S0;factors]


result in factors2
TASK path = cumprod(factors2);
Now, use the function cumprod with factors2 as the
input to compute the prices at future times. Store the
result in path.
TASK plot(path)
Plot path to see the predicted prices BAE Systems.
(Use plot with only 1 input)
5.8 Manually Creating and Concatenating Arrays: (9/9) Predict Future Prices Paths
Using the GBM formula, you can predict multiple Create a row vector of size 1-by-100 such that each element
paths of the future stock prices of BA. of the vector has the value equal to the last recorded stock
price S0. Store the result in lastPriceVector.
The code in the command window creates a matrix of lastPriceVector = ones(1,100)*S0;
random numbers and calculates the highlighted part
of the formula.
TASK factors2 = [lastPriceVector;factors];
Now, concatenate lastPriceVector and factors
vertically. Store the result in factors2
Now, use the function cumprod with factors2 as the paths = cumprod(factors2);
input to compute the prices at future time instants.
Store the result in paths.
Suppose you want to create the following plot. In this
plot, the future prices are plotted along with the First plot(BA);
historical data.
Enter hold on so that subsequent plots are added on the
current axes.
Hold on
plot(300:322,paths)

You can zoom in programmatically by changing the axis


limits.
xlim([1 100])
changes the lower limit of the x-axis to 1 and the upper limit
to 100.
xlim([275 330])

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.

>> edit >> edit fileName

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

7. Dates and Times


Import date and time data interactively. Create and modify variables representing dates and times. Perform
computations on date and time data. Create custom plots using date and time durations.
7.2 Creating Dates and Times: (1/6) Introduction
Creating Dates and Times
Many financial applications involve date and time-based computations. To perform these efficiently and
unambiguously, you can create special variables to represent dates and times. In this lesson, you will learn how to use
the datetime data type to create date and time variables.

>> d = datetime(1999, 12, 31)


d=
31-Dec-1999
Creating Datetime Variables I
You can import dates as datetime variables directly
using the Import Tool. Use the target type menu to
change the data type that will be used when a given
column is imported. For columns containing date and
time data, select the "Datetime" option from the
menu. After importing, the data in these columns will
be stored in MATLAB datetime variables in the
Workspace.
You can also create datetimes from strings or cell Create a datetime from a string representing the date.
arrays of strings representing dates. If successful, the >> t = datetime('Oct 21, 2005')
result, t, is a datetime representing the given date(s). t=
21-Oct-2005
To avoid ambiguity between different date formats, it Try creating a datetime variable from the character
is good practice to specify the InputFormat option to representation.
the datetime function when creating dates from >> t = datetime('21 Oct 2005')
strings or cell arrays of strings. This is because if Error using datetime
MATLAB cannot infer the date format unambiguously Could not recognize the format of the date/time
from the string(s), an error occurs. strings.

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)

Use the linspace function to create an equally-spaced d = linspace(datetime(1995, 1, 1),


1-by-20 datetime vector d starting on January 1st 1995
datetime(1995, 6, 30), 20)
and ending on June 30th 1995.
7.3 Adjusting Date Formats: (1/4) Introduction
Adjusting Date Formats >> d = datetime(1999, 12, 31)
Local date formats differ significantly around the d =
world. To enable compatibility with other date 31-Dec-1999
>> d.Format = 'MM/dd/yyyy'
formats, datetime variables allow you to adjust their d =
Format property to any valid date format. This can be 12/31/1999
useful if you work with colleagues or data from other
countries with different local date formats.
Adjusting Date Formats
All datetime variables have a Format property that controls how they are displayed and exported externally to files.
This property is set to a default format when the variable is created. You can see the current format setting using the
dot notation:
Create a datetime. >> t = datetime(2005,10,21)
t =
21-Oct-2005

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.

Retrieving data from a datafeed is a three step


process.

1. Connect to the server using a function from


the table above.
>> c = fred; % Connect to FRED server

2. Use the appropriate retrieval function (for


example, fetch) to request data. This will
involve specifying details such as:
- the data series required (e.g.
'USD12MD156N' to represent the daily 12-
month London Interbank Offered Rate
(LIBOR)),
- the start and end dates (specified as
datetime variables).
>> tStart = datetime(2014, 1, 1);
>> tEnd = datetime(2014, 12, 31);
>> data = fetch(c, 'USD12MD156N', tStart, tEnd);

3. Close the server connection and tidy up.


>> close(c)
>> clear c
Downloading Data from a Datafeed
The first step in the process is to create a connection to the datafeed service provider.

Connect to the FRED® data provider. >> c = fred


c =
fred with properties:

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.

In this lesson, you will learn how to


convert numeric serial dates to the datetime
format. This enables the integration of
datafeed data with existing code making use
of datetime variables.
Converting Datafeed Dates
Dates are imported from datafeed providers in numeric serial date format. These serial date
numbers represent the numbers of days elapsed since the nominal date of 0-Jan-0000. You can
convert these to datetimes by setting the 'ConvertFrom' option in the datetime function to
'datenum'.
Consider importing data from a datafeed provider as follows.
Connect to the server. >> c = fred;
Download some data. Note that the first column >> t0 = datetime(2010, 7, 1);
contains numeric dates. >> t1 = datetime(2010, 9, 30);

>> djia = fetch(c, 'DJIA', t0, t1);


>> djiaData = djia.Data
djiaData =
734320 9732.53
734321 9686.48
... ...
734411 10788.05
You can convert these numeric dates to the datetime format by specifying the 'ConvertFrom'
option.
Extract the first >> djiaDates = djiaData(:, 1);
column of the matrix.
Convert these >> djiaDates = datetime(djiaDates, ...
numeric dates to 'ConvertFrom', 'datenum')
datetimes. djiaDates =
01-Jul-2010 00:00:00
02-Jul-2010 00:00:00
...
30-Sep-2010 00:00:00
7.8 Joining Data by Dates:
When importing data from different sources, including datafeed service providers, databases and
spreadsheets, you may have data recorded on different dates or times. It is important to be able
to merge and integrate data sets according to their overlapping dates or times.
Set Operations
You can identify overlapping data by performing set operations on dates. In MATLAB, the set
operations work on various data types such as numeric arrays, character arrays, dates and times,
and others.
Refer to the documentation for a complete list of set operation functions.
Open the documentation. >> docsearch('set operations')
You can use the intersect function to identify the elements that two arrays have in common.
>> [C,idxA,idxB] = intersect(A,B)

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.

S-ar putea să vă placă și