block by timelyportfolio 3190664

r websocket for interaction with d3

Full Screen

rwebsocket-Axys-d3.r

#I deserve no credit for this code; most comes from the example provided at http://bigcomputing.com/PerformanceAnalytics.R

# R/websockets example
if(any(is.na(packageDescription('caTools'))))
  stop("This demo requires the caTools package.\nRun install.packages('caTools') to install it.\n\n")
if(any(is.na(packageDescription('PerformanceAnalytics'))))
  stop("This demo requires the PerformanceAnalytics package.\nRun install.packages('PerformanceAnalytics') to install it.\n\n")
library('websockets')
library('caTools')
library('quantmod')
library('PerformanceAnalytics')
require('RJSONIO')

#w = createContext(webpage=static_text_service(htmldata))
w = createContext()

# Set up an established (initialization) callback
g = function(DATA, WS, ...)
{
  websocket_write("hello",WS)
  print("established connection")
}
setCallback("established",g, w)

# Set up a receive callback
f = function(DATA, WS, ...)
{
  #get data sent from websocket
  d = tryCatch(rawToChar(DATA),error=function(e) "")
  #convert JSON message to data.frame and eventually xts
  perf <- fromJSON(d)
  perf.df<- as.data.frame(matrix(unlist(fromJSON(d)),ncol=3,byrow=TRUE),stringsAsFactors=TRUE)
  perf.df[,2:3] <- apply(perf.df[,2:3],MARGIN=2,as.numeric)/100
  #name columns
  colnames(perf.df) <- c("date","portfolio","sp500")
  #get as xts so convert dates from %m/%d/%Y to %Y-%m-%d
  perf.xts <- as.xts(perf.df[,2:NCOL(perf.df)],order.by=as.Date(perf.df[,1],format="%m/%d/%Y"))
  drawdown <- Drawdowns(perf.xts)
  drawdown.matrix <- as.matrix(cbind(index(drawdown),coredata(drawdown)))
  colnames(drawdown.matrix) <- c("date",colnames(drawdown))
  drawdown.matrix[,"date"] <- format(as.Date(drawdown.matrix[,"date"]),"%m/%d/%Y")
  #this will send the dataframe so an object of arrays
  #websocket_write(toJSON(df),WS);
  #try with matrix which sends an array of objects (d3 prefers and handles better)
  websocket_write(toJSON(drawdown.matrix),WS)
  #websocket_write("got your data; thanks",WS)
}
setCallback("receive",f, w)

#daemonize(w)


cat("\nThe web service will run until <CTRL>+C is pressed.\n")
cat("Open your local web browser to http://localhost:7681\n")
while(TRUE) {
  service(w, timeout=1000L)
  #old service(w)
  #old Sys.sleep(0.05)
}
rm(w)
gc()