-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathlib.py
103 lines (68 loc) · 2.15 KB
/
lib.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import numpy as np
import csv
class OutOfMoney(Exception):
pass
class OutOfStock(Exception):
pass
class EndOfFeed(Exception):
pass
class RateGenerator:
def __init__(self):
self._exrate = None
self.step()
def exrate(self):
return self._exrate
def step(self):
pass
class RandomRate(RateGenerator):
def step(self):
self._exrate = np.random.uniform(low=0.5, high=1.5)
class CSVRate(RateGenerator):
def __init__(self, csv_file):
self._rateseq = (row for row in read_csv(csv_file)) # iterator
self.step()
def step(self):
try:
self._exrate = next(self._rateseq)
except StopIteration:
raise EndOfFeed
class DummyExService:
def __init__(self, funds, rate_generator):
self._funds = funds
self._balance = 0
self.rate_generator = rate_generator
def balance(self):
return self._balance
def value(self):
return self._balance * self.exrate()
def funds(self):
return self._funds
def sell(self, value):
stock_qty = min(value / self.exrate(), self._balance)
money_qty = stock_qty * self.exrate()
if self._balance < stock_qty or self._balance == 0:
raise OutOfStock
self._balance -= stock_qty
self._funds += money_qty
return stock_qty
def buy(self, value):
money_qty = min(value, self._funds)
stock_qty = money_qty / self.exrate()
if self._funds < money_qty or self._funds == 0:
raise OutOfMoney
self._funds -= money_qty
self._balance += stock_qty
return stock_qty
def exrate(self):
return self.rate_generator.exrate()
def step_exrate(self):
self.rate_generator.step()
def read_csv(filename='csv/FB.csv'):
with open(filename, newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',', quotechar='"')
history = []
for row in spamreader:
# Date,Open,High,Low,Close,Adj, Close,Volume
if row[1] != 'Open':
history.append(float(row[1]))
return history