#setwd("D:/Dropbox/Temp/Gold")
#setwd("Dropbox/Temp/Gold")
rm(list=ls())
gd = read.csv(file="golddata.csv")
gd = na.omit(gd)
head(gd)
plot(gd$SellBar,type="l")
is.na(gd)

max_totalasset = 0
best_orderseq = NA


objectivefunc = function(gd, orderseq, maxseq, holdgold)
{
  totalasset = 0
  for(i in 1:maxseq)
  {
    #print(orderseq[i])
    #print(gd$SellBar[i])
    #User buys a gold bar
    if(orderseq[i] == "b")
    {
      r = money - gd$SellBar[i]
      if(r>0)
      {
        holdgold = holdgold+1
        money = r
      }
    }
    #User sells a gold bar
    if(orderseq[i] == "s")
    {
      if(holdgold>0)
      {
        r = money + gd$BuyBar[i]
        holdgold = holdgold-1
        money = r
      }
      else
        orderseq[i] = "w" #Fixing unsuitable order
    }
    #current asset
    if(holdgold>0)
    {
      r = gd$BuyBar[i]*holdgold
      totalasset = money +r
      #print(sprintf("Hold(%d),TotalAsset(%d)",holdgold,ta))
    }
  }
  rv = list(totalasset,orderseq,holdgold)
  return(rv)
}



startmoney = 100000
for(k in 1:1E6)
{
    money = startmoney
    holdgold = 0
    totalasset = 0
    maxseq = dim(gd)[1]
    orderseq = sample(c("b","s",'w'),maxseq,replace = TRUE)
    
    rv = objectivefunc(gd,orderseq, maxseq,holdgold)
    totalasset = rv[[1]]
    orderseq = rv[[2]]
    holdgold = rv[[3]]
    
    if(totalasset > max_totalasset)
    {
        gain = (totalasset / startmoney - 1)*100
        print(sprintf("Hold(%d),TotalAsset(%d),(%1.2f%%)",holdgold,totalasset,gain))
        max_totalasset = totalasset
        best_orderseq = orderseq
    }
}

saveRDS(best_orderseq, file="best_orderseq.dat")
best_orderseq = readRDS("best_orderseq.dat")


############################################
##RNN
############################################

#install.packages("rnn")
library("rnn")

difference_value = function(x)
{ 
  length_x = length(x)
  if(length_x<1)
    return(NULL)
  dif = c(x[1],x)

  dif = dif[-(length_x+1)]
  x-dif
  return(x-dif)
}

vdif = difference_value(gd$SellBar)
orderseq = best_orderseq
factor_orderseq = factor(orderseq)
orderseqval = as.numeric(factor_orderseq)
data.frame(vdif,orderseqval)

x = vdif/50
#x = vdif
y = orderseqval

time_x = 10
sample_x = length(x)/time_x
xx = array(x,c(sample_x,time_x))
yy = array(y,c(sample_x,time_x))
xt = array(c(xx),dim=c(dim(xx),1))

yy = array(y,c(sample_x,time_x))
yt = array(c(yy,yy),dim=c(dim(yy),1))

dim(xt)
dim(yt)

maxiter = 200
model = trainr(Y = yt,
               X = xt,
               learningrate = 0.01,
               hidden_dim = 100,
               numepochs = maxiter,
               use_bias = TRUE)

par(mfrow=c(4,1))
plot(as.vector(xt),type='l',xlab='
Epoch',ylab='xt')
plot(colMeans(model$error[,1:maxiter]),type='l',xlab='
Epoch',ylab='Errors')
yp = predictr(model, xt)
plot(as.vector(yt), col = 'black', type='l',
     main = "Actual(b) vs Predicted(r) on Training Data Set",
     ylab = "yt target")
plot(as.vector(yp), type = 'l', col = 'red',ylab="yp predict")

