-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstep8_relabelandplot_bond.py
354 lines (330 loc) · 15.7 KB
/
step8_relabelandplot_bond.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
#from kaleido.scopes.plotly import PlotlyScope
#import plotly.graph_objects as go
#scope = PlotlyScope()
import matplotlib.pyplot as plt
import itertools
import multiprocessing
import pandas as pd
import numpy as np
from os import listdir
from os.path import isfile, join
from pathlib import Path
from garch_utils.getList import getItemNameFromJson,getParameterListFromJson
from garch_utils.inputForm import inputForm
figsize=(16, 8)
fontsize = 16
def plotGraphSetting(params,result,setting,itemmode):
mode = params[0]
item = params[1]
SD = params[2]
MA = params[3]
itemType = params[4]
try:
epsilon = float(params[5])
except:
epsilon = 0
'''column name: [result.columns[0],MA+"MA","Bank's Rate","S/S_A", "S_U", "S_L", "Band Width", "s","Leakage Ratio",
"kappa","kappa_SE","kappa_lb","kappa_ub","kappa_z",
"theta","theta_SE","theta_lb","theta_ub","theta_z",
"sigma","sigma_SE","sigma_lb","sigma_ub","sigma_z"]'''
if epsilon != 0:
suffix = "(SD = {}, MA = {}, Tolerance = {})".format(SD, MA, epsilon)
else:
suffix = "(SD = {}, MA = {})".format(SD, MA)
if itemmode == "upper":
title = {
"stdtit": "{}, moving average and S_U (Quasi-bounded){}".format(item, suffix),
"leakage": "{} and leakage ratio {}".format(item, suffix),
"normalize": "{} and S/S_A {}".format(item, suffix),
"s": "{} and s {}".format(item, suffix),}
elif itemmode == "lower":
title = {
"stdtit": "{}, moving average, S_U (Inaccessible){}".format(item, suffix),
"leakage": "{} and leakage ratio {}".format(item, suffix),
"normalize": "{} and S/S_A {}".format(item, suffix),
"s": "{} and s {}".format(item, suffix),}
else:
title = {
"stdtit": "{}, moving average, S_U and S_L {}".format(item, suffix),
"leakage": "{} and leakage ratio {}".format(item, suffix),
"normalize": "{} and S/S_A {}".format(item, suffix),
"s": "{} and s {}".format(item, suffix),}
if setting == "main":
if "bond" in itemType:
if itemmode in ["upper","lower"]:
data = result[[result.columns[0], "{}MA".format(MA),"S_U"]]
else:
data = result[[result.columns[0], "{}MA".format(MA),"S_U", "S_L"]]
else:
data = result[[result.columns[0], "{}MA".format(MA),"S_U", "S_L"]]
ax1 = data.plot(title = title["stdtit"], grid=True, fontsize=fontsize, figsize=figsize, xticks = (np.arange(0, len(data)+1, 250.0)))
if setting == "s":
data = result[[result.columns[0], "s"]]
ax1 = data.plot(title = title[setting], grid=True, fontsize=fontsize, secondary_y="s", figsize=(16, 8), xticks = (np.arange(0, len(data)+1, 250.0)))
ax1.right_ax.set_ylabel("s", fontsize = fontsize)
if setting == "leakage":
data = result[[result.columns[0], "Leakage Ratio"]]
ax1 = data.plot(title = title[setting], grid=True, fontsize=fontsize, secondary_y="Leakage Ratio", figsize=(16, 8), xticks = (np.arange(0, len(data)+1, 250.0)))
ax1.right_ax.set_ylabel("Leakage Ratio", fontsize = fontsize)
if max(result["Leakage Ratio"]>1):
ax1.right_ax.set_ylim(0,1.5)
if setting == "normalize":
data = result[[result.columns[0], "S/S_A"]]
ax1 = data.plot(title = title[setting], grid=True, fontsize=fontsize, secondary_y="S/S_A", figsize=(16, 8), xticks = (np.arange(0, len(data)+1, 250.0)))
ax1.right_ax.set_ylabel("S/S_A", fontsize = fontsize)
ax1.right_ax.set_ylim(0,2)
if "bond" in itemType:
ylabalT = "Bond Yield"
elif "vix" in itemType:
ylabalT = "VIX"
else:
ylabalT = ""
ax1.set_ylabel(ylabalT, fontsize = fontsize)
ax1.set_xlabel("Date", fontsize = fontsize)
ax1.title.set_fontsize(fontsize)
for item in (ax1.get_legend().get_texts()):
item.set_fontsize(fontsize)
plt.autoscale(enable=True, axis='x', tight=True)
fig1 = ax1.get_figure()
fig1.autofmt_xdate()
plt.close('all')
return fig1
def plotGraphParameter(params,result,parameter,itemmode):
mode = params[0]
item = params[1]
SD = params[2]
MA = params[3]
itemType = params[4]
try:
epsilon = float(params[5])
except:
epsilon = 0
'''column name: [result.columns[0],MA+"MA","Bank's Rate","S/S_A", 'S_U', 'S_L', 'Band Width', "s","Leakage Ratio",
"kappa","kappa_SE","kappa_lb","kappa_ub","kappa_z",
"theta","theta_SE","theta_lb","theta_ub","theta_z",
"sigma","sigma_SE","sigma_lb","sigma_ub","sigma_z"]'''
data = result[[parameter, parameter + "_z"]]
data["z-score > 1.96"] = 1.96
data = data.iloc[749:]
if epsilon != 0:
suffix = "(SD = {}, MA = {}, Tolerance = {})".format(SD, MA, epsilon)
else:
suffix = "(SD = {}, MA = {})".format(SD, MA)
if itemmode == "upper":
title = "{}ing windows, S_U is quasi-bounded, {} - {} and z-score {}".format(mode.capitalize(),item, parameter, suffix)
elif itemmode == "lower":
title = "{}ing windows, S_U is inaccessible, {} - {} and z-score {}".format(mode.capitalize(),item, parameter, suffix)
else:
title = "{}ing windows, {} - {} and z-score {}".format(mode.capitalize(),item, parameter, suffix)
'''varMain = go.Scatter(
name=parameter,
x=data.index.tolist(),
y=data[parameter],
hoverlabel = dict(namelength = -1),
mode='lines',
line=dict(color='rgb(31, 119, 180)'),
)
zPlot = go.Scatter(
name=parameter + "_zscore (right)",
x=data.index.tolist(),
y=data[parameter + "_z"],
hoverlabel = dict(namelength = -1),
mode='lines',
yaxis='y2',
line=dict(color='rgb(255, 127, 14)', width = 2),
)
plotData = [varMain,zPlot]
layout = go.Layout(
yaxis=dict(title=parameter, rangemode='nonnegative',
showgrid=True,
showline=True,
gridcolor='rgb(0, 0, 0)',),
title=title,
legend=dict(orientation="h"),
yaxis2=dict(
overlaying='y',
side='right',
showgrid=False,
showline=False,
title = "z score",
),
xaxis_title="Date",
template="plotly_white",
)
fig = go.Figure(data=plotData, layout=layout)'''
ax1 = data.plot(title = title, grid=True, secondary_y=["{}_z".format(parameter),"z-score > 1.96"], fontsize=fontsize,figsize=(16, 8), xticks = (np.arange(0, len(data)+1, 250.0)))
plt.autoscale(enable=True, axis='x', tight=True)
ax1.set_xlabel("Date", fontsize = fontsize)
ax1.set_ylabel(parameter, fontsize = fontsize)
ax1.right_ax.set_ylabel("z score", fontsize = fontsize)
ax1.title.set_fontsize(fontsize)
for item in (ax1.get_legend().get_texts()):
item.set_fontsize(fontsize)
fig1 = ax1.get_figure()
fig1.autofmt_xdate()
return fig1
def relabelAndPlot(params):
mode = params[0]
item = params[1]
SDint = params[2]
day = params[3]
itemType = params[4]
try:
epsilon = float(params[5])
except:
epsilon = 0
MA = str(day)
SD = str(int(SDint*100))
pathString = "SD{}/day{}/{}/".format(SD,MA,mode)
itemmode = itemType.replace("bond","").replace("GER","")
if itemmode not in ["upper","lower"]:
itemmode = ""
else:
itemmode = itemmode
if not epsilon == 0:
filepath = {
"graph": "{itemType}/updating/graph/{item}/SD{SDint}day{day}tol{epsilon}/{mode}/".format(itemType = itemType,item = item,SDint = SDint,day = day,epsilon = epsilon,mode = mode),
"result": "{}/updating/tor{}/result/SD{}/day{}/{}/".format(itemType,epsilon,SD,day,mode),
"output_graph": "output/{itemType}/graph/{item}/day{day}tol{epsilon}SD{SDint}/{mode}/".format(itemType = itemType,item = item,SDint = SDint,day = day,epsilon = epsilon,mode = mode),
"output_result": "output/{itemType}/result/{item}/day{day}tol{epsilon}SD{SDint}/{mode}/".format(itemType = itemType,item = item,SDint = SDint,day = day,epsilon = epsilon,mode = mode),
}
resultFile = "tor{}_day{}_SD{}_{}.csv".format(epsilon,MA,SD,item)
graphName = "{}_SD{}day{}tol{}".format(item,SDint,day,epsilon)
infographName = "{}_SD{}day{}tol{}".format(item,SDint,day,epsilon)
else:
filepath = {
"graph": "{}/updating/graph/{}/SD{}day{}/{}/".format(itemType,item,SDint,day,mode),
"result": "{}/updating/result/SD{}/day{}/{}/".format(itemType,SD,day,mode),
"output_graph": "output/{itemType}/graph/{item}/day{day}SD{SDint}/{mode}/".format(itemType = itemType,item = item,SDint = SDint,day = day,mode = mode),
"output_result": "output/{itemType}/result/{item}/day{day}SD{SDint}/{mode}/".format(itemType = itemType,item = item,SDint = SDint,day = day,mode = mode),
}
if "bond" not in itemType:
resultFile = "{}_day{}_SD{}_{}.csv".format(mode,MA,SD,item)
graphName = "{}_{}_SD{}day{}".format(mode,item,SDint,day)
infographName = "{}_SD{}day{}".format(item,SDint,day)
else:
resultFile = "{}_{}_day{}_SD{}_{}.csv".format(mode,itemmode,MA,SD,item)
graphName = "{}_{}_{}_SD{}day{}".format(mode,itemmode,item,SDint,day)
infographName = "{}_{}_SD{}day{}".format(itemmode,item,SDint,day)
for f in filepath.values():
tempPath = Path(f)
tempPath.mkdir(parents=True, exist_ok=True)
resultPath = filepath["result"] + resultFile
#bank = pd.read_csv("{}/updating/bank.csv".format(itemType) , index_col=0, na_values=["null"])
#bank = bank.drop(bank.index[0:day-1])
result = pd.read_csv(resultPath, index_col=0)
result.to_csv(filepath["output_result"] + resultFile, sep=",", index=True)
#result.insert(2,"Bank",bank["Bank"].tolist())
'''
result.columns = [result.columns[0],MA+"MA","Bank's Rate","S/S_A", 'S_U', 'S_L', 'Band Width', "s","Leakage Ratio",
"kappa","kappa_SE","kappa_lb","kappa_ub","kappa_z",
"theta","theta_SE","theta_lb","theta_ub","theta_z",
"sigma","sigma_SE","sigma_lb","sigma_ub","sigma_z"]
'''
#result.to_csv(resultPath, sep=",", index=True)
variables = ["kappa", "theta", "sigma"]
for var in variables:
fig = plotGraphParameter(params,result, var,itemmode)
fig.savefig(filepath["graph"] + "{}_{}.png".format(graphName,var) )
fig.savefig(filepath["output_graph"] + "{}_{}.png".format(graphName,var) )
setting = ["main","s","leakage","normalize"]
for var in setting:
fig = plotGraphSetting(params,result, var,itemmode)
fig.savefig(filepath["graph"] + "{}_{}.png".format(infographName,var) )
fig.savefig(filepath["output_graph"] + "{}_{}.png".format(infographName,var) )
print(params)
'''
lws = [1.5, 2, 1.25]
mu = pd.read_csv("result/rolling_3000_result/" + names , usecols=[0,1,2,3], index_col=0, na_values=["null"])
sigma = pd.read_csv("result/rolling_3000_result/" + names , usecols=[0,4,5,6], index_col=0, na_values=["null"])
mutitle = "roll_3000_" + names[:4] + "." + names[4:6] + "_mu"
sigmatitle = "roll_3000_" + names[:4] + "." + names[4:6] + "_sigma"
ax1 = mu.plot(title = mutitle, grid=True, secondary_y="mu_z", figsize=(16, 8), xticks = (np.arange(0, len(mu)+1, 100.0)))
plt.autoscale(enable=True, axis='x', tight=True)
ax2 = sigma.plot(title = sigmatitle, grid=True, secondary_y="sigma_z", figsize=(16, 8), xticks = (np.arange(0, len(mu)+1, 100.0)))
for i, l in enumerate(ax1.lines):
plt.setp(l, linewidth=lws[i])
for i, l in enumerate(ax2.lines):
plt.setp(l, linewidth=lws[i])
plt.autoscale(enable=True, axis='x', tight=True)
fig1 = ax1.get_figure()
fig1.autofmt_xdate()
fig1.savefig("img/roll_3000/mu/" + mutitle + ".png")
fig2 = ax2.get_figure()
fig2.autofmt_xdate()
fig2.savefig("img/roll_3000/sigma/" + sigmatitle + ".png")
plt.close('all')
'''
def tablePlot(params):
mode = params[0]
item = params[1]
SDint = params[2]
day = params[3]
itemType = params[4]
try:
epsilon = float(params[5])
except:
epsilon = 0
MA = str(day)
SD = str(int(SDint*100))
pathString = "SD{}/day{}/{}/".format(SD,MA,mode)
itemmode = itemType.replace("bond","").replace("GER","")
if itemmode not in ["upper","lower"]:
itemmode = ""
else:
itemmode = itemmode
if not epsilon == 0:
filepath = {
"graph": "{itemType}/updating/graph/{item}/SD{SDint}day{day}tol{epsilon}/".format(itemType = itemType,item = item,SDint = SDint,day = day,epsilon = epsilon),
"table": "{itemType}/updating/tor{epsilon}/table/SD{SD}/day{day}/".format(itemType = itemType,epsilon = epsilon,SD = SD,day = day),
"output_graph": "output/{itemType}/graph/{item}/day{day}tol{epsilon}SD{SDint}/".format(itemType = itemType,item = item,SDint = SDint,day = day,epsilon = epsilon),
"output_table": "output/{itemType}/table/{item}/day{day}tol{epsilon}SD{SDint}/".format(itemType = itemType,item = item,SDint = SDint,day = day,epsilon = epsilon),
}
tableFile = "tor{}_day{}_SD{}_{}.csv".format(epsilon,MA,SD,item)
graphName = "{}_SD{}day{}tol{}".format(item,SDint,day,epsilon)
infographName = "{}_{}_SD{}day{}tol{}".format(item,SDint,day,epsilon)
else:
filepath = {
"graph": "{itemType}/updating/graph/{item}/SD{SDint}day{day}/".format(itemType = itemType,item = item,SDint = SDint,day = day),
"table": "{itemType}/updating/table/SD{SD}/day{day}/".format(itemType = itemType,SD = SD,day = day),
"output_graph": "output/{itemType}/graph/{item}/day{day}SD{SDint}/".format(itemType = itemType,item = item,SDint = SDint,day = day),
"output_table": "output/{itemType}/table/{item}/day{day}SD{SDint}/".format(itemType = itemType,item = item,SDint = SDint,day = day),
}
tableFile = "day{}_SD{}_{}.csv".format(MA,SD,item)
graphName = "{}_SD{}day{}".format(item,SDint,day)
infographName = "{}_SD{}day{}".format(item,SDint,day)
for f in filepath.values():
tempPath = Path(f)
tempPath.mkdir(parents=True, exist_ok=True)
talbePath = filepath["table"] + tableFile
table = pd.read_csv(talbePath, index_col=0)
table.columns = [table.columns[0],MA+"MA","S/S_A", 'S_U', 'S_L', "s"]
table.to_csv(filepath["output_table"] + tableFile, sep=",", index=True)
setting = ["VIX", "s", "normalize"]
for var in setting:
fig = plotGraphSetting(params,table, var,itemmode)
fig.savefig(filepath["graph"] + "{}_{}.png".format(infographName,var) )
fig.savefig(filepath["output_graph"] + "{}_{}.png".format(infographName,var) )
print(params)
def merger(itemType , region,mode="hybrid"):
tempList = getParameterListFromJson(itemType,region,mode = "plot")
modeList = ["roll"]
paramList = [(a,*b) for a,b in itertools.product(modeList,tempList)]
cpuCount = multiprocessing.cpu_count()
#print(cpuCount)
pool = multiprocessing.Pool(processes=cpuCount)
pool.map(relabelAndPlot,paramList)
#for param in paramList:
# relabelAndPlot(param)
return 0
if __name__ == '__main__':
#itemType, region = inputForm()
for mode in ["default"]:
#itemType = "bond{mode}".format(mode=mode)
#region = "GER"
itemType = "vixir"
region = ""
merger(itemType,region, mode = mode)
#itemType = "bondfloat3"
#region = "GER"
#merger(itemType , region)