[R] how to calculate the return?

Richard.Cotton at hsl.gov.uk Richard.Cotton at hsl.gov.uk
Mon Nov 26 10:23:24 CET 2007


Denver,

>   data is a matrix like this
>          AMR      BS      GE      HR      MO      UK   SP500
> 1974 -0.3505 -0.1154 -0.4246 -0.2107 -0.0758  0.2331 -0.2647
> 1975  0.7083  0.2472  0.3719  0.2227  0.0213  0.3569  0.3720
> 1976  0.7329  0.3665  0.2550  0.5815  0.1276  0.0781  0.2384
> 1977 -0.2034 -0.4271 -0.0490 -0.0938  0.0712 -0.2721 -0.0718
> 1978  0.1663 -0.0452 -0.0573  0.2751  0.1372 -0.1346  0.0656
> 1979 -0.2659  0.0158  0.0898  0.0793  0.0215  0.2254  0.1844
> 1980  0.0124  0.4751  0.3350 -0.1894  0.2002  0.3657  0.3242
> 1981 -0.0264 -0.2042 -0.0275 -0.7427  0.0913  0.0479 -0.0491
> 1982  1.0642 -0.1493  0.6968 -0.2615  0.2243  0.0456  0.2141
> 1983  0.1942  0.3680  0.3110  1.8682  0.2066  0.2640  0.2251

It is perhaps more natural to specify this information as a data frame.

> I want  to calculate the return say AMR,so I use
> re=numeric(10)
> for (i in 2:nrow(data))
>     re[1]=0
>    re[i]=log(data[i]/data[i-1])
> to my surprise, the result is
> > re
>  [1]  0.00000  0.00000  0.00000  0.00000  0.00000  0.00000  0.00000 
0.00000
>  [9]  0.00000 -1.70109

A couple of things:
1. You don't need re[1]=0 inside the loop (or at all, in fact, since 
numeric(10) will give a default value of 0).
2. It would be better to vectorise the code, to avoid the loop altogether.
3. You are looping over elements in the first column of data, which is why 
the log values are zero.

Some better code:
re = c(0, diff(log(data[,"AMR"])))

Regards,
Richie.

Mathematical Sciences Unit
HSL


------------------------------------------------------------------------
ATTENTION:

This message contains privileged and confidential inform...{{dropped:20}}



More information about the R-help mailing list