-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPRDE.py
237 lines (196 loc) · 7.7 KB
/
PRDE.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
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import matplotlib.pyplot as plt
import numpy as np
import csv
import math
import random
import argparse
from BSE import market_session
parser = argparse.ArgumentParser(
description="Run market sessions on BSE",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument("--experiment-type", default='bgr', type=str, help="Type of experiment")
parser.add_argument("--k-value", default=4, type=int, help="Value of k")
parser.add_argument("--F-value", default=0.8, type=float, help="Value of F")
parser.add_argument("--n-days", default=1.0, type=float, help="Number of days")
def plot_trades(trial_id):
prices_fname = trial_id + '_tape.csv'
x = np.empty(0)
y = np.empty(0)
with open(prices_fname, newline='') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
time = float(row[1])
price = float(row[2])
x = np.append(x,time)
y = np.append(y,price)
plt.plot(x, y, 'x', color='black')
def n_runs_plot_trades(n, trial_id, start_time, end_time, traders_spec, order_sched):
x = np.empty(0)
y = np.empty(0)
for i in range(n):
trialId = trial_id + '_' + str(i)
tdump = open(trialId + '_avg_balance.csv','w')
market_session(trialId, start_time, end_time, traders_spec, order_sched, tdump, True, False)
tdump.close()
with open(trialId + '_tape.csv', newline='') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
time = float(row[1])
price = float(row[2])
x = np.append(x,time)
y = np.append(y,price)
plt.plot(x, y, 'x', color='black');
def getorderprice(i, sched, n, mode):
pmin = min(sched[0][0], sched[0][1])
pmax = max(sched[0][0], sched[0][1])
prange = pmax - pmin
stepsize = prange / (n - 1)
halfstep = round(stepsize / 2.0)
if mode == 'fixed':
orderprice = pmin + int(i * stepsize)
elif mode == 'jittered':
orderprice = pmin + int(i * stepsize) + random.randint(-halfstep, halfstep)
elif mode == 'random':
if len(sched) > 1:
# more than one schedule: choose one equiprobably
s = random.randint(0, len(sched) - 1)
pmin = min(sched[s][0], sched[s][1])
pmax = max(sched[s][0], sched[s][1])
orderprice = random.randint(pmin, pmax)
return orderprice
def make_supply_demand_plot(bids, asks):
# total volume up to current order
volS = 0
volB = 0
fig, ax = plt.subplots()
plt.ylabel('Price')
plt.xlabel('Quantity')
pr = 0
for b in bids:
if pr != 0:
# vertical line
ax.plot([volB,volB], [pr,b], 'r-')
# horizontal lines
line, = ax.plot([volB,volB+1], [b,b], 'r-')
volB += 1
pr = b
if bids:
line.set_label('Demand')
pr = 0
for s in asks:
if pr != 0:
# vertical line
ax.plot([volS,volS], [pr,s], 'b-')
# horizontal lines
line, = ax.plot([volS,volS+1], [s,s], 'b-')
volS += 1
pr = s
if asks:
line.set_label('Supply')
if bids or asks:
plt.legend()
plt.show()
# Use this to plot supply and demand curves from supply and demand ranges and stepmode
def plot_sup_dem(seller_num, sup_ranges, buyer_num, dem_ranges, stepmode):
asks = []
for s in range(seller_num):
asks.append(getorderprice(s, sup_ranges, seller_num, stepmode))
asks.sort()
bids = []
for b in range(buyer_num):
bids.append(getorderprice(b, dem_ranges, buyer_num, stepmode))
bids.sort()
bids.reverse()
make_supply_demand_plot(bids, asks)
# plot sorted trades, useful is some situations - won't be used in this worksheet
def in_order_plot(trial_id):
prices_fname = trial_id + '_tape.csv'
y = np.empty(0)
with open(prices_fname, newline='') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
price = float(row[2])
y = np.append(y,price)
y = np.sort(y)
x = list(range(len(y)))
plt.plot(x, y, 'x', color='black')
# plot offset function
def plot_offset_fn(offset_fn, total_time_seconds):
x = list(range(total_time_seconds))
offsets = []
for i in range(total_time_seconds):
offsets.append(offset_fn(i))
plt.plot(x, offsets, 'x', color='black')
def schedule_offsetfn(t):
t /= 100
pi2 = math.pi * 2
c = math.pi * 3000
wavelength = t / c
gradient = 100 * t / (c / pi2)
amplitude = 100 / (c / pi2)
offset = gradient + amplitude * math.sin(wavelength)
return int(round(offset, 0))
def run_experiments(experiment_type, k_value, F_value, n_days, traders_spec):
start_time = 0.0
end_time = 60.0 * 60.0 * 24 * n_days
duration = end_time - start_time
# range1 = (65, 190)
# range2 = (200, 270)
range1 = (60, 60)
range2 = (140, 140)
# supply_schedule = [ {'from':start_time, 'to':duration/3, 'ranges':[range1], 'stepmode':'fixed'},
# {'from':duration/3, 'to':2*duration/3, 'ranges':[range2], 'stepmode':'fixed'},
# {'from':2*duration/3, 'to':end_time, 'ranges':[range1], 'stepmode':'fixed'}
# ]
supply_schedule = [{'from':start_time, 'to':end_time, 'ranges':[range1], 'stepmode':'fixed'}]
demand_schedule = [{'from':start_time, 'to':end_time, 'ranges':[range2], 'stepmode':'fixed'}]
order_interval = 5
order_sched = {'sup': supply_schedule , 'dem': demand_schedule, 'interval': order_interval, 'timemode': 'drip-jitter'}
n_trials = 1
trial = 1
while trial < (n_trials + 1):
trial_id = '%s_k%02d_F%2.2f_d%02d_%02d' % (experiment_type, k_value, F_value, n_days, trial)
tdump = open(f'{trial_id}_avg_balance.csv','w')
dump_all = True
verbose = True
market_session(trial_id, start_time, end_time, traders_spec, order_sched, tdump, dump_all, verbose)
tdump.close()
trial += 1
def main(args):
experiment_type = args.experiment_type
k_value = args.k_value
F_value = args.F_value
n_days = args.n_days
if experiment_type == 'jade':
n_traders = 12
sellers_spec = []
for i in range(n_traders):
if i % 2 == 0:
sellers_spec.append(('PRJADE', 1, {'k': 4, 'F': 0.8, 's_min': -1.0, 's_max': +1.0}))
else:
sellers_spec.append(('PRDE', 1, {'k': 4, 'F': 0.8, 's_min': -1.0, 's_max': +1.0}))
print(sellers_spec)
buyers_spec = sellers_spec
elif experiment_type == 'hmg':
sellers_spec = [('PRDE', 20, {'k': 4, 'F': 1.8, 's_min': -1.0, 's_max': +1.0})]
buyers_spec = sellers_spec
elif experiment_type == 'otm':
sellers_spec = [('PRDE', 1, {'k': k_value, 'F': F_value, 's_min': -1.0, 's_max': +1.0}),
('PRDE', 29, {'k': 4, 'F': 0.8, 's_min': -1.0, 's_max': +1.0})]
buyers_spec = [('PRDE', 30, {'k': 4, 'F': 0.8, 's_min': -1.0, 's_max': +1.0})]
elif experiment_type == 'bgr':
trader = 'PRDE'
n_traders = 12
sellers_spec = []
for i in range(n_traders):
if i % 2 == 0:
sellers_spec.append((trader, 1, {'k': k_value, 'F': F_value, 's_min': -1.0, 's_max': +1.0}))
else:
sellers_spec.append((trader, 1, {'k': 4, 'F': 0.8, 's_min': -1.0, 's_max': +1.0}))
print(sellers_spec)
buyers_spec = sellers_spec
traders_spec = {'sellers': sellers_spec, 'buyers': buyers_spec}
run_experiments(experiment_type, k_value, F_value, n_days, traders_spec)
if __name__ == "__main__":
main(parser.parse_args())