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

Class StockTrack

Data/stocksim.py:57–123  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

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

Callers 1

add_historyMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected