forked from theforage/forage-jpmc-swe-task-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0001-Both-python-files-running-smoothly.patch
182 lines (163 loc) · 6.18 KB
/
0001-Both-python-files-running-smoothly.patch
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
From b5b889ec3d2a8348c52181f8b519c10f8750ddf8 Mon Sep 17 00:00:00 2001
From: "THE PENTAGON MOVEMENT." <134065998+KingT5M@users.noreply.github.com>
Date: Mon, 23 Sep 2024 00:58:08 +0300
Subject: [PATCH] Both python files running smoothly.
---
client3.py | 16 ++++++----
server3.py | 86 +++++++++++++++++++++++++++++++++++-------------------
2 files changed, 66 insertions(+), 36 deletions(-)
diff --git a/client3.py b/client3.py
index 5d6d306..4854f81 100644
--- a/client3.py
+++ b/client3.py
@@ -42,9 +42,9 @@ def getDataPoint(quote):
def getRatio(price_a, price_b):
""" Get ratio of price_a and price_b """
""" ------------- Update this function ------------- """
- if (price_b==0):
- return
- return price_a/price_b
+ if (price_b == 0):
+ return None
+ return price_a / price_b
# Main
@@ -52,12 +52,16 @@ if __name__ == "__main__":
# Query the price once every N seconds.
for _ in iter(range(N)):
quotes = json.loads(urllib.request.urlopen(QUERY.format(random.random())).read())
-
- """ ----------- Update to get the ratio --------------- """
prices = {}
for quote in quotes:
stock, bid_price, ask_price, price = getDataPoint(quote)
prices[stock] = price
print("Quoted %s at (bid:%s, ask:%s, price:%s)" % (stock, bid_price, ask_price, price))
- print("Ratio %s" % getRatio(price, price))
+ # Assuming you have stocks 'ABC' and 'DEF'
+ if 'ABC' in prices and 'DEF' in prices:
+ ratio = getRatio(prices['ABC'], prices['DEF'])
+ print("Ratio of ABC to DEF: %s" % ratio)
+ else:
+ print("Not enough stock data to compute ratio.")
+
\ No newline at end of file
diff --git a/server3.py b/server3.py
index 1836de2..22d8b71 100644
--- a/server3.py
+++ b/server3.py
@@ -146,21 +146,31 @@ def order_book(orders, book, stock_name):
#
# Test Data Persistence
-def generate_csv():
+# Declare the file path for the CSV file
+CSV_FILE_PATH = 'c:/Users/T5M/Desktop/JP-MORGAN-JOB SIM/forage-jpmc-swe-task-1/test.csv'
+
+def generate_csv(file_path):
""" Generate a CSV of order history. """
- with open('test.csv', 'wb') as f:
+ with open(file_path, 'w', newline='') as f:
writer = csv.writer(f)
for t, stock, side, order, size in orders(market()):
if t > MARKET_OPEN + SIM_LENGTH:
break
writer.writerow([t, stock, side, order, size])
+def read_csv(file_path):
+ """ Read a CSV of order history into a list. """
+ if os.path.isfile(file_path):
+ with open(file_path, 'rt') as f:
+ reader = csv.reader(f)
+ for row in reader:
+ print(row) # Check the rows being read
+ time, stock, side, order, size = row
+ yield dateutil.parser.parse(time), stock, side, float(order), int(size)
+ else:
+ print(f"CSV file not found at: {file_path}")
+ generate_csv(file_path)
-def read_csv():
- """ Read a CSV or order history into a list. """
- with open('test.csv', 'rt') as f:
- for time, stock, side, order, size in csv.reader(f):
- yield dateutil.parser.parse(time), stock, side, float(order), int(size)
################################################################################
@@ -217,28 +227,33 @@ def get(req_handler, routes):
def run(routes, host='0.0.0.0', port=8080):
- """ Runs a class as a server whose methods have been decorated with
- @route.
- """
-
+ """Runs a class as a server whose methods have been decorated with @route."""
+
class RequestHandler(http.server.BaseHTTPRequestHandler):
def log_message(self, *args, **kwargs):
- pass
+ pass # Suppress logging
def do_GET(self):
get(self, routes)
server = ThreadedHTTPServer((host, port), RequestHandler)
- thread = threading.Thread(target=server.serve_forever)
- thread.daemon = True
- thread.start()
- print('HTTP server started on port 8080')
- while True:
- from time import sleep
- sleep(1)
- server.shutdown()
- server.start()
- server.waitForThread()
+ print(f'HTTP server started on {host} port {port}')
+
+ try:
+ thread = threading.Thread(target=server.serve_forever)
+ thread.daemon = True
+ thread.start()
+
+ while True:
+ from time import sleep
+ sleep(1)
+ except KeyboardInterrupt:
+ print("Server is shutting down...")
+ server.shutdown() # Properly shut down the server
+ thread.join() # Ensure the server thread is properly joined
+ finally:
+ print("Server stopped.")
+
################################################################################
@@ -257,11 +272,15 @@ class App(object):
def __init__(self):
self._book_1 = dict()
self._book_2 = dict()
- self._data_1 = order_book(read_csv(), self._book_1, 'ABC')
- self._data_2 = order_book(read_csv(), self._book_2, 'DEF')
- self._rt_start = datetime.now()
- self._sim_start, _, _ = next(self._data_1)
- self.read_10_first_lines()
+ try:
+ self._data_1 = order_book(read_csv(CSV_FILE_PATH), self._book_1, 'ABC')
+ self._data_2 = order_book(read_csv(CSV_FILE_PATH), self._book_2, 'DEF')
+ self._rt_start = datetime.now()
+ self._sim_start, _, _ = next(self._data_1)
+ self.read_10_first_lines()
+ except StopIteration:
+ print("No data available or data exhausted. Please ensure the CSV has enough entries.")
+
@property
def _current_book_1(self):
@@ -334,7 +353,14 @@ class App(object):
# Main
if __name__ == '__main__':
- if not os.path.isfile('test.csv'):
+ if not os.path.isfile(CSV_FILE_PATH):
print("No data found, generating...")
- generate_csv()
- run(App())
+ generate_csv(CSV_FILE_PATH)
+ else:
+ print(f"CSV file found at: {CSV_FILE_PATH}, proceeding with reading data...")
+ data = read_csv(CSV_FILE_PATH)
+ for d in data:
+ print(d)
+ # Start the HTTP server
+ app = App()
+ run(app) # This will start the server
--
2.42.0.windows.2