|
| 1 | +#!/usr/bin/env python |
| 2 | +# stocksim.py |
| 3 | +# |
| 4 | +# Stock market simulator. This simulator creates stock market |
| 5 | +# data and provides it in several different ways: |
| 6 | +# |
| 7 | +# 1. Makes periodic updates to a log file stocklog.dat |
| 8 | +# |
| 9 | +# The purpose of this module is to provide data to the user |
| 10 | +# in different ways in order to write interesting Python examples |
| 11 | + |
| 12 | +import math |
| 13 | +import time |
| 14 | +import threading |
| 15 | +try: |
| 16 | + import queue |
| 17 | +except ImportError: |
| 18 | + import Queue as queue |
| 19 | + |
| 20 | +history_file = "dowstocks.csv" |
| 21 | + |
| 22 | +# Convert a time string such as "4:00pm" to minutes past midnight |
| 23 | +def minutes(tm): |
| 24 | + am_pm = tm[-2:] |
| 25 | + fields = tm[:-2].split(":") |
| 26 | + hour = int(fields[0]) |
| 27 | + minute = int(fields[1]) |
| 28 | + if hour == 12: |
| 29 | + hour = 0 |
| 30 | + if am_pm == 'pm': |
| 31 | + hour += 12 |
| 32 | + return hour*60 + minute |
| 33 | + |
| 34 | +# Convert time in minutes to a format string |
| 35 | +def minutes_to_str(m): |
| 36 | + frac,m = math.modf(m) |
| 37 | + hours = m//60 |
| 38 | + minutes = m % 60 |
| 39 | + seconds = frac * 60 |
| 40 | + return "%02d:%02d.%02.f" % (hours,minutes,seconds) |
| 41 | + |
| 42 | +# Read the stock history file as a list of lists |
| 43 | +def read_history(filename): |
| 44 | + result = [] |
| 45 | + for line in open(filename): |
| 46 | + str_fields = line.strip().split(",") |
| 47 | + fields = [eval(x) for x in str_fields] |
| 48 | + fields[3] = minutes(fields[3]) |
| 49 | + result.append(fields) |
| 50 | + return result |
| 51 | + |
| 52 | +# Format CSV record |
| 53 | +def csv_record(fields): |
| 54 | + s = '"%s",%0.2f,"%s","%s",%0.2f,%0.2f,%0.2f,%0.2f,%d' % tuple(fields) |
| 55 | + return s |
| 56 | + |
| 57 | +class 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): |
| 115 | + self.time += dt |
| 116 | + if self.index < (len(self.history) - 2): |
| 117 | + while self.index < (len(self.history) - 2) and self.time >= self.history[self.index+1][3]: |
| 118 | + self.index += 1 |
| 119 | + self.update() |
| 120 | + |
| 121 | + def make_record(self): |
| 122 | + return [self.name,round(self.price,2),self.date,minutes_to_str(self.time),round(self.change,2),self.open,round(self.high,2), |
| 123 | + round(self.low,2),self.volume] |
| 124 | + |
| 125 | +class MarketSimulator(object): |
| 126 | + def __init__(self): |
| 127 | + self.stocks = { } |
| 128 | + self.prices = { } |
| 129 | + self.time = 0 |
| 130 | + self.observers = [] |
| 131 | + def register(self,observer): |
| 132 | + self.observers.append(observer) |
| 133 | + |
| 134 | + def publish(self,record): |
| 135 | + for obj in self.observers: |
| 136 | + obj.update(record) |
| 137 | + def add_history(self,filename): |
| 138 | + hist = read_history(filename) |
| 139 | + for record in hist: |
| 140 | + if record[0] not in self.stocks: |
| 141 | + self.stocks[record[0]] = StockTrack(record[0]) |
| 142 | + self.stocks[record[0]].add_data(record) |
| 143 | + |
| 144 | + def reset(self,time): |
| 145 | + self.time = time |
| 146 | + for s in list(self.stocks.values()): |
| 147 | + s.reset(time) |
| 148 | + |
| 149 | + # Run forever. Dt is in seconds |
| 150 | + def run(self,dt): |
| 151 | + for s in self.stocks: |
| 152 | + self.prices[s] = self.stocks[s].price |
| 153 | + self.publish(self.stocks[s].make_record()) |
| 154 | + while self.time < 1000: |
| 155 | + for s in self.stocks: |
| 156 | + self.stocks[s].incr(dt/60.0) # Increment is in minutes |
| 157 | + if self.stocks[s].price != self.prices[s]: |
| 158 | + self.prices[s] = self.stocks[s].price |
| 159 | + self.publish(self.stocks[s].make_record()) |
| 160 | + time.sleep(dt) |
| 161 | + self.time += (dt/60.0) |
| 162 | + |
| 163 | + |
| 164 | +class BasicPrinter(object): |
| 165 | + def update(self,record): |
| 166 | + print(csv_record(record)) |
| 167 | + |
| 168 | +class LogPrinter(object): |
| 169 | + def __init__(self,filename): |
| 170 | + self.f = open(filename,"w") |
| 171 | + def update(self,record): |
| 172 | + self.f.write(csv_record(record)+"\n") |
| 173 | + self.f.flush() |
| 174 | + |
| 175 | +m = MarketSimulator() |
| 176 | +m.add_history(history_file) |
| 177 | +m.reset(minutes("9:30am")) |
| 178 | +m.register(BasicPrinter()) |
| 179 | +m.register(LogPrinter("stocklog.csv")) |
| 180 | +m.run(1) |
| 181 | + |
| 182 | + |
| 183 | + |
0 commit comments