import sys, csv, mosek
from minrisk import minrisk
from sharpe import sharpe

def streamprinter(x): sys.stdout.write(x); sys.stdout.flush()
env = mosek.Env(); env.set_Stream (mosek.streamtype.log, streamprinter)

def newtask():
  task = env.Task(0,0)
  task.set_Stream(mosek.streamtype.log, streamprinter)
  return task

def main ():
  f_itrT = open('../data/sp500-ret.csv','rb')  # expected returns
  rT     = csv.reader(f_itrT, quoting=csv.QUOTE_NONNUMERIC).next()
  f_itG  = open('../data/sp500-Gqr.csv','rb')  # covariance factor
  itG    = csv.reader(f_itG, quoting=csv.QUOTE_NONNUMERIC)
  G      = [[(i,v) for i,v in enumerate(row) if v!=0.0] for row in itG]
  n = len(rT);  w0 = [1.0/n]*n

  [start, stop, num] = [1.0, 1.005, 21]
  RET = [start + float(i)/(num-1)*(stop-start) for i in range(num)]

  RISK = [0.0]*len(RET)
  for i in range(len(RET)):
    [_,RISK[i]] = minrisk(newtask(), G, rT, RET[i], w0)

  rf = 1.0005
  [_,risk2,ret2] = sharpe(newtask(), G, rT, w0, rf)
  sharperatio = (ret2 - rf*sum(w0))/risk2

  for item in zip(RET,RISK): 
    print item
  print 'sharpe:\n', sharperatio
  print (ret2,risk2)

if __name__ == '__main__': 
  main()
