Download code

Jump to: navigation, search

Back to Swiss_army_knife_MATLAB_programs_for_quantitative_finance

Download for Windows: zip

Download for UNIX: zip, tar.gz, tar.bz2

plotstruct.m

 1 % The authors of this work have released all rights to it and placed it
 2 % in the public domain under the Creative Commons CC0 1.0 waiver
 3 % (http://creativecommons.org/publicdomain/zero/1.0/).
 4 % 
 5 % THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 % EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 % MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 % IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 % CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 % TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 % SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 % 
13 % Retrieved from: http://en.literateprograms.org/Swiss_army_knife_MATLAB_programs_for_quantitative_finance?oldid=19217
14 
15 function h = plotstruct(data, varargin)
16 % PLOTSTRUCT - plot a structured dataset
17 % returns an handle on mydateticks
18 % use:
19 %  h = plotstruct(data, options)
20 % options:
21 % - dates    : false
22 % - figure   : []
23 % - linewidth: 2
24 opts = options({'dates', false, 'figure', [], 'linewidth', 2}, varargin);
25 h = [];
26 g = opts.get('figure');
27 if isempty(g)
28    g = figure;
29 else
30    g = figure(g);
31 end
32 plot(data.date, data.value, 'linewidth', opts.get('linewidth'));
33 legend(data.names);
34 title(data.title);
35 if opts.get('dates')
36    h=mydateticks; 
37 end


hijacker
hijacker
hijacker
hijacker

example4data_structure.m

 1 % The authors of this work have released all rights to it and placed it
 2 % in the public domain under the Creative Commons CC0 1.0 waiver
 3 % (http://creativecommons.org/publicdomain/zero/1.0/).
 4 % 
 5 % THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 % EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 % MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 % IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 % CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 % TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 % SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 % 
13 % Retrieved from: http://en.literateprograms.org/Swiss_army_knife_MATLAB_programs_for_quantitative_finance?oldid=19217
14 
15 data = struct('title','Randomized quotes','date',(today:today+199)', ...
16               'value',100*cumprod(1+[randn(200,1)* 0.10, randn(200,1)* 0.21]/16), ...
17               'names', {{'Ticker1', 'Ticker2'}})
18 figure;
19 plot(data.date,data.value,'linewidth',2);
20 title(data.title); 
21 axis([min(data.date) max(data.date) min(data.value(:)) max(data.value(:))]);
22 z = mydateticks('datestr-format',25);
23 legend(data.names);
24 dformat = 'dd/mm/yyyy';
25 dates = {'10/06/2006' '14/09/2006'};
26 if iscell(dates)
27     nate = datenum(dates{1},dformat);
28     if length(dates)>1
29         nate = [nate, datenum(dates{2},dformat)];
30     end
31     dates = nate;
32 end
33 if length(dates)<2
34     dates = [dates, dates];
35 end
36 idx = find((data.date>=dates(1)) & (data.date<=dates(2)));
37 data.value = data.value(idx,:);
38 data.date  = data.date(idx);
39 figure;
40 plot(data.date,data.value,'linewidth',2);
41 title(data.title); 
42 axis([min(data.date) max(data.date) min(data.value(:)) max(data.value(:))]);
43 z = mydateticks('datestr-format',25);
44 legend(data.names);
45 figure;
46 plot(data.date,data.value,'linewidth',2);
47 title(data.title); 
48 axis([min(data.date) max(data.date) min(data.value(:)) max(data.value(:))]);
49 z = mydateticks('datestr-format',25);
50 legend(data.names);


hijacker
hijacker
hijacker
hijacker

tokenize.m

 1 % The authors of this work have released all rights to it and placed it
 2 % in the public domain under the Creative Commons CC0 1.0 waiver
 3 % (http://creativecommons.org/publicdomain/zero/1.0/).
 4 % 
 5 % THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 % EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 % MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 % IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 % CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 % TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 % SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 % 
13 % Retrieved from: http://en.literateprograms.org/Swiss_army_knife_MATLAB_programs_for_quantitative_finance?oldid=19217
14 
15 function t = tokenize(str,sep)
16 % TOKENIZE - string into cellarray using a separator
17 if nargin<2
18    sep = ';';
19 end
20 t = cellfun(@(x)(x{1}),regexp(str,sprintf('([^%s]+)%s',sep,sep),'tokens'),'Uniformoutput',false);


hijacker
hijacker
hijacker
hijacker

myuserdata.m

 1 % The authors of this work have released all rights to it and placed it
 2 % in the public domain under the Creative Commons CC0 1.0 waiver
 3 % (http://creativecommons.org/publicdomain/zero/1.0/).
 4 % 
 5 % THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 % EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 % MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 % IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 % CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 % TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 % SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 % 
13 % Retrieved from: http://en.literateprograms.org/Swiss_army_knife_MATLAB_programs_for_quantitative_finance?oldid=19217
14 
15 function z = myuserdata(handle, mode, name, value, def_value)
16 % MYUSERDATA - a function to access the UserData field
17 % use:
18 %  myuserdata(gca,'set','my-data', rand(10,2))
19 %  v = myuserdata(gca,'get','my-data')
20 
21 ud = get(handle,'UserData');
22 switch lower(mode)
23     case 'set'
24         if isempty(ud)
25             ud = options({name, value});
26         else
27             ud.set(name,value);
28         end
29         set(handle,'UserData',ud);
30     case 'get'
31         if isempty(ud)
32             if nargin > 3
33                 z = value;
34             else
35                 error('myuserdata:get:unknown','option <%s> not present in the UserData field',name);
36             end
37         else
38             if nargin > 3
39                 z = ud.get(name, value);
40             else
41                 z = ud.get(name);
42             end
43         end
44     otherwise
45         error('myuserdata:mode','mode <%s> unknown', mode);
46 end


hijacker
hijacker
hijacker
hijacker

build_hook.m

 1 % The authors of this work have released all rights to it and placed it
 2 % in the public domain under the Creative Commons CC0 1.0 waiver
 3 % (http://creativecommons.org/publicdomain/zero/1.0/).
 4 % 
 5 % THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 % EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 % MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 % IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 % CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 % TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 % SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 % 
13 % Retrieved from: http://en.literateprograms.org/Swiss_army_knife_MATLAB_programs_for_quantitative_finance?oldid=19217
14 
15 function z = build_hook(varargin)
16 % BUILD_HOOK - build an hook
17 % a hook is a functionnal object with a field an 3 methods:
18 % - names  , which is the names of the columns to work on
19 % - func   , which is an handle on the function to apply to columns
20 % - datefun, which is an handle on the function to apply to dates
21 % - colfun , which is an handle on the function to apply on column names
22 
23 opt = options({'names', '', 'func', @(v,d)(v), 'datefun', @(d,v)(d), 'colfun', @(x)(x)}, varargin);
24 if isempty(opt.get('names'))
25     error('build_hook:names', 'I need names of columns to work on');
26 end
27 
28 this.opt = opt;
29 z = @apply;
30 
31 function data = apply(data, varargin)
32     names = this.opt.get('names');
33     idx   = strmatch(names,data.names,'exact');
34     data.value = data.value(:,idx);
35     data.names = data.names(idx);
36     data.value = feval(this.opt.get('func'),data.value,data.date,varargin{:});
37     data.date  = feval(this.opt.get('datefun'), data.date,data.value);
38     data.names = feval(this.opt.get('colfun'), data.names);
39 end
40 
41 end


hijacker
hijacker
hijacker
hijacker

brownexp.m

 1 % The authors of this work have released all rights to it and placed it
 2 % in the public domain under the Creative Commons CC0 1.0 waiver
 3 % (http://creativecommons.org/publicdomain/zero/1.0/).
 4 % 
 5 % THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 % EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 % MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 % IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 % CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 % TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 % SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 % 
13 % Retrieved from: http://en.literateprograms.org/Swiss_army_knife_MATLAB_programs_for_quantitative_finance?oldid=19217
14 
15 function data = brownexp(volatility, nb_points, varargin)
16 % BROWNEXP - simulation of a brownian exponential diffusion
17 %  use:
18 % > data = brownexp(volatility, nb_points, options)
19 % options:
20 % - drift         :   0
21 % - start-price   : 100
22 % - time-step     :  1/250
23 % - nb-simulations:   1
24 % - time-horizon  :  []
25 % if time-horizon not empty, it replaces nb_points
26 %
27 %  example:
28 % data = brownexp(.20, 250, 'nb-simulations', 5)
29 % plotstruct( data)
30 
31 opt = options({'drift', 0, 'start-price', 100, 'time-step', 1/250, ...
32                'nb-simulations', 1, 'time-horizon', []}, varargin);
33 
34 if nargin < 2
35     nb_points = 100;
36 end
37 time_step = opt.get('time-step');
38 if ~isempty(opt.get('time-horizon'))
39     time_horizon = opt.get('time-horizon');
40 else
41     time_horizon = time_step*(nb_points-1);
42 end
43 
44 dates  = (0:time_step:time_horizon)';
45 values = opt.get('start-price')*cumprod(1+opt.get('drift') * ...
46          time_step+volatility *sqrt(time_step)*randn(length(dates),opt.get('nb-simulations')));
47 
48 data   = struct( 'title', 'simulations', 'value', values, 'date', dates, ...
49                  'names', {tokenize(sprintf('sim-%d;',1:size(values,2)),';')});


hijacker
hijacker
hijacker
hijacker

firstoo.m

 1 % The authors of this work have released all rights to it and placed it
 2 % in the public domain under the Creative Commons CC0 1.0 waiver
 3 % (http://creativecommons.org/publicdomain/zero/1.0/).
 4 % 
 5 % THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 % EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 % MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 % IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 % CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 % TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 % SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 % 
13 % Retrieved from: http://en.literateprograms.org/Swiss_army_knife_MATLAB_programs_for_quantitative_finance?oldid=19217
14 
15 function z = firstoo( n)
16 % FIRSTOO - my first real matlab object
17 % z=firstoo(2)
18 % z.add_n(3)
19 % z.get_n()
20 % z.set_n(7)
21 % z.get_n()
22 this.n = n;
23 z = struct('get_n',@get_n,'add_n',@add_n, 'set_n', @set_n);
24     function a = get_n()
25         a=this.n;
26     end
27     function u = set_n( m)
28         this.n = m;
29     end
30     function u = add_n(u)
31         u = u +this.n;
32     end
33 end
34 


hijacker
hijacker
hijacker
hijacker

mydateticks.m

 1 % The authors of this work have released all rights to it and placed it
 2 % in the public domain under the Creative Commons CC0 1.0 waiver
 3 % (http://creativecommons.org/publicdomain/zero/1.0/).
 4 % 
 5 % THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 % EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 % MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 % IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 % CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 % TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 % SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 % 
13 % Retrieved from: http://en.literateprograms.org/Swiss_army_knife_MATLAB_programs_for_quantitative_finance?oldid=19217
14 
15 function z = mydateticks( varargin)
16 % MYDATETICKS - simple dateticks management
17 
18 %%** MyDateTicks
19 opt = options({'axe-handle',gca, 'nb-steps',[], 'text-handle', [], ...
20                'datestr-format',24, 'rotation', 60, 'fontsize',8, ...
21                'fontname','Arial'},varargin);
22 %<* Initializations
23 this.options = opt;
24 redraw;
25 %>*
26 z    = struct('redraw', @redraw);
27 
28 %%** Redraw
29 function redraw
30     %<* Get info
31     % From internal state
32     ah = this.options.get('axe-handle');
33     th = this.options.get('text-handle');
34     %>*
35     %<* Cleaning
36     % Select good axe, clean xtickslabels
37     axes(ah);
38     ax  = axis;
39     dtx = get(ah,'XTick');
40     set(ah,'XTickLabel',[]);
41     if ~isempty(th)
42         delete(th);
43     end
44     %>*
45     %<* Nb of ticks
46     % It's a function of the number of pixel on screen
47     nb_steps = this.options.get('nb-steps');
48     if isempty(nb_steps)
49         posf     = get(gcf,'position');
50         posa     = get(gca,'position');
51         w        = posf(3)*posa(3);
52         nb_steps = round(w/20);
53     end
54     dv  = ax(1):(ax(2)-ax(1))/nb_steps:ax(2);
55     if abs(dv(end)-ax(2))<eps
56         dv = [dv, ax(2)];
57     end
58     %>*
59     th = text(dv,repmat(ax(3),length(dv),1), ...
60               datestr(dv,this.options.get('datestr-format')), ...
61               'Rotation',this.options.get('rotation'),...
62               'HorizontalAlignment','Right', ...
63               'fontsize',this.options.get('fontsize'), ...
64               'fontname',this.options.get('fontname'));
65     this.options.set('text-handle',th);
66 end
67 end


hijacker
hijacker
hijacker
hijacker

options.m

 1 % The authors of this work have released all rights to it and placed it
 2 % in the public domain under the Creative Commons CC0 1.0 waiver
 3 % (http://creativecommons.org/publicdomain/zero/1.0/).
 4 % 
 5 % THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 % EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 % MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 % IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 % CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 % TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 % SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 % 
13 % Retrieved from: http://en.literateprograms.org/Swiss_army_knife_MATLAB_programs_for_quantitative_finance?oldid=19217
14 
15 function z = options(default, overwrite)
16 % OPTIONS - sandbox for optionnal parameters management
17 %
18 % use:
19 % opt = options({'alpha',1,'beta',2},{'alpha',8,'gamma',3})
20 % opt.get('alpha')
21 % opt.set('alpha',3)
22 % opt.get('alpha')
23 % opt.get()
24 
25 %%** Optional parameters management
26 
27 %<* Initialization of the structure
28 values = default;
29 if nargin>1
30     for i=1:2:length(overwrite)-1
31         idx = strmatch(overwrite{i},values(1:2:end-1),'exact');
32         if isempty(idx)
33             %< New parameter
34             % Added to the list of parameters
35             values{end+1} = overwrite{i};
36             values{end+1} = overwrite{i+1};
37             %>
38         else
39             %< Parameter exists
40             % the new value replace the old one
41             values{idx(1)*2} = overwrite{i+1};
42             %>
43         end
44     end
45 end
46 %< Internal variable
47 this = struct('value',{values});
48 %>
49 %< Publication of external methods
50 z    = struct('get',@get_v,'set',@set_v);
51 %>
52 %>*
53 
54 %%** Internals
55 
56 %<* Get a value
57 function [r, h] = get_v( name, def_value)
58     h = 1:length(this.value);
59     if nargin==0
60         %< No argument
61         % Return the internal memory
62         r = this.value;
63         %>
64     else
65         idx = strmatch(name, this.value(1:2:end-1),'exact');
66         if isempty(idx) & nargin>1
67             %< Default value
68             % Unknown argument but default value is provided.
69             r = def_value;
70             h = 0;
71             %>
72         elseif isempty(idx) & nargin < 2
73             %< Unknown argument
74             error('options:get:unknown','parameter with name <%s> unknown',name);
75             %>
76         else
77             %< Argument found
78             % Its value (and the associate index) is returned
79             r = this.value{idx(1)*2-1+1};
80             h = idx(1)*2-1+1;
81             %>
82         end
83     end
84 end
85 %>*
86 %<* Set a value
87 function set_v(name, value)
88     [v,h] = get_v(name, []);
89     if h>0
90         this.value{h} = value;
91     else
92         this.value{end+1} = name;
93         this.value{end+1} = value;
94     end
95 end
96 %>*
97 end


hijacker
hijacker
hijacker
hijacker