Code covered by the BSD License  

Highlights from
Pricing Derivatives Securities using MATLAB

image thumbnail

Pricing Derivatives Securities using MATLAB

by

 

02 Apr 2007 (Updated )

Examples of pricing derivatives securities using MATLAB

portbrowser(varargin)
function varargout = portbrowser(varargin)
% PORTBROWSER M-file for portbrowser.fig
%      PORTBROWSER, by itself, creates a new PORTBROWSER or raises the existing
%      singleton*.
%
%      H = PORTBROWSER returns the handle to a new PORTBROWSER or the handle to
%      the existing singleton*.
%
%      PORTBROWSER('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in PORTBROWSER.M with the given input arguments.
%
%      PORTBROWSER('Property','Value',...) creates a new PORTBROWSER or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before portbrowser_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to portbrowser_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help portbrowser

% Last Modified by GUIDE v2.5 20-Jul-2005 22:52:21

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @portbrowser_OpeningFcn, ...
                   'gui_OutputFcn',  @portbrowser_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before portbrowser is made visible.
function portbrowser_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to portbrowser (see VARARGIN)

% Choose default command line output for portbrowser
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes portbrowser wait for user response (see UIRESUME)
% uiwait(handles.figure1);

Port = varargin{1};
setappdata(hObject, 'Port', Port);

InstNames = instget(Port, 'Name');
NumInst = size(InstNames,1);
IdxStr = num2str((1:NumInst)');
set(handles.popupmenu1, 'String', IdxStr);

% Make the column titles bold
handles.activex1.ActiveSheet.Range('A1:B1').Font.Bold = true;
handles.activex1.ActiveSheet.Name='Instrument Parameters';

% Initialize the sheet using the callback fcn
popupmenu1_Callback(handles.popupmenu1, eventdata, handles)



% --- Outputs from this function are returned to the command line.
function varargout = portbrowser_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on selection change in popupmenu1.
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns popupmenu1 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu1

% Get selected index
idx = get(hObject,'Value');

% Get parameters and values for the instrument
Port=getappdata(gcf, 'Port');
[DataList, FieldList, ClassList, IndexSet, TypeSet] = instgetcell(Port, 'Index', idx);

%Eliminate Fields "Quantity" and "Face", and any field that has NaN (default) as a
%value
BadFields=[];
for iField = 1:length(FieldList)
    if(strcmpi(FieldList{iField}, 'quantity') | strcmpi(FieldList{iField}, 'face') | isnan(DataList{iField}))
        BadFields=[BadFields;iField];
    end
end
DataList(BadFields)=[];
FieldList(BadFields)=[];


% Swaps have two fields that are 2-element vectors. Need to map those to
% a string:
if strcmpi(TypeSet, 'Swap')
    LegRateIdx = strmatch('LegRate', FieldList, 'exact');
    DataList{LegRateIdx} = sprintf('%d / %d', DataList{LegRateIdx}(1), DataList{LegRateIdx}(2));
    
    LegResetIdx = strmatch('LegReset', FieldList, 'exact');
    DataList{LegResetIdx} = sprintf(' %d / %d ', DataList{LegResetIdx}(1), DataList{LegResetIdx}(2));
end

% Date values in DataList are serialized. Must find them and convert them
% to strings representation
serialIdx = find(~cellfun('isempty', strfind(FieldList, 'Date')));
if ~isempty(serialIdx)
    for i=serialIdx'
        if ~isnan(DataList{i})
            DataList{i}= datestr(DataList{i});        
        end
    end
end

% Still have to deal with Field Names that do not contain the string 
% 'Date' in them, but that are still dates
for iField=1:size(FieldList,1)
    switch lower(FieldList{iField})
        case {'settle', 'maturity'}
            if ~isnan(DataList{iField})
                DataList{iField}= datestr(DataList{iField});
            end
    end
end

% All NaNs must be turned into equivalentr string 'NaN'
for idx = 1:size(DataList,1)
    if isnan(DataList{idx})
        DataList{idx} = 'NaN';
    end
end

% reorder the fields so that TYPE and NAME are the first
% two fields:
NameIdx = strmatch('Name', FieldList, 'exact');
FL=[{'Parameter:'};{'Type'};FieldList(NameIdx);FieldList(1:NameIdx-1);FieldList(NameIdx+1:end)];
DL=[{'Value:'};{TypeSet};DataList(NameIdx);DataList(1:NameIdx-1);DataList(NameIdx+1:end)];
Data = [FL DL];
FillGrid2(handles.activex1, Data);
handles.activex1.ActiveSheet.Range('A1:B20').Columns.AutoFit();


% --- Executes during object creation, after setting all properties.
function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called


% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function FillGrid2(Spreadsheet1,M,DoPaste,DoWaitbar,MinR,MinC,MaxR,MaxC,AsStr)
% FILLGRID populates a grid, i.e. Microsoft Spreadsheet Object, with a cell array
% The cell array may contain mixed types.
%    FILLGRID(SPREADSHEET,M) populates SPREADSHEET with M
%    FILLGRID(SPREADSHEET,M,DOPASTE) usage obsolete
%    FILLGRID(SPREADSHEET,M,DOPASTE,DOWAITBAR) also uses a progress
%       indicator if DOWAITBAR is 1 (default), does not if DOWAITBAR is 0
%    FILLGRID(SPREADSHEET,M,DOPASTE,DOWAITBAR,MINR,MINC,MAXR,MAXC) specifies
%       the minimum and maximum rows and cloumns to use
%    FILLGRID(SPREADSHEET,M,DOPASTE,DOWAITBAR,MINR,MINC,MAXR,MAXC,ASSTR)
%       forces all values to be placed as strings, instead of the default
%       behavior which populates the grid with numbers when possible.
%
%    Example:
%       figure;
%       spreadsheet = actxcontrol('OWC11.Spreadsheet.11',[0 0 200 200]);
%       M = {'abc', 123; 12.17, logical(1)};
%       FillGrid(spreadsheet,M);
%
% IT'S NOT FANCY, BUT IT WORKS
%
%    See also Graph_and_Table, QuestDlgWithGrid, SearchAndReplaceMany,
%       SpreadSheet, DatabaseEditingTool, DuplicateFileFinder,
%       PutCellValue, nn2an
%
%    Keywords: grid spreadsheet ActiveX Active-X Active X GUI Table
%       graph_and_table plot graph table grid object flexgrid
%       msflexgrid ocx tabular

% Michael Robbins
% robbins@bloomberg.net
% michaelrobbins1@yahoo.com

TRUE = 1;
FALSE = 0;
TEST = TRUE;

if nargin<4 DoPaste = TRUE; end;
if nargin<5 DoWaitbar = TRUE; end;
if nargin<6 MinR =   0; end;
if nargin<7 MinC =   0; end;
if nargin<8 MaxR = 9e99; end;
if nargin<9 MaxC = 9e99; end;
if nargin<10 AsStr=0; end;

% USE AN ENUMERATED TYPE WORKAROUND
ClassEnumType = {'cell','char','logical','numeric'};

% FIND THE ACTIVE SHEET
ActSheet = get(Spreadsheet1,'ActiveSheet');

% CLEAR CONTENTS
ActSheet.Cells.ClearContents;

% FIND THE ACTIVE CELL, ROW AND COLUMN
% THIS IS NOT NECESSARY, BUT IT IS DONE FOR DEMONSTRATION
ActCell = get(Spreadsheet1,'ActiveCell');
ActCellRow = 1;%get(ActCell,'Row');
ActCellColumn = 1;%get(ActCell,'Column');

[L,W] = size(M);
MinR = max(MinR,1);
MinC = max(MinC,1);
MaxR = min(L,MaxR);
MaxC = min(W,MaxC);
DoPaste=0;

for r = MinR:MaxR
    for c = MinC:MaxC
        % Select current cell
        XLfmt = nn2an(ActCellRow+r-1,ActCellColumn+c-1);
        Select(Range(ActSheet,XLfmt));

        % Assign value
        ActCell = get(Spreadsheet1,'ActiveCell');
        if putcellvalue(ActCell,M(r,c),AsStr) break; end;
        % Re-select starting cell
        XLfmt = nn2an(ActCellRow,ActCellColumn);
        Select(Range(ActSheet,XLfmt));

    end;
end;
return



function cr = nn2an(r,c)
% Thanks Brett Shoelson, via CSSM

t = [floor((c - 1)/26) + 64 rem(c - 1, 26) + 65];
if(t(1)<65), t(1) = []; end
cr = [char(t) num2str(r)];
return


function DoBreak = putcellvalue(ActCell,M,AsStr)
% PUTCELLVALUE puts a value in an active cell
%    PUTCELLVALUE(ACTCELL,M) puts M in ACTCELL
%    PUTCELLVALUE(ACTCELL,M,ASSTR) converts M to a string before putting
%       it if ASSTR = 1, leaves it as is if ASSTR = 0 (default)
%
%    PUTCELLVALUE handles all classes and is used by FILLGRID.
%
% IT'S NOT FANCY, BUT IT WORKS
%
%    See also Graph_and_Table, QuestDlgWithGrid, SearchAndReplaceMany,
%       SpreadSheet, DatabaseEditingTool, DuplicateFileFinder,
%       PutCellValue, nn2an, FillGrid
%
%    Keywords: grid spreadsheet ActiveX Active-X Active X GUI Table
%       graph_and_table plot graph table grid object flexgrid
%       msflexgrid ocx tabular

% Michael Robbins
% robbins@bloomberg.net
% michaelrobbins1@yahoo.com


if nargin<3 AsStr=0; end;

if AsStr prefix = ''; else prefix = ''''; end;
DoBreak=0;
switch class(M)
    case 'cell', % DE-CELLIZE
        if prod(size(M)) > 1
            errordlg('bad cell');
        else
            putcellvalue(ActCell,M{:},AsStr);
        end;
    case 'char', % POST (DATES WILL POST NUMERICLY UNLESS AsStr==1
        set(ActCell,'Value',[prefix M]); DoBreak=1;
    case 'logical', % LOGICAL -> INT
        putcellvalue(ActCell,int32(M),AsStr);
    otherwise
        if isnumeric(M)
            if AsStr % # -> STRING
                if isinteger(M) fstr='%d'; else fstr='%f'; end;
                putcellvalue(ActCell,sprintf(fstr,M),AsStr);
            else % POST
                set(ActCell,'Value',M);
            end;
        else
            errordlg('bad class');
        end;
end;




Contact us