setwd("D:/Dropbox/Temp/Gold")
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 = 200000
for(k in 1:2E6)
{
    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
    }
}

save(file="best_orderseq.dat",best_orderseq)
