summaryrefslogtreecommitdiffstats
path: root/bandit.R
diff options
context:
space:
mode:
Diffstat (limited to 'bandit.R')
-rw-r--r--bandit.R79
1 files changed, 79 insertions, 0 deletions
diff --git a/bandit.R b/bandit.R
index a1b9703..3482daa 100644
--- a/bandit.R
+++ b/bandit.R
@@ -80,3 +80,82 @@ for( i in 1:100){
indexchange$Ticker.del[i]))
}
}
+
+n.stocks <- ncol(P)
+N <- nrow(P)
+current.wealth <- 1
+w <- rep(1/n.stocks,n.stocks)
+dP <- apply(P,2,diff)
+L <- rep(0,n.stocks)
+V <- 0
+W <- w
+pnl <- 0
+for(i in 1:(N-1)){
+ r <- dP[i,]/as.numeric(P[i,])
+ #r <- c(r,-r)
+ pnl <- cbind(pnl,current.wealth*crossprod(w,r))
+ current.wealth <- 1+sum(pnl)
+ L <- rbind(L,-r)
+ V <- V+crossprod(w,r^2)
+ T <- 2/3*sqrt(log(N)/V)
+ #w <- exp(-T*(apply(1+L,2,prod)-1))
+ w <- exp(-T*colSums(L))
+ w <- w/sum(w)
+ W <- rbind(W,w)
+ if(i%%10==0){
+ cat(current.wealth,sep="\n")
+ }
+}
+
+price2return <- function(x){
+ diff(x)/x[-length(x)]
+}
+#number of shares implementations
+tc <- 0.005+0.02
+days <- nrow(data.bus)
+init.capital <- 1000000
+tickers <- memb(sp500.tickers,add,as.Date(time(data.bus)[1]))
+tickers.index <- which(sp500.tickers.extended%in%tickers)
+n.stocks <- length(tickers)
+w <- rep(0,length(sp500.tickers.extended))
+w[tickers.index] <- rep(1/n.stocks,n.stocks)
+N <- round((capital*w)/as.numeric(data.bus[1,tickers.index]))
+dP <- apply(data.bus,2,diff)
+L <- rep(0,n.stocks)
+V <- 0
+W <- w
+pnl <- 0
+tcvec <- sum(N)*tc
+for(i in 1:days){
+ tickers <- memb(sp500.tickers,add,as.Date(time(data.bus)[1]))
+ tickers.index <- which(sp500.tickers.extended%in%tickers)
+ r <- dP[i,]/as.numeric(data.bus[i,])
+ pnl <- cbind(pnl,crossprod(N,dP[i,]))
+ capital <- init.capital+sum(pnl)-sum(tcvec)
+ L <- rbind(L,-r)
+ V <- V+crossprod(w,r^2)
+ T <- 2/3*sqrt(log(days)/V)
+ #w <- exp(-T*(apply(1+L,2,prod)-1))
+ w <- exp(-T*colSums(L))
+ w <- w/sum(w)
+ newN <- round((capital*w)/as.numeric(data.bus[(i+1),tickers.index]))
+ tcvec <- c(tcvec,sum(abs(newN-N)*tc))
+ N <- newN
+ if(i%%10==0){
+ cat(capital,sep="\n")
+ }
+}
+
+fixed.rebal <- function(P,delta){
+ init.capital <- 1
+ dP <- apply(P,2,diff)
+ capital <- init.capital
+ pnl <- c()
+ for(i in 1:(nrow(P)-1)){
+ r <- dP[i,]/P[i,]
+ pnl <- c(pnl,capital*crossprod(delta,r))
+ capital <- init.capital+sum(pnl)
+ }
+ return( pnl )
+}
+