Programming performance/TimN Python
< Programming performance(Difference between revisions)
Latest revision as of 03:45, 7 March 2007
- Language: Python
- Skill: Advanced. I've been coding in Python for several years and use it on a regular basis for work and fun. I've written several large programs in Python.
- Time: Less than 30 minutes. I did not keep track of time well and this is just an estimate.
- Notes: The noisy flag can be used to adjust the amount of output.
noisy = True
def lines(fn) :
return (l.strip() for l in file(fn))
def fields(fn) :
return (l.split(' ') for l in lines(fn) if l != '#')
def closes(fn) :
return ((fs,float(fs[-1])) for fs in fields(fn))
def delta(p, oldp) :
return (p - oldp) / oldp
def strategy(ps) :
cash = 10000.0 held = 0.0 queue =  p = 0.0 lastp = 1.0 for n,(date,p) in enumerate(ps) : if delta(p, lastp) < -0.03 : # down 3%, buy 10% cost = 0.10 * cash quant = cost / p queue.append((quant, p, n)) cash -= cost held += quant if noisy : print date, "buy %.2f at $%.2f ($%.2f)" % (quant, p, cost) while len(queue) > 0 : # check triggers quant, buyp, n2 = queue[-1] if delta(p, buyp) > 0.06 : # up 6%, sell queue.pop() cost = quant * p cash += cost held -= quant if noisy : print date, "sell %.2f at $%.2f ($%.2f)" % (quant, p, cost) else : break lastp = p if noisy : print queue cash += held * p return cash
- data is stored in reverse order.
series = list(closes('gspc')) series.reverse() val = strategy(series) print '$%.2f' % val