#!/usr/bin/python

from historicaldata import *
import random

def evaluate(brian):
	h = HistoricalData()
	reals = 10.0
	btc = 0.0
	
	datasize = len(h.rawdata)-1-10
	for i in range(1,datasize):
		hist = h.deltahistory(i)
		act = brian.activate(hist)
		
		if act > 0:
			if reals > 0:
				if random.random() < act*10:
					btc = h.bid(i+9,reals)
					reals = 0
		elif act < 0:
			if btc > 0:
				if random.random() < -act*10:
					reals += h.ask(i+9,btc)
					btc = 0
	
	if btc > 0:
		if random.random() < -act*10:
			reals += h.ask(datasize,btc)
			btc = 0
	
	return reals
		

def staggeredevaluate(brian,debug=False):
	h = HistoricalData()
	reals = 10.0
	btc = 0.0
	
	datasize = len(h.rawdata)-1-100
	for i in range(1,datasize):
		if debug:
			print "Time: %d" % (i+99)
		hist = h.staggeredDeltaHistory(i)
		act = brian.activate(hist)
		if debug:
			print "Bot thinks: %f" % (act)
		
		if act > 0:
			if reals > 0:
				if random.random() < act:
					btc = h.bid(i+99,reals)
					reals = 0
					if debug:
						print "Bid"
		elif act < 0:
			if btc > 0:
				if random.random() < -act:
					reals += h.ask(i+99,btc)
					btc = 0
					if debug:
						print "Ask"
	
	if btc > 0:
		if random.random() < -act*10:
			reals += h.ask(datasize,btc)
			btc = 0
	
	return reals


def staggeredlog(brian):
	h = HistoricalData()
	reals = 10.0
	btc = 0.0
	log = []
	
	datasize = len(h.rawdata)-1-100
	for i in range(1,datasize):
		hist = h.staggeredDeltaHistory(i)
		act = brian.activate(hist)
		
		if act > 2.5:
			if reals > 0:
				btc = h.bid(i+99,reals)
				reals = 0
				log.append("%i - %s bid -> %f btc" % (i,h.rawdata[i+99].split(",")[0],btc))
		elif act < -2.5:
			if btc > 0:
				reals += h.ask(i+99,btc)
				btc = 0
				log.append("%i - %s ask -> $%f" % (i,h.rawdata[i+99].split(",")[0],reals))
	
	if btc > 0:
		reals += h.ask(datasize,btc)
		btc = 0
		log.append("\n final ask -> $%f" % (reals))
	
	return reals,log
		
def staggereddeltalog(brian,dataset="line2.csv"):
	h = HistoricalData(dataset)
	reals = 10.0
	btc = 0.0
	log = []
	
	datasize = len(h.rawdata)-1-100
	for i in range(1,datasize):
		hist = h.staggeredDeltaHistory(i)
		act = brian.activate(hist)
		
		if act > 1.0:
			if reals > 0:
				if random.random() < act-1.0:
					btc = h.bid(i+99,reals)
					reals = 0
					log.append("%i - %s bid -> %f btc" % (i,h.rawdata[i+99].split(",")[0],btc))
		elif act < -1.0:
			if btc > 0:
				if random.random() < (-act)-1.0:
					reals += h.ask(i+99,btc)
					btc = 0
					log.append("%i - %s ask -> $%f" % (i,h.rawdata[i+99].split(",")[0],reals))
	
	if btc > 0:
		reals += h.ask(datasize,btc)
		btc = 0
		log.append("final ask -> $%f" % (reals))
	
	return reals,log
		
if __name__ == "__main__":
	from staggeredbrain import *
	sb = StaggeredBrain()
	staggeredevaluate(sb,True)
