[R] simulation
Berend Hasselman
bhh at xs4all.nl
Thu Jan 3 20:52:38 CET 2013
On 03-01-2013, at 17:40, Simone Gogna <singletonthebest at msn.com> wrote:
> Dear R users,
> suppose we have a random walk such as:
>
> v_t+1 = v_t + e_t+1
>
> where e_t is a normal IID noise pocess with mean = m and standard deviation = sd and v_t is the fundamental value of a stock.
>
> Now suppose I want a trading strategy to be:
>
> x_t+1 = c(v_t – p_t)
>
> where c is a costant.
> I know, from the paper where this equations come from (Farmer and Joshi, The price dynamics of common trading strategies, 2001) that the induced price dynamics is:
>
> r_t+1 = –a*r_t + a*e_t + theta_t+1
>
> and
>
> p_t+1 = p_t +r_t+1
>
> where r_t = p_t – p_t-1 , e_t = v_t – v_t-1 and a = c/lambda (lambda is another constant).
>
> How can I simulate the equations I have just presented?
> I have good confidence with R for statistical analysis, but not for simulation therefore I apologize for my ignorance.
> What I came up with is the following:
>
> ##general settings
> c<-0.5
> lambda<-0.3
> a<-c/lambda
> n<-500
>
> ## Eq.12 (the v_t random walk)
> V_init_cond<-0
> Et<-ts(rnorm(n+100,mean=0,sd=1))
> Vt<-Et*0
> Vt[1]<-V_init_cond+Et[1]
> for(i in 2:(n+100)) {
> Vt[i]<-Vt[i-1]+Et[i]
> }
> Vt<-ts(Vt[(length(Vt)-n+1):length(Vt)])
> plot(Vt)
>
> ## Eq.13 (the strategy)
> Xt_init_cond<-0
> Xt<-Xt_init_cond*0
> Xt[2]<-c(Vt[1]-Pt[1])
> for(i in 2:(n)){
> Xt[i]<-c(Vt[i-1]-Pt[i-1])
> }
> Xt<-ts(Xt[(length(Xt)-n+1):length(Xt)])
> plot(Xt)
>
> ## Eq. 14 (pice dynamics)
> P_init_cond<-0
> Pt<-Rt*0
> Pt[1]<-P_init_cond+Rt[1]
> for(i in 2:(n+100)) {
> Pt[i]<-Pt[i-1]+Rt[i]
> }
> Pt<-ts(Pt[(length(Pt)-n+1):length(Pt)])
> plot(Pt)
> Rt_init_cond<-0
> Rt<-Rt_init_cond*0
> Rt[2]<- -a*Rt[1]+a*Et[1]+e[2]
> for(i in 2:(n)){
> Rt[i]<- -a*Rt[i-1]+a*Et[i-1]+e[i]
> }
> Rt<-ts(Rt[(length(Rt)-n+1):length(Rt)])
> plot(Rt)
>
> I don’t think the code above is correct, and I don’t even know if this is the approach I have to take.
> Any suggestion is warmly appreciated.
>
Do not use "c" as a user variable. It is an R provided function.
You have a formulae such as
Xt[2]<-c(Vt[1]-Pt[1])
for(i in 2:(n)){
Xt[i]<-c(Vt[i-1]-Pt[i-1])
c is not doing here what you want.
I assume you meant to multiply as in
Xt[2]<-c*(Vt[1]-Pt[1])
for(i in 2:(n)){
Xt[i]<-c*(Vt[i-1]-Pt[i-1])
So call this constant cpar or something similar.
Where has e been defined?
If you reorder your equations in such a way that all initial conditions are computed first in the correct order
then you simulation loops could be condensed into a single loop such as
for(i in 2:(n+100)) {
Vt[i] <- Vt[i-1]+Et[i]
Rt[i] <- -a*Rt[i-1]+a*Et[i-1]+e[i]
Pt[i] <- Pt[i-1]+Rt[i]
Xt[i] <- cpar*(Vt[i-1]-Pt[i-1])
}
If I am correct.
Berend
More information about the R-help
mailing list