OOP is short for Object-Oriented programming. Instead of defining separate functions and processes, we define objects that both store properties(data) to compute and functions(methods) to deal with the data, or to realize certain functionalities. Say we want to define an object for Up-and-out barrier call options, let’s list all of them first:
Option:
properties: (things that define the option)
spot price, strike price, upper barrier, interest rate, dividend rate, volatility, expiration date.
methods:
price the option by Closed-form formula
price the option by simple Monte Carlo simulation
price the option with Monte Carlo simulation * antithetic variance reduction
price the option with MC simulation * control variates
So this is the structure we would like to define. For each of the methods, we would like MATLAB to look inside the *option* object and take out what is needed, compute the price and display the result.
First of all:
use this template to build up a basic framework:
classdef <objectName> < handle
properties (SetAccess = public)
<anything you would like to add>
yes, anything you would like to be included in the *class*. it can be double, integer, vector or anything. Keep in mind that you just need to put a name there first and don’t specify the form.
end
methodsend
function obj = <objectName>(external parameters)
the first function usually shares the same name with the object, and it’s exactly the constructor function. So at least one external parameter is need.
function A(obj)
end
function B(obj, external parameter)
end
function disp(obj)
and yes, you can overload some frequently-used functions specifically for your object
end
end
---------------------------------------------------------------------
That’s it. Replace the <objectName> with exact and meaningful string, save the file as <objectName>.m. And you can call the functions or do anything you like with the object.
Let’s do a simple example. Define a class with one 5*5 matrix, and one double. There is one method (besides the constructor) inside the class, each time we call this method, 5*5 matrix would be filled with random number, and the double will be the biggest one of the matrix entries.
classdef example < handle
propertiesend
matrix5_5
double1
end
methods
function obj = example(void)
obj.matrix5_5 = zeros(5,5);
obj.double1 = 0; % see how we cite the value inside?
end
function randomAndPick(obj)
obj.matrix5_5 = randn(5,5)
obj.double1 = max(max(randn)
end
end
---------------------------------------------------
save it with filename = ‘example.m’
run in main window:
test1 = example();
test1.randomAndPick
Here I attach one of my code. It’s not that well written, but works.
BarrierOption2.m
Jiaming
No comments:
Post a Comment