MCPcopy Create free account
hub / github.com/dabeaz-course/practical-python / StockTrack

Class StockTrack

Work/Data/stocksim.py:55–121  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

53 return s
54
55class StockTrack(object):
56 def __init__(self,name):
57 self.name = name
58 self.history = []
59 self.price = 0
60 self.time = 0
61 self.index = 0
62 self.open = 0
63 self.low = 0
64 self.high = 0
65 self.volume = 0
66 self.initial = 0
67 self.change = 0
68 self.date = ""
69 def add_data(self,record):
70 self.history.append(record)
71 def reset(self,time):
72 self.time = time
73 # Sort the history by time
74 self.history.sort(key=lambda t:t[3])
75 # Find the first entry who's time is behind the given time
76 self.index = 0
77 while self.index < len(self.history):
78 if self.history[self.index][3] > time:
79 break
80 self.index += 1
81 self.open = self.history[0][5]
82 self.initial = self.history[0][1] - self.history[0][4]
83 self.date = self.history[0][2]
84 self.update()
85 self.low = self.price
86 self.high = self.price
87
88 # Calculate interpolated value of a given field based on
89 # current time
90 def interpolate(self,field):
91 first = self.history[self.index][field]
92 next = self.history[self.index+1][field]
93 first_t = self.history[self.index][3]
94 next_t = self.history[self.index+1][3]
95 try:
96 slope = (next - first)/(next_t-first_t)
97 return first + slope*(self.time - first_t)
98 except ZeroDivisionError:
99 return first
100
101 # Update all computed values
102 def update(self):
103 self.price = round(self.interpolate(1),2)
104 self.volume = int(self.interpolate(-1))
105 if self.price < self.low:
106 self.low = self.price
107 if self.price >= self.high:
108 self.high = self.price
109 self.change = self.price - self.initial
110
111 # Increment the time by a delta
112 def incr(self,dt):

Callers 1

add_historyMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected