Hello,

I have to build a function that takes a time serie and calculate the momentum. 
For each date of the serie, I have to build a loop to calculate it using the 
last few data.

My problem is that it takes one minute to compute and I need to run this 
function very often.
I would like to vectorize it, as much as possible. 

Can somebody help me? I have read the 
http://www.burns-stat.com/pages/Tutor/R_inferno.pdf tutorial but it seems I am 
not smart enough to vectorize this.

here is the code of my function:



momentum = function(price,H,N,HL) {

indicator = price                                            #creates the empty 
vector for the indicator
indicator[,1]=0

if ((H/N)==floor(H/N)) {                                    #Checks if length 
of subperiods is an integer
    
    for (i in 1:(length(indicator)-H)) {
        ph=last(price,H+1)                                #Horizon time data 
list
        horizonPerformance=as.numeric(last(ph))/as.numeric(first(ph))-1    
#Performance over the time horizon
        for (j in 1:N) {
            phj=last(first(ph,(N-j+1)*H/N+1),H/N+1)                #subperiod 
data list
            periodPerf=as.numeric(last(phj))/as.numeric(first(phj))-1    
#Performance over period j
            if (periodPerf*horizonPerformance>0)                #checks 
consistency with time horizon perf 
            
indicator[length(indicator)-i+1,1]=indicator[length(indicator)-i+1,1]+sign(periodPerf)
        }
        price=last(price,-1)                                #shift the data list
    }

}

return(indicator)
}

_________________________________________________________________
Inédit ! Des Emoticônes Déjantées! Installez les dans votre Messenger ! 

        [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to