#------------------------------------------------# # # # week12: Maximieren der Likelihood-Funktion # # fuer das Beispiel 3 # # # #------------------------------------------------# # we have to calculate the log-Likelihood function: # we use 'vectorized' calculation logic of R to make the code # a bit more performant -> code looks a bit less intuitive: logL = function( d , d0 , ret ) { n = length(ret) cumsum_retsquared = cumsum(ret^2) # remove last d elements: cumsum_retsquared_shifted = cumsum_retsquared[-( (n-d+1):n )] # fill in d zeros at the first d places: cumsum_retsquared_shifted = c( rep(0,d) , cumsum_retsquared_shifted ) sum_d_retsquared = cumsum_retsquared - cumsum_retsquared_shifted # start at d0 or d0+1: ret = ret[(d0+1):n] sum_d_retsquared = sum_d_retsquared[d0:(n-1)] vol = sqrt( 1/d * sum_d_retsquared ) # the actual calculation: terms = log(vol) + 1/2*ret^2/vol^2 result = -sum(terms) return(result) } # lets fit to SPX-data: spx = read.table("C:/Users/detlef/OneDrive/hochschule/Vorlesungen/WS2425/WBS/week6/SPX.txt",header=TRUE,sep=";") spx summary(spx) head(spx) S = spx$Adj.Close n=length(S) ret = rep(0,n) for(i in 2:n) { ret[i] = (S[i]-S[i-1])/S[i-1] } par(mfrow=c(2,1)) plot(S,type="l") plot(ret,type="l") plot(log(S/S[1],2),type="l") plot(ret,type="l") d0 = 100 F = rep(0,d0) for(d in 1:d0) { F[d] = logL( d , d0 , ret ) } plot( 1:d0, F ) plot( 5:d0, F[5:d0] ) plot( 10:d0, F[10:d0] ) which.max(F) # d = 24 plot( 10:d0, F[10:d0] ) points( 24 , logL(24,d0,ret) , col="red", pch="X")