Financial derivative and energy market valuation

651 126 0
Financial derivative and energy market valuation

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

FINANCIAL DERIVATIVE AND ENERGY MARKET VALUATION FINANCIAL DERIVATIVE AND ENERGY MARKET VALUATION Theory and Implementation in Matlab R Michael Mastro U.S Naval Research Lab Washington, DC A JOHN WILEY & SONS, INC., PUBLICATION Copyright © 2013 by John Wiley & Sons, Inc All rights reserved Published by John Wiley & Sons, Inc., Hoboken, New Jersey Published simultaneously in Canada No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning, or otherwise, except as permitted under Section 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 750-4470, or on the web at www.copyright.com Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permission Limit of Liability/Disclaimer of Warranty: While the publisher and author have used their best efforts in preparing this book, they make no representations or warranties with respect to the accuracy or completeness of the contents of this book and specifically disclaim any implied warranties of merchantability or fitness for a particular purpose No warranty may be created or extended by sales representatives or written sales materials The advice and strategies contained herein may not be suitable for your situation You should consult with a professional where appropriate Neither the publisher nor author shall be liable for any loss of profit or any other commercial damages, including but not limited to special, incidental, consequential, or other damages For general information on our other products and services or for technical support, please contact our Customer Care Department within the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002 Wiley also publishes its books in a variety of electronic formats Some content that appears in print may not be available in electronic formats For more information about Wiley products, visit our web site at www.wiley.com MATLAB® is a trademark of The MathWorks, Inc and is used with permission The MathWorks does not warrant the accuracy of the text or exercises in this book This book’s use or discussion of MATLAB® software or related products does not constitute endorsement or sponsorship by The MathWorks of a particular pedagogical approach or particular use of the MATLAB® software Library of Congress Cataloging-in-Publication Data: Mastro, Michael A., 1975– Financial derivative and energy market valuation : theory and implementation in Matlab® / Michael Mastro p cm Includes bibliographical references and index ISBN 978-1-118-48771-6 (cloth) Derivative securities Energy derivatives MATLAB I Title HG6024.A3M3774 2012 332.64’57–dc23 2012031825 Printed in the United States of America 10 CONTENTS Preface vii Financial Models Jump Models 35 Options 65 Binomial Trees 105 Trinomial Trees 131 Finite Difference Methods 167 Kalman Filter 231 Futures and Forwards 245 Nonlinear and Non-Gaussian Kalman Filter 295 10 Short-Term Deviation/Long-Term Equilibrium Model 349 11 Futures and Forwards Options 359 12 Fourier Transform 397 13 Fundamentals of Characteristic Functions 459 14 Application of Characteristic Functions 467 15 Levy Processes 505 16 Fourier-Based Option Analysis 547 17 Fundamentals of Stochastic Finance 585 18 Affine Jump-Diffusion Processes 605 Index 645 v PREFACE Energy markets and their associated financial derivatives are characterized by sudden jumps, mean reversion, and stochastic volatility These aspects necessitate sophisticated models to properly describe even a subset of these traits Moreover, the implementation of these models itself requires advanced numerical methods This book establishes the fundamental mathematics and builds up all necessary statistical, quantitative, and financial theories A number of theoretical topics are expanded, including the Fourier transform, moment generating functions, characteristic functions, and finite and infinite activity Levy processes such as the alpha stable, tempered stable, gamma, variance gamma, inverse Gaussian, and normal inverse Gaussian processes Applied mathematics such as the fast Fourier transform and the fractional fast Fourier transform are developed and used to generate statistical distributions and for option pricing On the basis of this knowledge, state-of-the-art quantitative financial models are developed without the need to refer external sources Seminal works are derived and implemented, including the Black–Scholes, Black, Ornstein–Uhlenbeck, Merton Gaussian jump diffusion, Kou double exponential jump diffusion, and Heston stochastic volatility models Nevertheless, these models cannot capture the true behavior of the energy markets The influential two-factor stochastic convenience yield model and the short-term long-term model are derived and implemented It is shown that adding jumps to these models can be done in a rather ad hoc manner; however, a thorough discussion of the affine transform formalism is presented This provides an elegant framework to augment jumps to the two-factor models or develop similar jump-diffusion models To fit these models and display their predictive power, a particular focus is made in developing and utilizing the Kalman filter For linear models with Gaussian noise, the Kalman filter finds an optimal recursive solution with very little computational burden For the nonlinear and non-Gaussian models developed in this book, we build up and exploit the extended, Gauss–Hermite, unscented, Monte Carlo, and particle Kalman filters As suggested by the title, a major vein of this book is the implementation of these models Availability of working code of modern financial models is limited, and the implementation is typically only discussed in an abstract sense This book details the necessary steps for implementation and displays the working code The Matlab® vii viii PREFACE environment was selected because it is broadly available and is simple to port to other popular environments including C++ and C# In addition, Matlab provides refined graphing routines that allow our code to focus on the relevant quantitative and financial concepts Michael Mastro Financial Models 1.1 INTRODUCTION The movement of financial assets and products generally displays some type of expected return, even over a short period This expected return trends at a predictable rate that may be positive, indicating growth; negative, indicating a decline; or zero Additionally, there are random movements that are individually unpredictable; however, the general distribution of these fluctuations is predictable based on historical movements The common approach to model randomness is to assume a single- or multi-component Gaussian process The generalized format to describe a time-dependent stochastic process is dSt = α(S, t)dt + σ (S, t)dWt , where the drift α and volatility σ are functions of time t and asset price S, and Wt is a Wiener process If the drift α(S, t) = μ and volatility σ are constants, then the process dSt = μ dt + σ dWt is known as arithmetic Brownian motion This process by itself states that the stock price S will increase (or decrease) without bound at a rate that is not dependent on the current stock price Clearly, this does not describe the typical behavior for an asset, but modified versions of arithmetic motion are useful in finance and are revisited later in the text 1.2 GEOMETRIC BROWNIAN MOTION A more appropriate description of a stock price process is that the movements in the stock are proportional to the value of the stock A specific description is that the overall drift, α(S, t) = μSt , is the product of an expected return μ and the current asset price St Adding a stochastic movement that is also proportional to the current price level gives dSt = μS dt + σ S dWt , Financial Derivative and Energy Market Valuation: Theory and Implementation in Matlab®, First Edition Michael Mastro © 2013 John Wiley & Sons, Inc Published 2013 by John Wiley & Sons, Inc FINANCIAL MODELS which is the well known geometric Brownian motion process A crude discrete approximation of the stochastic differential equation for geometric Brownian motion given by St =μ t +σ St Wt is only valid over short time intervals This form does highlight that the percentage change in the stock price SS over a short √ time interval is normally distributed with mean μ t and standard deviation σ t, where μ is the drift and σ is the volatility The shorthand for a normal distribution is √ S ∼ N μ t, σ t S The variance of this stochastic return is proportional to the time interval, var SS = σ t (Hull, 2006) One benefit of geometric Brownian motion is that negative asset prices are not possible because any price change is proportional to the current price Bankruptcy could drive an asset price down to but not past the natural absorbing barrier at zero (Chance, 1994) The discrete approximation of the geometric Brownian motion stochastic equation is composed of a trend (or expectation) term E dS S = μ dt and an uncertainty (of deviation) term The uncertainty term is given by the Wiener increment √ dWt = εt dt, with E(dWt ) = 0, where ε is the standard normal distribution It turns out that the variance of dWt is equal to the time interval dt The variance of the Wiener increment was found by evaluating var(dWt ) = E[dWt − μdWj ]2 = E(dWt ) − E(dWt )2 = E(dWt2 ) √ The expected value of (dWt )2 is, by definition, E[(dWt )2 ] = E[(εt dt)2 ] (Chance, 2005) Pulling the dt factor out of the expectation gives E(dWt2 ) = E(εt2 dt) = (E(εt2 ))dt To evaluate the E(εt2 ) term requires the computational formula for the variance var(εt ) = E[(εt − E(εt ))2 ] = E[(εt2 − 2εt E(εt ) + E(εt ))2 ] var(εt ) = E(εt2 ) − 2E(εt )E(εt ) + E(εt )2 = E(εt2 ) − 2E(εt )2 + E(εt )2 var(εt ) = E(εt2 ) − E(εt )2 → E(εt2 ) = var(εt ) − E(εt )2 GEOMETRIC BROWNIAN MOTION The variance term of a standard normal variable is one, var(εt ) = The expected value of a standard normal variable E(εt ) and the square of the expected value E(εt )2 are zero Therefore, E(εt2 ) = var(εt ) − E(εt )2 = − 0, the expected value of a squared standard normal variable is one The value for the expectation of the Wiener increment squared is given by E(dWt2 ) = (E(εt2 ))dt = dt This important result states that the square of a Wiener process equals the time interval, dt = dWt2 In other words, the Weiner process is unpredictable but the square of the Weiner process is predictable t The percentage price change of the stochastic representation of dS St is normally distributed because the stochastic differential equation, written as dSt = μ dt + σ dWt , St is a linear transformation of the normally distributed variable dWt The relative St t t = + dS return S0 +dS S0 S0 = S0 over a time period T is the product of the intervening price changes as displayed by S ST S S S = t−1 T , S0 S0 S1 St−2 St−1 i where each increment in relative return SSi−1 is capable of being further subdivided in time A logarithm of the product converts the product series into a summation series as given by ln ST S0 = ln S1 S0 + ln S2 S1 + · · · + ln St−1 St−2 + ln ST St−1 The central limit theorem states that the summation of a large number of identically distributed and independent random variables, each with finite mean and variance, will be approximately normally distributed (Rice, 1995) 1.2.1 Lognormal Stochastic Differential Equation The insight of the previous paragraph provides a motivation to recast the geometric Brownian motion dS = μS dt + σ S dW , FINANCIAL MODELS as a lognormal diffusion stochastic differential equation The alteration is accomplished by using the function G = ln S, and its derivatives ∂G ∂ 2G ∂G = = =− 2 ∂S S ∂S S ∂t Application of Ito’s lemma gives Infinitesimally small→0 ∂G ∂G ∂ 2G ∂ 2G (dt)2 (dS) + dS + dt + ∂S ∂S ∂t ∂t 1 dG = dS − (dS)2 + S S2 1 dG = (μS dt + σ S dW ) − (μS dt + σ S dW )2 S S2 dG = (μ dt + σ dW ) ⎛ ⎞ Infinitesimally dG = dW =dt Infinitesimally small→0 1 ⎜ ⎜ 2 2 − ⎜σ S dW + μσ S dt dW + α S 2 S2 ⎝ small→0 dt ⎟ ⎟ ⎟ ⎠ dG = (μ dt + σ dW ) − σ dt ⎛ =η ⎞ ⎜ 2⎟ ⎟ dG = ⎜ ⎝μ − σ ⎠ dt + σ dW , where we have introduced a lognormal return drift factor, η, which is the continuously compounded return A solution to the log return stochastic differential equation is found by integrating dGu = η dt + σ dWu The deterministic drift term can be integrated similar to an ordinary differential equation The σ coefficient is taken as a time-invariant constant, which greatly simplifies the stochastic integral to t σ dWu = σ (Wt − W0 ) = σ (Wt − 0), APPENDIX 635 Sajko, W.N (2005) A Comparision of Forward Default Rates for Mean-Reverting-Jumps and CIR Affine Models, McMaster University, Department of Mathematics and Statistics Schwartz, E, Smith, J.E (2000) Short-Term Variations and Long-Term Dynamics in Commodity Prices, Management Science 46, 893 Villaplana, P (2003) Pricing Power Derivatives: A Two-Factor Jump-Diffusion Approach, Universitat Pompeu Fabra APPENDIX Code: Affine3Model function Affine3Model(data); % Affine3Model Implements term Affine Jump-Diffusion model % using Kalman filter via fminsearch % Jump-Diffusion Model and approach is based on % N.K Nomikos, O.A Soldatos(2010)Energy Policy 38,5671 % who applied model to Nordpool Electricity Prices % % % % % % % % % Their model is unique in that the jump model (Y) is an independent third component in their affine model F=f(t)+exp(Chi+Epsilon+Y) where Chi is the short term deviation mean reversion dChi=-kappaChi*Chi*dt + sigmaChi*dWchi Epsilon is the long term drift arithmetic Brownian motion dEps=(muEps-0.5sigmaEpsˆ2)dt + sigmaEps*dWeps Chi is the jump process + mean reversion dY=-kappaY*Y*dt + J(muJ,sigmaJˆ2)dq(lambda) % % % % % Nomikos suggests pre-filtering the jumps from the Spot Data to calculate the jump process parameters and to extract the jumps from the Spot Data The Kalman filter is feed a deseaonalied set of futures and jumpless spot data % For the electricity market, Nomikos also added a seasonal % dependency into the jump parameters These features will % be ignored in this analysis of the natural gas market % % % % f(t) is a seasonality parameter: the graphs below show that seasonality is surprising small compared to the price of impact of supply changes (not shown) for the natural gas data of 1997–2012 global tau global Obs 636 AFFINE JUMP-DIFFUSION PROCESSES global global global global global knownParam latent time S MRvec % Price Data 'ngSpotFut.dat' contains columns of time, spot % price, 1, 2, 3, and month Futures price data where the % futures settlement is at the end of the particular month if (nargin == 0), data=load('ngSpotFut.dat'); end [Col,Rows] = size(data) if (Col>Rows) disp('flip') data=data'; %flip S=(column) to S'=(rows) temp=Col; Col=Rows; Rows=temp end time = data(1,:)+1997; S = data(2,:); F = data(3:Col,:); SMat=S'*ones (1,Col-2); offset=4; % adjust if start date not at beginning of month % and end date not a beginning of month Days=1:Rows; % Simplify by assuming 21(=252/12) trading days per (every) % month tau=mod(-Days-offset,21)'; taustart=tau(1) % S 1M-Fut 2M-Fut 3M-Fut 4M-Fut tau = [tau*0, tau, tau+21, tau+2*21, tau+3*21]/252; % Check Seasonality in Natural Gas Data from 1997 to 2012 options=optimset('MaxIter',200);%'Display','iter', SeasonPar =[-0.12 0.6816 -0.15 (mean(S))] % Initial Guess % Nomikos suggests deterministic fit of historic spot date % with two sinusoidal functions Function Season.m contains % SeasonVal = amp1*sin(2pi(t+phase1)) + amp2*sin(2pi(t+phase2)) SeasonPar=fminsearch('SineFit',SeasonPar,options); amp1=SeasonPar(1) phase1=SeasonPar(2) amp2=SeasonPar(3) phase2=SeasonPar(4) LongRunMean=SeasonPar(5) APPENDIX 637 SeasonVal=Season(SeasonPar,time); % Substrate Seasonal Oscillations from Spot and Futures S=S-SeasonVal; F(1,:)=F(1,:)-Season(SeasonPar,time+tau(1)); F(2,:)=F(2,:)-Season(SeasonPar,time+tau(2)); F(3,:)=F(3,:)-Season(SeasonPar,time+tau(3)); F(4,:)=F(4,:)-Season(SeasonPar,time+tau(4)); %% Calculate Standard Deviation as if logarithmic returns % of log(St/S0) are normally distributed LogDelta=log(S(2:end))-log(S(1:end-1)); % lenghtLD=length(LogDelta); M1=mean(LogDelta); %Technically this is the first raw moment StanDev = std(LogDelta) neg3sd=M1-3*StanDev; pos3sd=M1+3*StanDev; % Returns +/- standard deviations followed by strong % reversion are considered jump 'Y spikes' by Nomikos % Jumps without reversion are not considered 'Y spikes' % Nomikos Suggests Repeating until all data +/- sd NoJumpS=S; % Loop below will remove spikes JumpS=zeros(1,Rows)*NaN; % Loop below will add spikes LogDeltaNJ=zeros(1,Rows); % Return Vector with Spikes removed JumpInd=[]; % Will Contain Spike Indices JumpReversionVec = []; % Will Contain Spike Reversion JumpSizeVec= []; % Will Contain Spike Size for i= 2:Rows-1 LogDeltaNJ(i)=log(NoJumpS(i))-log(NoJumpS(i-1)); % LogDeltaNJ(i+1)=log(NoJumpS(i+1))-log(NoJumpS(i)); % if (((LogDeltaNJ(i)(pos3sd/2))) ||(LogDeltaNJ(i) > pos3sd ) && (LogDeltaNJ(i+1) < (neg3sd/2))) JumpS(i) = S(i); NoJumpS(i)=NoJumpS(i-1); JumpInd=[JumpInd i]; JumpReversionVec =[JumpReversionVec LogDeltaNJ(i+1)]; JumpSizeVec= [JumpSizeVec LogDeltaNJ(i)]; %else % JumpS(i)=NaN; end end kappaY=sqrt(mean(JumpReversionVec.ˆ2)) lambda=length(JumpInd)/ time(end) muJ=mean(abs(JumpSizeVec)) 638 AFFINE JUMP-DIFFUSION PROCESSES sigmaJ=sqrt(mean(JumpSizeVec.ˆ2)) figure plot (time, SeasonVal+LongRunMean, time, S,'k ', time, JumpS, 'bs',time, NoJumpS,'g-') title ('Daily NYMEX Natural Gas Spot Price') xlabel ('Time [Year]'); ylabel('Price [Dollars per Thousand Cubic Feet]'); axis tight legend('Deterministic Seasonality', 'Deseasonalized Price', 'Spikes', 'w/o Spikes') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Obs=log([NoJumpS; F(1:end,:)]); % Observations Data for Kalman % Check for and replace missing Data (= NaN) [a,b]=find(isnan(Obs)); for loop = 1:length(a) Obs(a(loop),b(loop))=Obs(a(loop),b(loop)-1); end R=diag(1e-3*ones(1,Col-1)); % Observation Noise Covariance knownParam(1) knownParam(2) knownParam(3) knownParam(4) dt = 1/252; knownParam(5) knownParam(6) knownParam(7) = = = = kappaY; lambda; muJ; sigmaJ; %Pre-Estimated Jump Process = dt; % e.g., 1/252 for daily = Col-1; % Col-1= Spot + # of Futures = Rows; % number of time points %Supply initial guess values muChiGuess = 0.95; kappaChiGuess = 3; sigChiGuess = 0.34; muEGuess = 0; kappaEGuess = 0.27; sigEGuess = 0.32; rhoGuess = 0.0; phiChiGuess=0.65; RvarGuess=1e-3; param=zeros(7,1); param(1)=muChiGuess; APPENDIX 639 param(2)=kappaChiGuess; param(3)=sigChiGuess; param(4)=muEGuess; param(5)=kappaEGuess; param(6)=sigEGuess; param(7)=rhoGuess; param(8)=phiChiGuess; param(9:13)=RvarGuess; % diagonal variance terms % fminsearch for (negative) maximum likelihood of parameters % as calculated by Kalman filtration of all observed data options=optimset('Display','iter','MaxIter',100);%options=[];% pnew=fminsearch('A3Mloglikelihoodfn',param,options); muChi = pnew(1) kappaChi = pnew(2) sigChi = pnew(3) muE = pnew(4) kappaE = pnew(5) sigE = pnew(6) rho = pnew(7) phiChi = pnew(8) fprintf(1, 'Measurement Error Variance Terms \n'); disp (pnew(9:13)); %%% Plot Spot Data with Jumps removed Vs % Calculated Equilibirum (Epsilon) % and Deviation (Chi) + Equilibirum (Epsilon) figure plot (time, log(NoJumpS), ' ', time, (latent(:,1)+latent(:,2)),'-.', time, (latent(:,2)), time, (latent(:,1)),':') legend('Spot w/o Spikes', '(\chi+\epsilon)', '(Equilibrium:\epsilon)','(Deviation:\chi)') xlabel ('Time [Year]'); ylabel('Log Price'); title ('Fit to Daily Natural Gas Log Price') axis tight; %%%%%%%%% Predict Futures Curve ChiCurrent=latent(end,1) EpsCurrent=latent(end,2) YCurrent=JumpS(end) if (isnan(YCurrent)), YCurrent=0;, end FutT=((0:251)/252); djump=FutT*0; maxj=5; jcount=linspace(0,maxj,maxj); deltaTau=FutT/maxj; 640 AFFINE JUMP-DIFFUSION PROCESSES for j=1:maxj TauChop=(j-0.5)*deltaTau; djump=djump+(exp(muJ*exp(-kappaY*TauChop) +0.5*sigmaJˆ2*exp(-2*kappaY*TauChop))-1); end djump=lambda*djump.*deltaTau; AT= (sigChiˆ2/(4*kappaChi))*(1-exp(-2.*kappaChi.*FutT)) -((phiChi-rho*sigE*sigChi)/kappaChi)*(1-exp(-kappaChi.* FutT)) +muE*FutT; exp(EpsCurrent + ChiCurrent) FutF=exp(EpsCurrent + ChiCurrent*exp(-kappaChi*FutT) + YCurrent*exp(-kappaY*FutT)+ + djump + AT); timeS=time(end) FutT=FutT+time(end); FutFpSeason=FutF+Season(SeasonPar,FutT); figure plot(FutT, FutF, ' ' ,FutT, FutFpSeason) title ('Predicted Natural Gas Futures Curve') xlabel ('Time [Year]'); ylabel('Price [Dollars per Thousand Cubic Feet]'); axis tight legend ('Deseaonalized Futures', 'Futures Curve') figure ribbon (time, MRvec) title ('Kalman Filter Measurement Residual') ylabel ('Time [Year]'); axis tight zlabel ('Log Price Residual'); legend ('Spot', '1M Futures', '2M Futures', '3M Futures', '4M Futures') end Code: A3Mloglikelihoodfn function LikeSum = A3Mloglikelihoodfn(param)%,knownParam) % A3Mloglikelihoodfn returns negative of % log Maximum Likelihood Estimation of Component Affine % Model via Kalman Filter Jumps were pre-filtered in % calling program APPENDIX global global global global global 641 tau Obs knownParam latent MRvec kappaY = knownParam(1); lambda = knownParam(2); muJ = knownParam(3); sigJ = knownParam(4); dt = knownParam(5); nObs=knownParam(6); nsamples=knownParam(7); muChi = param(1); kappaChi = param(2); sigChi = param(3); muE = param(4); kappaE = param(5); sigE = param(6); rho = param(7); phiChi =param(8); Rvar=param(9:13); % Variance terms on diagonal of R=diag(Rvar); % Measurement Noise Covariance % Kalman filter equations are described by % x(t) = M*x(t-1) + C + w w~N(0,Q) % z = Obs = Hx + d + v v~N(0,R) H = ones(nObs,2); % H + d = Observation Model % H(:,1) = exp(-kappaChi*tau(1,:)); % % Measurement Noise Covariance is small but non-zero %R = diag(0.1*ones(nObs,1)); % Nomikos suggests Zero Measurement Noise for Spot % but here we will simply make smaller % R(1,1)=0.001; % % % % % State Transition Matrix M Chi (short term variation) exponential decay (exp(kappaChi*dt)) Epsilon (long term rate) drifts at rate (muE-0.5*sigEˆ2*dt) Linear M + Constant C = State Transition Model M = [exp(-kappaChi*dt), 0; 0, 1]; C = [0; muE-0.5*sigEˆ2*dt]; % Q = State Space Process Variance % include if-else if searching for process w/ kappaChi==0 642 AFFINE JUMP-DIFFUSION PROCESSES if (kappaChi==0) Q=sig*sig*(dt); Q(1,1)=sigChi*sigChi*dt; Q(1,2)=rho*sigE*sigChi*dt; Q(2,1)=Q(1,2); Q(2,2)=sigE*sigE*dt; else Q(1,1)=sigChi*sigChi*( (1-exp(-2.*kappaChi.*dt)) / (2.*kappaChi)); Q(1,2)=rho*sigE*sigChi*( (1-exp(-kappaChi.*dt)) / kappaChi); Q(2,1)=Q(1,2); Q(2,2)=sigE*sigE*dt; end LikeSum=0.5*nsamples*log(2*pi); % Create Crude Initial Estimation of Latent Variable x=[Obs(1,1)-Obs(end,1) ;Obs(end,1)]; %Initialize Covariance to Unconditional Variance of State %Process P=Q; %%%% Step Forward in Time %%%%%%%%%%%%%%%%%%%%% %approach avoids saving every a-priori and a-posteriori %variable for i=2:nsamples H(:,1) = exp(-kappaChi*tau(i,:)); % Second column of Observation Model (that % multiples Epsilon) is always equal to unity % H(:,2) % = ones(nObs,1); % Integrate Jump Component by summing Rectangles djump=zeros(1,nObs); maxj=5; jcount=linspace(0,maxj,maxj); deltaTau=tau(i,:)/maxj; for j=1:maxj % tau mid-point of jth rectangle TauChop=(j-0.5)*deltaTau; % jth Heigth at mid-point djump=djump+(exp(muJ*exp(-kappaY*TauChop) +0.5*sigJˆ2*exp(-2*kappaY*TauChop))-1); end djump=lambda*djump.*deltaTau; % lambda = jump frequency % (Linear) H + (Constant) d = Observation Model maps hidden % (latent) variables X, eps into observation space APPENDIX 643 d=(sigChiˆ2/(4*kappaChi))*(1-exp(-2.*kappaChi.*tau(i,:))) -((phiChi-rho*sigE*sigChi)/kappaChi) *(1-exp(-kappaChi.*tau(i,:))) + muE*tau(i,:) + djump; % Predict x = M*x+C; %x(k|k-1) State Prediction P = M*P*M'+ Q; %P(k|k-1) Covariance Prediction %Update MR = Obs(:,i) - H*x-d';%Measurement (Innovation) Residual V = H*P*H' + R; %Residual (Innovation) Covariance K = P*H' * inv(V); %Kalman Gain %x(k|k) State Correction based on observation Residual x = x + K*(MR); P = P - K*H*P; %P(k|k) Covariance Correction % negative of maximum likelihood gives minimum for fminsearch LikeSum=LikeSum+0.5*log(det(V))+0.5*MR'*(V\MR); MRvec(i,:) = MR; % store globally to plot later latent(i,:)=x; % store globally to plot later end % Crude technique to prevent unreasonable parameters if ((sigE

Ngày đăng: 20/03/2018, 13:51

Tài liệu cùng người dùng

Tài liệu liên quan