HaskellWiki

Haskell | Wiki community | Recent changes
Random page | Special pages

 

Not logged in
Log in | Help

Programming performance/TimN Python

< Programming performance

Code

#!/usr/bin/python

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[0] != '#')
def closes(fn) :
    return ((fs[0],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

Retrieved from "http://haskell.org/haskellwiki/Programming_performance/TimN_Python"

This page has been accessed 488 times. This page was last modified 03:45, 7 March 2007. Recent content is available under a simple permissive license.