Programming performance/KrassiVanguelov R

From HaskellWiki
< Programming performance
Revision as of 21:11, 7 April 2007 by Krassi (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Language: R

Experience level: Advanced

Time: 22 minutes


 theData=read.table(file="gspc.txt", sep=" ", comment.char='#')
 prices=rev(theData[,5])
 pctReturns=diff(prices)/prices[-length(prices)]*100
 cash=10000
 portfolio=list(shares=numeric(0),prices=numeric(0))
 trades = mapply(
               function(price,ret){
                   if(ret <= -3) {
                       portfolio$shares <<- c(portfolio$shares,0.1*cash/price);
                       portfolio$prices <<- c(portfolio$prices,price);
                       cash <<- 0.9*cash
                   }
                   else if(ret > 0){ 
                       sells = which(price/portfolio$prices >= 1.06); 
                       if(length(sells)>0){
                           cash <<- cash + sum(portfolio$shares[sells]*price); 
                           portfolio$shares <<- portfolio$shares[-sells]; 
                           portfolio$prices <<- portfolio$prices[-sells]
                       }    
                   }
               }
               , prices[-1]
               , pctReturns
 )
 cash = cash + sum(portfolio$shares*prices[length(prices)])
 cat(cash, '\n')