CS计算机代考程序代写 matlab python data science database finance Excel Lectures 1 and 2: MATLAB Basics

Lectures 1 and 2: MATLAB Basics

Lectures 1 and 2: MATLAB Basics
Computational Finance

Language Comparisons

2
Which is better: MATLAB, R, Python, or Excel?
Excel R Python MATLAB
Great for small datasets
Possible to see all of your data
Portable
Fast
Free
Constantly updated
Great dashboards/visualizations
Online community Fast
Free
Updated often
Heavy on data science
More like a “real” programming language
Online community Great development environment (IDE)
Simple syntax – easiest to read and write
Great visualizations
Online community
Instructional webinars (mathworks.com)

Short answer: It depends!
Each has its own strengths and purposes

Calculates
Fast and natural matrix calculations
Visualizes
Basic plots are easy
Advanced plots are harder – but amazing
Reads Data
Excel, CSV, text, databases, datafeeds (Bloomberg®, Haver Analytics®, FRED®)
Learns
Statistical and machine learning
Creates
Reports can be easy

What does MATLAB do?

MATLAB Learning Resources

MATLAB: A Practical Introduction to Programming and Problem Solving
Stormy Attaway

www.mathworks.com
Webinars and videos by subject and Toolbox
Help with debugging errors; Community code-sharing

Introduction

Choosing Your Current Directory & Recording Your Command Session Window

Before starting to use MATLAB:
Change to the directory you want to use:

Now we can create a file to record our command session
Type: diary lecture_1.txt
NOTE: MATLAB files should never have spaces in names
When we want to close this file, we type: diary off

Variable and Assignment Statements
Assignment operator (pronounced ”assign”): ‘=‘
variable_name = a numerical value
Example: stock_price = 32;
Note: ‘;’ suppresses output
Rules about variable names:
Letters, digits, and the underscore character are allowed
Must begin with a letter
Case-sensitive
Allowed: s, stock, stock_price, s1
Not allowed: 1s, s!, s*

Meaningful Names and Readability
What does this mean?
b = 6 * exp(-.05*1) + 106*exp(-.05*2)
Compare to:
r = .05;
t = [1 2];
cash_flows = [6 106];
discounted_cash_flows = cash_flows.*exp(-r.*t)
bond_price = sum(discounted_cash_flows)
Readability is key to writing maintainable, understandable code!

MATLAB Variable Considerations
Keywords:
Reserved by MATLAB for various purposes and can’t be used as variable names
Two ways to identify them:
iskeyword() function – [‘length(iskeyword)’ tells us that there are 20 keywords]
Keywords turn blue when typed: try typing ‘if’ in the command window
Predefined MATLAB variables:
ans, pi, eps (the smallest difference between two numbers), i, j, NaN
Some useful commands:
who, whos, clear x, clear(‘x’,’y’,’z’), clear, clc

Built-In Functions
For functions (and variables, as we will see later), capitalization/case matters
Type ‘help function_name’ on the command line (no quotes, and replace function_name) for the description of a function and usage instructions, or search the MATLAB help
Math Functions Rounding Functions
sqrt(x) – the square root of x round(x) – round to the nearest integer
exp(x) – e to the power x ceil(x) – round toward infinity
log(x) – natural logarithm of x floor(x) – round toward minus infinity
log10(x) – log of x to the base 10
abs(-10) – absolute value

Trigonometric Functions Random numbers
sin(0) – sine rand() – generate a uniformly distributed random number
cos(1) – cosine randn() – generate a normally distributed random number
randi() – random integers between 1 and a specified maximum

Working in the Command Window
Command Window Tricks Display Format
clc – clear the command window format short – default format
; – semicolon suppresses output format long – displays more digits
↑ – recall previously typed command format bank – displays whole numbers plus two significant decimal digits
↓ – navigate to more recent commands (type ‘help format’ for options)
, – comma separates multiple commands on one line
(See command history window for previous commands)

Displaying Outputs: The Disp() Function
Type ‘help disp’ in the command window
Help menu: Search disp, copy the first example and run it
Examples:
disp(5); %displays the number 5
x = 5; disp(x); %displays the value of variable x
disp(‘ ‘); %displays an empty line (space required between the quotes)
disp(‘show text in string’); %displays the text between the quotes

Creating a Script File
Everything working in the command window also works in script files
From the command line: ‘edit AssetReturn.m’
Or New Script from the toolbar
From the Graphical User Interface (GUI): New Script
In the script file that comes up:

clc; clear;
simple_return = 0.01;
log_return= log(1 + simple_return);

disp(‘Simple Return’);
disp(simple_return);
disp(‘ ’);
disp(‘Log (compounded) Return’);
disp(log_return);

Running a Script File
There are three ways to run a script file:
The green run button (after running from the green button, you can use the up arrow from the command line to run again)
The green run button with a break point for debugging
Type the name of the script on the command line

Displaying Outputs: fprintf()
fprintf() allows us to display a mix of text and numerical values in specific formats
Example:
fprintf(‘An int: %3d; a float: %6.2f; an exp/float: %g\n’, 5, 4.9, 4.637);
The text is displayed as shown except for each ‘%’ denoting a “placeholder” for which we must pass a corresponding value:

Search “Formatting text” in MATLAB’s help for a full explanation of format strings

Using fprintf()
Let’s re-do our script file using fprintf()
Open a new script file and call it ‘AssetReturn2.m’

clc; clear;
simple_return = 0.01;
log_return= log(1 + simple_return);

fprintf(‘Simple Return: %g\n’,simple_return);
disp(‘ ‘);
fprintf(‘Log (compounded) Return: %g\n’,log_return);

The ‘\n’ is a special character specifying a new line
The disp() function automatically includes a carriage return and newline, while the fprintf() function doesn’t

Net Present Value Example
Net Present Value (NPV):

Cash flows (millions): , ,
Cost of capital: R=.12 (i.e., 12%)
See lecture code ‘Calculate_NPV.m’
Note: ‘%’ indicates a comment; nothing after the percent sign will be evaluated, so it is a ‘comment’ to the reader
Comments are extremely useful for you when you look back at your own code, and useful for others who want to use and/or modify the code

Calculate Bond Price: Script File
Net Present Value (NPV):
Suppose that a 2-year Treasury bond with a principal of $100 provides coupons at the rate of 6% per annum semiannually. What is the price of this bond?
( )
Calculate_BondPrice.m

What is an Array?
Concepts:
1D: for each point, x (a 1D array is often called a “vector”)
2D: for each point (x,y) – often called a “matrix”
3D: for each point (x,y,z)
Vectors: Bond price example
Time vector: [0.5, 1.0, 1.5, 2.0]
Interest vector: [5%, 5.8%, 6.4%, 6.8%]
Cash flow vector: [3, 3, 3, 103]
Terminology
Row vector
Column vector
Transpose operator

Creating Vectors in MATLAB
Creating a vector from a list of numbers:
Row vector: [3 3 3 103] (or [3, 3, 3, 103])
Column vector: [3; 3; 3; 103]
Transpose operator: ‘ (apostrophe / single quote)
Creating a vector with known spacing
Consider the time vector: [0.5, 1.0, 1.5, 2.0]
t = 0.5:0.5:2.0;
To increment by one, omit the middle increment value
t = 1.5;
1:?:9 (can we specify 5 number between 1 and 9?)

Creating Vectors Cont.
Creating a vector by specifying the ends and the number of points
linspace(1,9,5): 5 evenly-spaced numbers from 1 to 9
linspace(1,9,6): 6 evenly-spaced numbers from 1 to 9

Creating a 2D Matrix
Concepts:
A triangle in 2D: three points [7 4], [3 8], [6 5]
As a matrix , 3×2
Extension: mxn, m row vectors, n column vectors

Input a matrix in MATLAB
[7 4; 3 8; 6 5]
[v1;v2;v3] %v1, v2 and v3 are row vectors
[1:2:9; 2:2:10]
Transpose operator: ‘

Matrices Cont.
Special matrices in MATLAB
zeros (creates a matrix of all zeros)
ones (creates a matrix of all ones)
Eye (creates an identity matrix: ones on the diagonal and zeroes elsewhere)

All variables in MATLAB are arrays
Scalar, 1×1
Row vector, 1 xn
Column vector, mx1
Matrix, mxn

Array Addressing
Vector: v(n)
2D array: a(m,n)
Colon (‘:’) operator
Vector: v(:), v(n1:n2)
Matrix:
Row m: a(m,:)
Column n: a(:,n)
Other usage in the book on page 44
end operator
v(end)
a(1,end), m(end,1), a(end,end)
a(:,end), a(end,:)
Built-in functions for arrays
length(v) – the number of elements in the vector v
size(a) – the size of the array a, mxn

Matrix Operations
Addition and subtraction (must be the same size)
Vector addition and subtraction
v1=1:5;v2=5:-1:1;v3=v2+v1
v4=11:15;v5=v4-v1;
Matrix addition and subtraction
a1 = [v1;v2];a2 = [v3;v2];a3 = a1+a2;
a4 = a2-a1;
Element-by-element operations (arrays must be the same size or one must be a scalar)
Multiplication (.*): a5=2*ones(2,5);a6=a5.*a1;
(right) Division (./): a7 = a6./a1;
Exponentiation (.^): a8 = a1.^2;

Matrix Multiplication (* – NO DOT)
“Matrix multiplication” refers to the mathematical concept from linear/matrix algebra
This is not an element-by-element operation
Vector example: (1×3)*(3×1)

‘Inner’ dimensions
must match

Outer Dimensions (1×1) determine
the size of the resulting matrix

In MATLAB, this is:
[4 5 6]*[1 2 3]’

Matrix Multiplication (With Matrices)
Try this example:
X = randi(10,3,5)
Y = randi(10,5,4)
X_times_Y = X*Y
This is a (3×5) times a (5×4), so the result is (3×4)
If the inner dimensions don’t match, you will see this error:

Functions and Arrays
Using arrays in MATLAB built-in math functions (element-by-element)
sqrt(a8)
x = linspace(-2*pi,2*pi); y=sin(x);plot(x,y);
Built-in functions for analyzing arrays
sum(v): v=1:9; sum(v)
max(a): a = round(9*rand(5)+1);max(a)
min(a)
mean(v): v=randn(1000,1);mean(v);
std(v)
Note the dim parameter in the help pages for array functions
This determines whether it operates down the first dimension or across the second dimension in a two-dimensional matrix
Try: disp(max(a,[],2)); and disp(max(a,[],1));

Vectorization Examples
Examples: the bond price and NPV problems vectorized:
Calculate_NPV_vectorized.m
Calculate_BondPrice_vectorized.m

In-Class Exercise
Suppose we have a table of zero rates with continuous compounding
A forward rate is the rate used to discount a payment at a future date to an earlier future date
Using the table of zero rates provided and the formula below for the zero rate at time , calculate the one-year forward rates for years 2 through 5 using arrays and array indexing
Maturity (years) Zero Rate
(% per annum)
1 2.0
2 3.0
3 3.7
4 4.2
5 4.5

Programming in MATLAB
Relational and logical operators:
>, <, >=, <=, ==, ~= True 1, false 0 Element-by-element comparison for arrays (same size) Logical arrays vs. numeric arrays of 0s and 1s Logical operators: &, |, ~ Nonzero true, zero false Element-by-element for arrays (same size) Order of precedence (arithmetic, logical, and relational operators) The highest for parentheses Use parentheses when in doubt Financial Concept: European Call Option “A call option gives the holder the right to buy the underlying asset by a certain date for a certain price.” (John C. Hull: Options, Futures and Other Derivatives) Parameters for a call option: S, or S0: the current (spot) price of the underlying asset K: the “strike price”, the price for which the holder can buy the asset at the maturity date Maturity date: the date when the holder can buy the underlying asset at the strike price This is the date when the holder can buy the underlying asset For a European option, the maturity time is the only time the underlying asset can be purchased Note: the time-to-maturity (usually specified in years and often designated as T or τ (the Greek letter “tau”) is typically used when pricing the option. The time-to-maturity is calculated as maturity date minus the current date. The ”payoff” for a call option is the underlying asset price at maturity minus the strike price If the payoff would be negative (i.e., the maturity price of the asset is less than the strike price), we would not exercise the option, so the payoff is zero European Call Option S0 t price 0 T K: Strike Price ST,1 ST,2 Maturity is T years from now (now: t=0) If the stock price at time T is ST,1>K we will exercise the option, and the payoff is ST,1-K
If the stock price at time T is ST,2< K, we will not exercise the option, and the payoff is 0 Conditional Statements if-end Ex: payoff for a European call option payoff = 0; s = 40; K = 35; if s > K
payoff = s – K;
end
if-else-end
Ex: payoff for a European call option (again)
s = 40; K = 35;
if s > K
payoff = s – K;
else
payoff = 0;
end

Conditional Statements Cont.
if-elseif-else-end
Ex: Payoff of a bull spread
Buy a call option with strike price K1
Sell a call option with K2, where K2 > K1
K1 = 100; K2 = 115; s = 110;
if s > K2
payoff = K2 – s + s – K1;
elseif s > K1
payoff = s – K1; %no payoff on short call
else
payoff = 0;
end
Switch-case statement
Short-hand method to implement a long series of elseif statements
See the book for this; we won’t use it

Loops
for-end loops: Repeat a block of code a pre-determined number of time
for i = 1:5
disp(i)
end

while-end loops: Repeat a block of code while a condition is true
i = 10;
while (i >= 5)
i = i – 1;
disp(i);
end

Two-Dimensional Plot
simple_return = linspace( -0.5, 0.5);

log_return = log(1+simple_return);

plot(simple_return,log_return)

plot(simple_return, log_return, ‘o’)
%Add title, X and Y labels
title(‘Log Return vs. Simple Return’);
xlabel(‘Simple Return’);
ylabel(‘Log Return’);
Type ‘help plot’ on the command line to see plot options; use MATLAB help and/or see Attaway 3.5
Open a new blank figure window for plotting: figure
Two plots in the same figure window:
hold on and hold off
line([0 0],[-1 1],’color’,’r’); %draws a red line from point (0,-1) to (0,1)

Result of Plot Code

Note: To copy figure, choose Edit -> Copy Figure
Wait for the copy to finish, then you can paste in any MS Office document

Other Plot Functions
Function Description
clf Clears the current figure window
figure Creates a new, blank figure window. Using figure(n) allows you to refer to figure windows by number
hold ‘hold on’ plots all succeeding plot calls on the same window
‘hold off’ turns off the hold
legend Displays a legend box in the figure window
grid Displays grid lines on the plot

See script file: plot2figs.m

-0.5-0.4-0.3-0.2-0.100.10.20.30.40.5
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
Log Return vs. Simple Return
Simple Return
Log Return

/docProps/thumbnail.jpeg