blackscholes.m
上传用户:hfch80
上传日期:2007-10-25
资源大小:3637k
文件大小:26k
源码类别:

行业发展研究

开发平台:

Matlab

  1. % PURPOSE : Demonstrate the differences between the following
  2. % filters on an options pricing problem.
  3. %           
  4. %           1) Extended Kalman Filter  (EKF)
  5. %           2) Unscented Kalman Filter (UKF)
  6. %           3) Particle Filter         (PF)
  7. %           4) PF with EKF proposal    (PFEKF)
  8. %           5) PF with UKF proposal    (PFUKF)
  9. % For more details refer to:
  10. % AUTHORS  : Nando de Freitas      (jfgf@cs.berkeley.edu)
  11. %            Rudolph van der Merwe (rvdmerwe@ece.ogi.edu)
  12. %            + We re-used a bit of code by Mahesan Niranjan.             
  13. % DATE     : 17 August 2000
  14. clear all;
  15. echo off;
  16. path('./ukf',path);
  17. path('./data',path);
  18. % INITIALISATION AND PARAMETERS:
  19. % ==============================
  20. doPlot = 0;                 % 1 plot online. 0 = only plot at the end.
  21. g1 = 3;                     % Paramater of Gamma transition prior.
  22. g2 = 2;                     % Parameter of Gamman transition prior.
  23.                             % Thus mean = 3/2 and var = 3/4.
  24. T = 204;                    % Number of time steps.
  25. R = diag([1e-5 1e-5]);      % EKF's measurement noise variance. 
  26. Q = diag([1e-7 1e-5]);      % EKF's process noise variance.
  27. P01 = 0.1;                  % EKF's initial variance of the
  28.                             % interest rate.
  29. P02 = 0.1;                  % EKF's initial variance of the volatility.
  30. N = 10;                     % Number of particles.
  31. optionNumber = 1;           % There are 5 pairs of options.
  32. resamplingScheme = 1;       % The possible choices are
  33.                             % systematic sampling (2),
  34.                             % residual (1)
  35.                             % and multinomial (3). 
  36.                             % They're all O(N) algorithms. 
  37. P01_ukf = 0.1;
  38. P02_ukf = 0.1;
  39.     
  40. Q_ukf = Q;
  41. R_ukf = R;
  42.     
  43. initr = .01;
  44. initsig = .15;
  45. Q_pfekf = 10*1e-5*eye(2);
  46. R_pfekf = 1e-6*eye(2);
  47. Q_pfukf = Q_pfekf;
  48. R_pfukf = R_pfekf;
  49.     
  50. alpha = 1;                     % UKF : point scaling parameter
  51. beta  = 2;                     % UKF : scaling parameter for higher order terms of Taylor series expansion 
  52. kappa = 1;                     % UKF : sigma point selection scaling parameter (best to leave this = 0)
  53. no_of_experiments = 1;         % Number of times the experiment is
  54.                                % repeated (for statistical purposes).
  55. % DATA STRUCTURES FOR RESULTS
  56. % ===========================
  57. errorcTrivial = zeros(no_of_experiments,1);
  58. errorpTrivial = errorcTrivial;
  59. errorcEKF     = errorcTrivial;
  60. errorpEKF     = errorcTrivial;
  61. errorcUKF     = errorcTrivial;
  62. errorpUKF     = errorcTrivial;
  63. errorcPF      = errorcTrivial;
  64. errorpPF      = errorcTrivial;
  65. errorcPFEKF   = errorcTrivial;
  66. errorpPFEKF   = errorcTrivial;
  67. errorcPFUKF   = errorcTrivial;
  68. errorpPFUKF   = errorcTrivial;
  69. % LOAD THE DATA:
  70. % =============
  71. fprintf('n')
  72. fprintf('Loading the data')
  73. fprintf('n')
  74. load c2925.prn;         load p2925.prn;
  75. load c3025.prn;         load p3025.prn;
  76. load c3125.prn;         load p3125.prn;
  77. load c3225.prn;         load p3225.prn;
  78. load c3325.prn;         load p3325.prn;
  79. X=[2925; 3025; 3125; 3225; 3325];
  80. [d1,i1]=sort(c2925(:,1));  Y1=c2925(i1,:);      Z1=p2925(i1,:);
  81. [d2,i2]=sort(c3025(:,1));  Y2=c3025(i2,:);      Z2=p3025(i2,:);
  82. [d3,i3]=sort(c3125(:,1));  Y3=c3125(i3,:);      Z3=p3125(i3,:);
  83. [d4,i4]=sort(c3225(:,1));  Y4=c3225(i4,:);      Z4=p3225(i4,:);
  84. [d5,i5]=sort(c3325(:,1));  Y5=c3325(i5,:);      Z5=p3325(i5,:);
  85. d=Y1(:,1); 
  86. % d - date to maturity.
  87. St(1,:) = Y1(:,3)';   C(1,:) = Y1(:,2)';  P(1,:) = Z1(:,2)';
  88. St(2,:) = Y2(:,3)';   C(2,:) = Y2(:,2)';  P(2,:) = Z2(:,2)';
  89. St(3,:) = Y3(:,3)';   C(3,:) = Y3(:,2)';  P(3,:) = Z3(:,2)';
  90. St(4,:) = Y4(:,3)';   C(4,:) = Y4(:,2)';  P(4,:) = Z4(:,2)';
  91. St(5,:) = Y5(:,3)';   C(5,:) = Y5(:,2)';  P(5,:) = Z5(:,2)';
  92. % St - Stock price.
  93. % C - Call option price.
  94. % P - Put Option price.
  95. % X - Strike price.
  96. % Normalise with respect to the strike price:
  97. for i=1:5
  98.    Cox(i,:) = C(i,:) / X(i);
  99.    Sox(i,:) = St(i,:) / X(i);
  100.    Pox(i,:) = P(i,:) / X(i);
  101. end
  102. Cpred=zeros(T,5);
  103. Ppred=zeros(T,5);
  104. % PLOT THE LOADED DATA:
  105. % ====================
  106. figure(1)
  107. clf;
  108. plot(Cox');
  109. ylabel('Call option prices','fontsize',15);
  110. xlabel('Time to maturity','fontsize',15);
  111. fprintf('n')
  112. fprintf('Press a key to continue')  
  113. pause;
  114. fprintf('n')
  115. fprintf('n')
  116. fprintf('Training has started')
  117. fprintf('n')
  118. % SPECIFY THE INPUTS AND OUTPUTS
  119. % ==============================
  120. ii=optionNumber;   % Only one call price. Change 1 to 3, etc. for other prices.
  121. X = X(ii,1);
  122. St = Sox(ii,1:T);
  123. C = Cox(ii,1:T);
  124. P = Pox(ii,1:T);
  125. counter=1:1:T;
  126. tm = (224*ones(size(counter))-counter)/260;
  127. u = [St' tm']';
  128. y = [C' P']'; % Call and put prices.
  129. % MAIN LOOP
  130. % =========
  131. for expr=1:no_of_experiments,
  132.   rand('state',sum(100*clock));   % Shuffle the pack!
  133.   randn('state',sum(100*clock));   % Shuffle the pack!  
  134.   
  135. %%%%%%%%%%%%%%%  PERFORM EKF and UKF ESTIMATION  %%%%%%%%%%%%%%%%%%%%%
  136. %%%%%%%%%%%%%%%  ==============================  %%%%%%%%%%%%%%%%%%%%%
  137. % INITIALISATION:
  138. % ==============
  139. mu_ekf = ones(2,T);       % EKF estimate of the mean of the states.
  140. Inn = ones(2,2,T);        % Innovations Covariance.
  141. Inn_ukf = Inn;
  142. mu_ekf(1,1) = initr;
  143. mu_ekf(2,1) = initsig;
  144. P_ekf = ones(2,2,T);      % EKF estimate of the variance of the states.
  145. for t=1:T
  146.   P_ekf(:,:,t)= diag([P01 P02]);
  147. end;
  148. mu_ukf = mu_ekf;        % UKF estimate of the mean of the states.
  149. P_ukf = P_ekf;          % UKF estimate of the variance of the states.
  150. yPred = ones(2,T);      % One-step-ahead predicted values of y.
  151. yPred_ukf = yPred;
  152. mu_ekfPred = mu_ekf;    % EKF O-s-a estimate of the mean of the states.
  153. PPred =eye(2);          % EKF O-s-a estimate of the variance of the states.
  154. disp(' ');
  155. for t=2:T,    
  156.   fprintf('EKF & UKF : t = %i / %i  r',t,T);
  157.   fprintf('n')
  158.   
  159.   % EKF PREDICTION STEP:
  160.   % ==================== 
  161.   mu_ekfPred(:,t) = feval('bsffun',mu_ekf(:,t-1),t);
  162.   Jx = eye(2);  % Jacobian for bsffun.  
  163.   PPred = Q + Jx*P_ekf(:,:,t-1)*Jx'; 
  164.   
  165.   % EKF CORRECTION STEP:
  166.   % ====================
  167.   yPred(:,t) = feval('bshfun',mu_ekfPred(:,t),u(:,t),t);
  168.   % COMPUTE THE JACOBIAN:
  169.   St  = u(1,t);            % Index price.
  170.   tm  = u(2,t);            % Time to maturity.
  171.   r   = mu_ekfPred(1,t);   % Risk free interest rate.
  172.   sig = mu_ekfPred(2,t);   % Volatility.  
  173.   d1 = (log(St) + (r+0.5*(sig^2))*tm ) / (sig * (tm^0.5));
  174.   d2 = d1 - sig * (tm^0.5);  
  175.   % Differentials of call price
  176.   dcsig = St * sqrt(tm) * exp(-d1^2) / sqrt(2*pi);
  177.   dcr   = tm * exp(-r*tm) * normcdf(d2);
  178.   % Differentials of put price
  179.   dpsig = dcsig;
  180.   dpr   = -tm * exp(-r*tm) * normcdf(-d2);
  181.   Jy = [dcr dpr; dcsig dpsig]'; % Jacobian for bshfun.
  182.   % APPLY THE EKF UPDATE EQUATIONS:
  183.   M = R + Jy*PPred*Jy';                 % Innovations covariance.
  184.   Inn(:,:,t)=M;
  185.   K = PPred*Jy'*inv(M);                 % Kalman gain.
  186.   mu_ekf(:,t) = mu_ekfPred(:,t) + K*(y(:,t)-yPred(:,t));
  187.   P_ekf(:,:,t) = PPred - K*Jy*PPred;
  188.   
  189.   % Full Unscented Kalman Filter step
  190.   % =================================
  191.   [mu_ukf(:,t),P_ukf(:,:,t),zab1,zab2,yPred_ukf(:,t),inov_ukf,Inn_ukf(:,:,t),K_ukf]=ukf(mu_ukf(:,t-1),P_ukf(:,:,t-1),u(:,t),Q_ukf,'ukf_bsffun',y(:,t),R_ukf,'ukf_bshfun',t,alpha,beta,kappa);
  192.   
  193. end;   % End of t loop.
  194. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  195. %-- CALCULATE PERFORMANCE --%
  196. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  197. figure(3)
  198. clf;
  199. subplot(211)
  200. p1=plot(1:T,mu_ekf(1,:),'r','linewidth',2);hold on;
  201. p2=plot(1:T,mu_ukf(1,:),'b','linewidth',2);hold off;
  202. legend([p1 p2],'ekf','ukf');
  203. ylabel('Interest rate','fontsize',15)
  204. subplot(212)
  205. p1=plot(1:T,mu_ekf(2,:),'r','linewidth',2);hold on;
  206. p2=plot(1:T,mu_ukf(2,:),'b','linewidth',2);hold off;
  207. ylabel('Volatility','fontsize',15);
  208. xlabel('Time (days)','fontsize',15)
  209. zoom on;
  210. % Transform innovations covariance for plotting.
  211. Inn11=zeros(1,T);
  212. Inn22=zeros(1,T);
  213. Pekf11=zeros(1,T);
  214. Pekf22=zeros(1,T);
  215. for t=1:T,
  216.   Inn11(t)=Inn(1,1,t);
  217.   Inn22(t)=Inn(2,2,t);
  218.   Inn11_ukf(t)=Inn_ukf(1,1,t);
  219.   Inn22_ukf(t)=Inn_ukf(2,2,t);
  220.   Pekf11(t)=P_ekf(1,1,t);
  221.   Pekf22(t)=P_ekf(2,2,t);
  222.   Pukf11(t)=P_ukf(1,1,t);
  223.   Pukf22(t)=P_ukf(2,2,t);
  224. end;
  225. figure(1)
  226. clf;
  227. subplot(211)
  228. plot(1:T,y(1,:),'r--',1:T,yPred(1,:),'b','linewidth',2);
  229. hold on;
  230. plot(1:T,yPred(1,:)+2*sqrt(Inn11),'k',1:T,yPred(1,:)-2*sqrt(Inn11),'k')
  231. ylabel('Call price','fontsize',15)
  232. legend('Actual price','Prediction');
  233. axis([0 204 0.03 .22])
  234. title('EKF');
  235. subplot(212)
  236. plot(1:T,y(2,:),'r--',1:T,yPred(2,:),'b','linewidth',2);
  237. hold on;
  238. plot(1:T,yPred(2,:)+2*sqrt(Inn22),'k',1:T,yPred(2,:)-2*sqrt(Inn22),'k')
  239. ylabel('Put price','fontsize',15)
  240. xlabel('Time (days)','fontsize',15)
  241. axis([0 204 0 .06])
  242. zoom on;
  243. legend('Actual price','Prediction');
  244. figure(2)
  245. clf;
  246. subplot(211)
  247. plot(1:T,y(1,:),'r--',1:T,yPred_ukf(1,:),'b','linewidth',2);
  248. hold on;
  249. plot(1:T,yPred_ukf(1,:)+2*sqrt(Inn11_ukf),'k',1:T,yPred_ukf(1,:)-2*sqrt(Inn11_ukf),'k')
  250. ylabel('Call price','fontsize',15)
  251. legend('Actual price','Prediction');
  252. axis([0 204 0.03 .22])
  253. title('UKF');
  254. subplot(212)
  255. plot(1:T,y(2,:),'r--',1:T,yPred_ukf(2,:),'b','linewidth',2);
  256. hold on;
  257. plot(1:T,yPred_ukf(2,:)+2*sqrt(Inn22_ukf),'k',1:T,yPred_ukf(2,:)-2*sqrt(Inn22_ukf),'k')
  258. ylabel('Put price','fontsize',15)
  259. xlabel('Time (days)','fontsize',15)
  260. axis([0 204 0 .06])
  261. zoom on;
  262. legend('Actual price','Prediction');
  263. %%%%%%%%%%%%%%%  PERFORM SEQUENTIAL MONTE CARLO  %%%%%%%%%%%%%%%%%%%%%
  264. %%%%%%%%%%%%%%%  ==============================  %%%%%%%%%%%%%%%%%%%%%
  265. % INITIALISATION:
  266. % ==============
  267. xparticle_pf = ones(2,T,N);      % These are the particles for the estimate
  268.                                  % of x. Note that there's no need to store
  269.                                  % them for all t. We're only doing this to
  270.                                  % show you all the nice plots at the end.
  271. xparticlePred_pf = ones(2,T,N);    % One-step-ahead predicted values of the states.
  272. yPred_pf = ones(2,T,N);            % One-step-ahead predicted values of y.
  273. w = ones(T,N);                   % Importance weights.
  274. % Initialisation:
  275. for i=1:N,
  276.   xparticle_pf(1,1,i) = initr; % sqrt(initr)*randn(1,1);
  277.   xparticle_pf(2,1,i) = initsig; %sqrt(initsig)*randn(1,1);
  278. end;
  279. disp(' ');
  280.  
  281. tic;                             % Initialize timer for benchmarking
  282. for t=2:T,    
  283.   fprintf('PF :  t = %i / %i  r',t,T);
  284.   fprintf('n')
  285.   
  286.   % PREDICTION STEP:
  287.   % ================ 
  288.   % We use the transition prior as proposal.
  289.   for i=1:N,
  290.     xparticlePred_pf(:,t,i) = feval('bsffun',xparticle_pf(:,t-1,i),t) + sqrtm(Q)*randn(2,1);    
  291.   end;
  292.   % EVALUATE IMPORTANCE WEIGHTS:
  293.   % ============================
  294.   % For our choice of proposal, the importance weights are give by:  
  295.   for i=1:N,
  296.     yPred_pf(:,t,i) = feval('bshfun',xparticlePred_pf(:,t,i),u(:,t),t);        
  297.     lik = exp(-0.5*(y(:,t)-yPred_pf(:,t,i))'*inv(R)*(y(:,t)-yPred_pf(:,t,i)) ) + 1e-99; % Deal with ill-conditioning.
  298.     w(t,i) = lik;    
  299.   end;  
  300.   w(t,:) = w(t,:)./sum(w(t,:));                % Normalise the weights.
  301.   
  302.   % SELECTION STEP:
  303.   % ===============
  304.   % Here, we give you the choice to try three different types of
  305.   % resampling algorithms. Note that the code for these algorithms
  306.   % applies to any problem!
  307.   if resamplingScheme == 1
  308.     outIndex = residualR(1:N,w(t,:)');        % Residual resampling.
  309.   elseif resamplingScheme == 2
  310.     outIndex = systematicR(1:N,w(t,:)');      % Systematic resampling.
  311.   else  
  312.     outIndex = multinomialR(1:N,w(t,:)');     % Multinomial resampling.  
  313.   end;
  314.   xparticle_pf(:,t,:) = xparticlePred_pf(:,t,outIndex); % Keep particles with
  315.                                                     % resampled indices.
  316. end;   % End of t loop.
  317. time_pf = toc;    % How long did this take?
  318. % Compute posterior mean predictions:
  319. yPFmeanC=zeros(1,T);
  320. yPFmeanP=zeros(1,T);
  321. for t=1:T,
  322.   yPFmeanC(t) = mean(yPred_pf(1,t,:));
  323.   yPFmeanP(t) = mean(yPred_pf(2,t,:));  
  324. end;  
  325. figure(4)
  326. clf;
  327. domain = zeros(T,1);
  328. range = zeros(T,1);
  329. thex=[0:1e-3:20e-3];
  330. hold on
  331. ylabel('Time (t)','fontsize',15)
  332. xlabel('r_t','fontsize',15)
  333. zlabel('p(r_t|S_t,t_m,C_t,P_t)','fontsize',15)
  334. for t=11:20:200,
  335.   [range,domain]=hist(xparticle_pf(1,t,:),thex);
  336.   waterfall(domain,t,range/sum(range));
  337. end;
  338. view(-30,80);
  339. rotate3d on;
  340. a=get(gca);
  341. set(gca,'ygrid','off');
  342. figure(5)
  343. clf;
  344. domain = zeros(T,1);
  345. range = zeros(T,1);
  346. thex=[0.1:1e-2:0.25];
  347. hold on
  348. ylabel('Time (t)','fontsize',15)
  349. xlabel('r_t','fontsize',15)
  350. zlabel('p(sigma_t|S_t,t_m,C_t,P_t)','fontsize',15)
  351. %v=[0 1];
  352. %caxis(v);
  353. for t=11:20:200,
  354.   [range,domain]=hist(xparticle_pf(2,t,:),thex);
  355.   waterfall(domain,t,range/sum(range));
  356. end;
  357. view(-30,80);
  358. rotate3d on;
  359. a=get(gca);
  360. set(gca,'ygrid','off');
  361. %%%%%%%%%%%%%%%  PERFORM SEQUENTIAL MONTE CARLO  %%%%%%%%%%%%%%%%%%%%%
  362. %%%%%%%%%%%%%%%  ======== EKF proposal ========  %%%%%%%%%%%%%%%%%%%%%
  363. % INITIALISATION:
  364. % ==============
  365. xparticle_pfekf = ones(2,T,N);      % These are the particles for the estimate
  366.                                     % of x. Note that there's no need to store
  367.                                     % them for all t. We're only doing this to
  368.                                     % show you all the nice plots at the end.
  369. Pparticle_pfekf = cell(N,1);        % Particles for the covariance of x.
  370. % Initialisation:
  371. for i=1:N,
  372.   xparticle_pfekf(1,1,i) = initr;   % sqrt(initr)*randn(1,1);
  373.   xparticle_pfekf(2,1,i) = initsig; %sqrt(initsig)*randn(1,1);
  374.   Pparticle_pfekf{i} = ones(2,2,T);
  375.   for t=1:T,
  376.     Pparticle_pfekf{i}(:,:,t)= diag([P01 P02]); 
  377.   end;
  378. end;  
  379. xparticlePred_pfekf = ones(2,T,N);    % One-step-ahead predicted values of the states.
  380. PparticlePred_pfekf = Pparticle_pfekf;    % One-step-ahead predicted values of P.
  381. yPred_pfekf = ones(2,T,N);          % One-step-ahead predicted values of y.
  382. w = ones(T,N);                      % Importance weights.
  383. muPred_pfekf = ones(2,T);           % EKF O-s-a estimate of the mean of the states.
  384. PPred_pfekf = ones(2,2);            % EKF O-s-a estimate of the variance of the states.
  385. mu_pfekf = ones(2,T,N);             % EKF estimate of the mean of the states.
  386. P_pfekf = ones(2,2,T);              % EKF estimate of the variance of the states.
  387. disp(' ');
  388. tic;                                % Initialize timer for benchmarking
  389. for t=2:T,    
  390.   fprintf('PF-EKF : t = %i / %i  r',t,T);
  391.   fprintf('n')
  392.   
  393.   % PREDICTION STEP:
  394.   % ================ 
  395.   % We use the EKF as proposal.
  396.   for i=1:N,
  397.     muPred_pfekf(:,t) = feval('bsffun',xparticle_pfekf(:,t-1,i),t);
  398.     Jx = eye(2);                                 % Jacobian for ffun.
  399.     PPred_pfekf = Q_pfekf + Jx*Pparticle_pfekf{i}(:,:,t-1)*Jx'; 
  400.     yPredTmp = feval('bshfun',muPred_pfekf(:,t),u(:,t),t);
  401.     % COMPUTE THE JACOBIAN:
  402.     St  = u(1,t);              % Index price.
  403.     tm  = u(2,t);              % Time to maturity.
  404.     r   = muPred_pfekf(1,t);   % Risk free interest rate.
  405.     sig = muPred_pfekf(2,t);   % Volatility.  
  406.     d1 = (log(St) + (r+0.5*(sig^2))*tm ) / (sig * (tm^0.5));
  407.     d2 = d1 - sig * (tm^0.5);  
  408.     % Differentials of call price
  409.     dcsig = St * sqrt(tm) * exp(-d1^2) / sqrt(2*pi);
  410.     dcr   = tm * exp(-r*tm) * normcdf(d2);
  411.     % Differentials of put price
  412.     dpsig = dcsig;
  413.     dpr   = -tm * exp(-r*tm) * normcdf(-d2);
  414.     Jy = [dcr dpr; dcsig dpsig]'; % Jacobian for bshfun.
  415.     % APPLY THE EKF UPDATE EQUATIONS:
  416.     M = R_pfekf + Jy*PPred_pfekf*Jy';                  % Innovations covariance.
  417.     K = PPred_pfekf*Jy'*inv(M);                        % Kalman gain.
  418.     mu_pfekf(:,t,i) = muPred_pfekf(:,t) + K*(y(:,t)-yPredTmp); % Mean of proposal.
  419.     P_pfekf(:,:,t) = PPred_pfekf - K*Jy*PPred_pfekf;           % Variance of proposal.
  420.     xparticlePred_pfekf(:,t,i) = mu_pfekf(:,t,i) + sqrtm(P_pfekf(:,:,t))*randn(2,1);
  421.     PparticlePred_pfekf{i}(:,:,t) = P_pfekf(:,:,t);
  422.   end;
  423.   % EVALUATE IMPORTANCE WEIGHTS:
  424.   % ============================
  425.   % For our choice of proposal, the importance weights are give by:  
  426.   for i=1:N,
  427.     yPred_pfekf(:,t,i) = feval('bshfun',xparticlePred_pfekf(:,t,i),u(:,t),t);        
  428.     lik = exp(-0.5*(y(:,t)-yPred_pfekf(:,t,i))'*inv(R)*(y(:,t)-yPred_pfekf(:,t,i)) ) + 1e-99;
  429.     prior = exp(-0.5*(xparticlePred_pfekf(:,t,i)- xparticle_pfekf(:,t-1,i))'*inv(Q) * (xparticlePred_pfekf(:,t,i)-xparticle_pfekf(:,t-1,i) ))+ 1e-99;
  430.     proposal = inv(sqrt(det(PparticlePred_pfekf{i}(:,:,t)))) * exp(-0.5*(xparticlePred_pfekf(:,t,i)-mu_pfekf(:,t,i))'*inv(PparticlePred_pfekf{i}(:,:,t)) * (xparticlePred_pfekf(:,t,i)-mu_pfekf(:,t,i)))+ 1e-99;
  431.     w(t,i) = lik*prior/proposal;      
  432.   end;  
  433.   w(t,:) = w(t,:)./sum(w(t,:));                % Normalise the weights.
  434.   
  435.   % SELECTION STEP:
  436.   % ===============
  437.   % Here, we give you the choice to try three different types of
  438.   % resampling algorithms. Note that the code for these algorithms
  439.   % applies to any problem!
  440.   if resamplingScheme == 1
  441.     outIndex = residualR(1:N,w(t,:)');        % Residual resampling.
  442.   elseif resamplingScheme == 2
  443.     outIndex = systematicR(1:N,w(t,:)');      % Systematic resampling.
  444.   else  
  445.     outIndex = multinomialR(1:N,w(t,:)');     % Multinomial resampling.  
  446.   end;
  447.   xparticle_pfekf(:,t,:) = xparticlePred_pfekf(:,t,outIndex); % Keep particles with
  448.                                                               % resampled indices.
  449.   for i=1:N,
  450.     Pparticle_pfekf{i} = PparticlePred_pfekf{outIndex(i)};  
  451.   end;
  452. end;   % End of t loop.
  453. time_pfekf = toc;
  454. %%%%%%%%%%%%%%%  PERFORM SEQUENTIAL MONTE CARLO  %%%%%%%%%%%%%%%%%%%%%
  455. %%%%%%%%%%%%%%%  ======== UKF proposal ========  %%%%%%%%%%%%%%%%%%%%%
  456. % INITIALISATION:
  457. % ==============
  458. xparticle_pfukf = ones(2,T,N);      % These are the particles for the estimate
  459.                                     % of x. Note that there's no need to store
  460.                                     % them for all t. We're only doing this to
  461.                                     % show you all the nice plots at the end.
  462. Pparticle_pfukf = cell(N,1);        % Particles for the covariance of x.
  463. %Initialization
  464. for i=1:N,
  465.   xparticle_pfukf(1,1,i) = initr;   % sqrt(initr)*randn(1,1);
  466.   xparticle_pfukf(2,1,i) = initsig; % sqrt(initsig)*randn(1,1);
  467.   Pparticle_pfukf{i} = ones(2,2,T);
  468.   for t=1:T,
  469.     Pparticle_pfukf{i}(:,:,t) = diag([P01_ukf P02_ukf]);
  470.   end
  471. end  
  472. xparticlePred_pfukf = ones(2,T,N);       % One-step-ahead predicted values of the states.
  473. PparticlePred_pfukf = Pparticle_pfukf;   % One-step-ahead predicted values of P.
  474. yPred_pfukf = ones(2,T,N);               % One-step-ahead predicted values of y.
  475. w = ones(T,N);                           % Importance weights.
  476. muPred_pfukf = ones(2,T);                % EKF O-s-a estimate of the mean of the states.
  477. PPred_pfukf = ones(2,2);                 % EKF O-s-a estimate of the variance of the states.
  478. mu_pfukf = ones(2,T,N);                  % EKF estimate of the mean of the states.
  479. P_pfukf = ones(2,2,T);                   % EKF estimate of the variance of the states.
  480. error=0;
  481. disp(' ');
  482. tic;
  483. if (1),
  484. for t=2:T,    
  485.   fprintf('PF-UKF : t = %i / %i  r',t,T);
  486.   fprintf('n')
  487.   
  488.   % PREDICTION STEP:
  489.   % ================ 
  490.   % We use the UKF as proposal.
  491.   for i=1:N,
  492.     % Call Unscented Kalman Filter
  493.     [mu_pfukf(:,t,i),P_pfukf(:,:,t)]=ukf(xparticle_pfukf(:,t-1,i),Pparticle_pfukf{i}(:,:,t-1),u(:,t),Q_pfukf,'ukf_bsffun',y(:,t),R_pfukf,'ukf_bshfun',t,alpha,beta,kappa);
  494.     xparticlePred_pfukf(:,t,i) = mu_pfukf(:,t,i) + sqrtm(P_pfukf(:,:,t))*randn(2,1);
  495.     PparticlePred_pfukf{i}(:,:,t) = P_pfukf(:,:,t);
  496.     
  497.   end;
  498.   % EVALUATE IMPORTANCE WEIGHTS:
  499.   % ============================
  500.   % For our choice of proposal, the importance weights are give by:  
  501.   for i=1:N,
  502.     yPred_pfukf(:,t,i) = feval('bshfun',xparticlePred_pfukf(:,t,i),u(:,t),t);
  503.     lik = exp(-0.5*(y(:,t)-yPred_pfukf(:,t,i))'*inv(R)*(y(:,t)-yPred_pfukf(:,t,i)) ) + 1e-99;
  504.     prior = exp(-0.5*(xparticlePred_pfukf(:,t,i)- xparticle_pfukf(:,t-1,i))'*inv(Q) * (xparticlePred_pfukf(:,t,i)-xparticle_pfukf(:,t-1,i) ))+ 1e-99;    
  505.     proposal = inv(sqrt(det(PparticlePred_pfukf{i}(:,:,t)))) * exp(-0.5*(xparticlePred_pfukf(:,t,i)-mu_pfukf(:,t,i))'*inv(PparticlePred_pfukf{i}(:,:,t)) * (xparticlePred_pfukf(:,t,i)-mu_pfukf(:,t,i)))+ 1e-99;    
  506.     
  507.     w(t,i) = lik*prior/proposal;      
  508.   end;  
  509.   w(t,:) = w(t,:)./sum(w(t,:));                % Normalise the weights.
  510.   
  511.   % SELECTION STEP:
  512.   % ===============
  513.   % Here, we give you the choice to try three different types of
  514.   % resampling algorithms. Note that the code for these algorithms
  515.   % applies to any problem!
  516.   if resamplingScheme == 1
  517.     outIndex = residualR(1:N,w(t,:)');        % Residual resampling.
  518.   elseif resamplingScheme == 2
  519.     outIndex = systematicR(1:N,w(t,:)');      % Systematic resampling.
  520.   else  
  521.     outIndex = multinomialR(1:N,w(t,:)');     % Multinomial resampling.  
  522.   end;
  523.   xparticle_pfukf(:,t,:) = xparticlePred_pfukf(:,t,outIndex); % Keep particles with
  524.                                               % resampled indices.
  525.   for i=1:N,       
  526.     Pparticle_pfukf{i} = PparticlePred_pfukf{outIndex(i)};
  527.   end
  528.   
  529. end;   % End of t loop.
  530. end
  531. time_pfukf = toc;
  532. % Compute posterior mean predictions:
  533. yPFEKFmeanC=zeros(1,T);
  534. yPFEKFmeanP=zeros(1,T);
  535. for t=1:T,
  536.   yPFEKFmeanC(t) = mean(yPred_pfekf(1,t,:));
  537.   yPFEKFmeanP(t) = mean(yPred_pfekf(2,t,:));  
  538. end;  
  539. yPFUKFmeanC=zeros(1,T);
  540. yPFUKFmeanP=zeros(1,T);
  541. for t=1:T,
  542.   yPFUKFmeanC(t) = mean(yPred_pfukf(1,t,:));
  543.   yPFUKFmeanP(t) = mean(yPred_pfukf(2,t,:));  
  544. end;  
  545. errorcTrivial(expr) = norm(C(104:204)-C(103:203));
  546. errorpTrivial(expr) = norm(P(104:204)-P(103:203));
  547. errorcEKF(expr) =norm(C(104:204)-yPred(1,104:204));
  548. errorpEKF(expr) =norm(P(104:204)-yPred(2,104:204));
  549. errorcUKF(expr) =norm(C(104:204)-yPred_ukf(1,104:204));
  550. errorpUKF(expr) =norm(P(104:204)-yPred_ukf(2,104:204));
  551. errorcPF(expr) =norm(C(104:204)-yPFmeanC(104:204));
  552. errorpPF(expr) =norm(P(104:204)-yPFmeanP(104:204));
  553. errorcPFEKF(expr) =norm(C(104:204)-yPFEKFmeanC(104:204));
  554. errorpPFEKF(expr) =norm(P(104:204)-yPFEKFmeanP(104:204));
  555. errorcPFUKF(expr) =norm(C(104:204)-yPFUKFmeanC(104:204));
  556. errorpPFUKF(expr) =norm(P(104:204)-yPFUKFmeanP(104:204));
  557. disp(' ');
  558. disp(['Experiment ' num2str(expr) ' of ' num2str(no_of_experiments) ' : Mean square errors sqrt(sum((errors).^2))']);
  559. disp('------------------------------------------------------------');
  560. disp(' ');
  561. disp(['Trivial call   = ' num2str(errorcTrivial(expr))]);
  562. disp(['EKF call       = ' num2str(errorcEKF(expr))]);
  563. disp(['UKF call       = ' num2str(errorcUKF(expr))]);
  564. disp(['PF call        = ' num2str(errorcPF(expr))]);
  565. disp(['PF-EKF call    = ' num2str(errorcPFEKF(expr))]);
  566. disp(['PF-UKF call    = ' num2str(errorcPFUKF(expr))]);
  567. disp(['Trivial put    = ' num2str(errorpTrivial(expr))]);
  568. disp(['EKF put        = ' num2str(errorpEKF(expr))]);
  569. disp(['UKF put        = ' num2str(errorpUKF(expr))]);
  570. disp(['PF put         = ' num2str(errorpPF(expr))]);
  571. disp(['PF-EKF put     = ' num2str(errorpPFEKF(expr))]);
  572. disp(['PF-UKF put     = ' num2str(errorpPFUKF(expr))]);
  573. figure(9)
  574. bti=20;
  575. lw=2;
  576. clf;
  577. subplot(211)
  578. p0=plot(bti:T,y(1,bti:T),'k-o','linewidth',lw); hold on;
  579. p1=plot(bti:T,yPFmeanC(bti:T),'m','linewidth',lw);
  580. p2=plot(bti:T,yPFEKFmeanC(bti:T),'r','linewidth',lw);
  581. p3=plot(bti:T,yPFUKFmeanC(bti:T),'b','linewidth',lw); hold off;
  582. ylabel('Call price','fontsize',15);
  583. legend([p0 p1 p2 p3],'Actual price','PF prediction','PF-EKF prediction','PF-UKF prediction');
  584. v=axis;
  585. axis([bti T v(3) v(4)]);
  586. subplot(212)
  587. p0=plot(bti:T,y(2,bti:T),'k-o','linewidth',lw); hold on;
  588. p1=plot(bti:T,yPFmeanP(bti:T),'m','linewidth',lw);
  589. p2=plot(bti:T,yPFEKFmeanP(bti:T),'r','linewidth',lw);
  590. p3=plot(bti:T,yPFUKFmeanP(bti:T),'b','linewidth',lw); hold off;
  591. ylabel('Put price','fontsize',15);
  592. legend([p0 p1 p2 p3],'Actual price','PF prediction','PF-EKF prediction','PF-UKF prediction');
  593. xlabel('Time (days)','fontsize',15)
  594. v=axis;
  595. axis([bti T v(3) v(4)]);
  596. zoom on;
  597. end   % END OF MAIN LOOP
  598. % CALCULATE MEAN AND VARIANCE OF EXPERIMENT RESULTS
  599. % means
  600. errorcTrivial_mean = mean(errorcTrivial);
  601. errorcEKF_mean     = mean(errorcEKF);
  602. errorcUKF_mean     = mean(errorcUKF);
  603. errorcPF_mean      = mean(errorcPF);
  604. errorcPFEKF_mean   = mean(errorcPFEKF);
  605. errorcPFUKF_mean   = mean(errorcPFUKF);
  606. errorpTrivial_mean = mean(errorpTrivial);
  607. errorpEKF_mean     = mean(errorpEKF);
  608. errorpUKF_mean     = mean(errorpUKF);
  609. errorpPF_mean      = mean(errorpPF);
  610. errorpPFEKF_mean   = mean(errorpPFEKF);
  611. errorpPFUKF_mean   = mean(errorpPFUKF);
  612. % variances
  613. errorcTrivial_var = var(errorcTrivial);
  614. errorcEKF_var     = var(errorcEKF);
  615. errorcUKF_var     = var(errorcUKF);
  616. errorcPF_var      = var(errorcPF);
  617. errorcPFEKF_var   = var(errorcPFEKF);
  618. errorcPFUKF_var   = var(errorcPFUKF);
  619. errorpTrivial_var = var(errorpTrivial);
  620. errorpEKF_var     = var(errorpEKF);
  621. errorpUKF_var     = var(errorpUKF);
  622. errorpPF_var      = var(errorpPF);
  623. errorpPFEKF_var   = var(errorpPFEKF);
  624. errorpPFUKF_var   = var(errorpPFUKF);
  625. disp(' ');
  626. disp('Mean and Variance of MSE ');
  627. disp('-------------------------');
  628. disp(' ');
  629. disp(['Trivial call   : ' num2str(errorcTrivial_mean) ' (' num2str(errorcTrivial_var) ')']);
  630. disp(['EKF call       : ' num2str(errorcEKF_mean) ' (' num2str(errorcEKF_var) ')']);
  631. disp(['UKF call       : ' num2str(errorcUKF_mean) ' (' num2str(errorcUKF_var) ')']);
  632. disp(['PF call        : ' num2str(errorcPF_mean) ' (' num2str(errorcPF_var) ')']);
  633. disp(['PF-EKF call    : ' num2str(errorcPFEKF_mean) ' (' num2str(errorcPFEKF_var) ')']);
  634. disp(['PF-UKF call    : ' num2str(errorcPFUKF_mean) ' (' num2str(errorcPFUKF_var) ')']);
  635. disp(['Trivial put    : ' num2str(errorpTrivial_mean) ' (' num2str(errorpTrivial_var) ')']);
  636. disp(['EKF put        : ' num2str(errorpEKF_mean) ' (' num2str(errorpEKF_var) ')']);
  637. disp(['UKF put        : ' num2str(errorpUKF_mean) ' (' num2str(errorpUKF_var) ')']);
  638. disp(['PF put         : ' num2str(errorpPF_mean) ' (' num2str(errorpPF_var) ')']);
  639. disp(['PF-EKF put     : ' num2str(errorpPFEKF_mean) ' (' num2str(errorpPFEKF_var) ')']);
  640. disp(['PF-UKF put     : ' num2str(errorpPFUKF_mean) ' (' num2str(errorpPFUKF_var) ')']);
  641. figure(10);
  642. subplot(211);
  643. p1=semilogy(errorcTrivial,'k','linewidth',lw); hold on;
  644. p2=semilogy(errorcEKF,'y','linewidth',lw);
  645. p3=semilogy(errorcUKF,'g','linewidth',lw);
  646. p4=semilogy(errorcPF,'m','linewidth',lw);
  647. p5=semilogy(errorcPFEKF,'r','linewidth',lw);
  648. p6=semilogy(errorcPFUKF,'b','linewidth',lw); hold off;
  649. legend([p1 p2 p3 p4 p5 p6],'trivial','EKF','UKF','PF','PF-EKF','PF-UKF');
  650. ylabel('MSE','fontsize',12);
  651. xlabel('experiment','fontsize',12);
  652. title('CALL Options Mean Prediction Error','fontsize',14);
  653. subplot(212);
  654. p1=semilogy(errorpTrivial,'k','linewidth',lw); hold on;
  655. p2=semilogy(errorpEKF,'y','linewidth',lw);
  656. p3=semilogy(errorpUKF,'g','linewidth',lw);
  657. p4=semilogy(errorpPF,'m','linewidth',lw);
  658. p5=semilogy(errorpPFEKF,'r','linewidth',lw);
  659. p6=semilogy(errorpPFUKF,'b','linewidth',lw); hold off;
  660. legend([p1 p2 p3 p4 p5 p6],'trivial','EKF','UKF','PF','PF-EKF','PF-UKF');
  661. ylabel('MSE','fontsize',12);
  662. xlabel('experiment','fontsize',12);
  663. title('PUT Options Mean Prediction Error','fontsize',14);