Skip to content

Instantly share code, notes, and snippets.

@falsetru
Created April 11, 2011 15:22
Show Gist options
  • Save falsetru/913688 to your computer and use it in GitHub Desktop.
Save falsetru/913688 to your computer and use it in GitHub Desktop.
import csv
import re
import datetime
import itertools
def iter_prices(filename):
PATTERN_DIGIT = re.compile(r'\d+')
with open(filename) as f: # HTS-exported data
reader = csv.reader(f)
next(reader)
for row in reader:
date = datetime.date(*map(int, PATTERN_DIGIT.findall(row[0])))
price = int(row[4])
yield date, price
def main(filename):
k5 = 2.0 / (5+1)
k20 = 2.0 / (20+1)
it = iter_prices(filename)
prices = list(itertools.islice((p for d,p in it), 20))
ema5, ema20 = sum(prices[-5:])/5.0, sum(prices[-20:])/20.0
buy_price = 0
initial = balance = 1000000
transaction_cost_rate = 0.00015
pos_prev = 0
stock = 0
y1 = []
y2 = []
for d,price in it:
ema5 = price * k5 + ema5 * (1-k5)
ema20 = price * k20 + ema20 * (1-k20)
#print d,ema5,ema20
pos = cmp(ema5, ema20)
if pos and pos != pos_prev:
pos_prev = pos
if pos > 0:
n = (balance // price)
value = n * price
transaction_cost = int(value * transaction_cost_rate)
balance -= n * price
balance -= transaction_cost
stock += n
print '{0} Buy {1:,} * {2} ({3}) .. {4:,}'.format(
d, price, n, transaction_cost, balance+value)
buy_price = price
elif stock:
value = price * stock
transaction_cost = int(value * transaction_cost_rate)
balance += value
balance -= transaction_cost
n = stock
yn = '+' if price > buy_price else '-'
print '{0} Sell {1:,} * {2} ({3}) .. {4:,} {5}'.format(
d, price, n, transaction_cost, balance, yn)
stock = 0
y1.append(ema5)
y2.append(ema20)
total = balance + stock*price
print 'init. = {0:,}'.format(initial)
print 'total = {0:,} ({1:,} + {2:,})'.format(total, balance, stock*price)
print '{0:+.2%}'.format(float(total) / initial - 1)
#from pylab import *
#plot(y1)
#plot(y2)
#show()
main('a.csv')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment