forked from Rainy1993/PricingKernel_NonMonotone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Classical_EPK_SP500.R
executable file
·300 lines (246 loc) · 11.4 KB
/
Classical_EPK_SP500.R
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
# Clear variables and close windows
rm(list = ls(all = TRUE))
graphics.off()
# Set working directory
# setwd('~/...') # linux/mac os
# setwd('/Users/...') # windows
## Install packages
# install.packages(KernSmooth)
# install.packages(rugarch)
# install.packages(fGarch)
# install.packages(forecast)
# install.packages(TSA)
# install.packages(ks)
# install.packages(matlab)
# install.packages("optimx")
# Load packages
library(KernSmooth)
library(rugarch)
# library(fGarch)
library(forecast)
library(TSA)
library(ks)
library(matlab)
library(splines) # bs()
library(pracma)
library(optimx)
library(data.table)
library(dplyr)
library(ggplot2)
library(dplyr)
library(readxl)
# set directory
# path <- "~/Library/CloudStorage/OneDrive-NationalUniversityofSingapore/PAPER/Pricing/code/test/"
Path_raw = "/Users/ruting/Library/Mobile Documents/com~apple~CloudDocs/PK_BTC/code_data/"
path <- "/Users/ruting/Library/Mobile Documents/com~apple~CloudDocs/PK_BTC/code_data/main_code/"
setwd(path)
path_Qfile <- paste0(path,"Q_density_files_SP500/")
directories <- list.files(path = path_Qfile, full.names = FALSE, recursive = FALSE)
# classical part
HDEgarch = function(garchfit, data, grid, maturity, N, start){
# Simulation
garchsim = ugarchsim(garchfit, n.sim = round(maturity),
n.start = 0, m.sim=N, startMethod=("sample"),
mexsimdata=TRUE)
# head(g11sim@simulation)[2]= extracting simulated return data
returnsim = as.vector(head(garchsim@simulation)[2])
# Calculating spot prices from return data
value = matrix(0,ncol=5000)
for(i in 1:N) {
value[,i] = start*exp(sum(returnsim$seriesSim[,i]))
}
# Computing density on given grid: Either by using build in function (kde(...)):
# kde() computes bandwith h wih function hpi() which uses Wand&Jones (1994) estimator
# grid: strike
ValDens = kde(value[1,],eval.points=grid, gridsize=length(grid),
xmin=min(grid), xmax=max(grid))
return(ValDens$estimate)
}
Price_infor = read.csv(paste0(Path_raw,'SP500_data/sp500_price_daily.csv'))%>% data.frame()
sp1 <- Price_infor
# sp1 <- sp1[!(as.Date(sp1$Date) < as.Date(dates_Q[i]) | as.Date(sp1$Date) > as.Date(dates_Q[i]) + tau), ]
sp1.retts = ts(log(sp1$Close)[2:nrow(sp1)]-log(sp1$Close)[1:(nrow(sp1)-1)])
# rt <- seq(-1, log(sp1$Adj.Close[nrow(sp1)] / sp1$Adj.Close[1]), length.out = 500)
# Parameters for calculation/simulation
numbapprox = 2000 # fineness of the grid
N = 5000 # No. of Simulations
# Check return series for ARMA effects, e.g. with the following function
# auto.arima(dax.retts, max.p=10, max.q=10, max.P=5, max.Q=5,
# start.p=1, start.q=1,start.P=1, start.Q=1, stationary=T, seasonal=F)
p = 0
q = 0
arma = c(p,q)
# specify garch order (need to be checked)
m = 1
s = 1
garch = c(m,s)
# Specify GARCH model (default is standard GARCH)
# for changing GARCH-model + submodel, please refer to
# rugarch package for further information
garchmodel = "fGARCH"
submodel = "GARCH"
# underlying distribution (default: "sstd" - skewed stundent t's)
# (alternatives: "norm" - normal, "ghyp"- generalized hyperbolic)
udist = "sstd"
# set archm=T for ARCH in mean model (archpow specifies the power)
archm = F
archpow = 1
# set include.mean = F if you don't want to include a mean in the mean model
include.mean = T
spec = ugarchspec(variance.model = list(model = garchmodel,
garchOrder = garch, submodel = submodel), mean.model =
list(armaOrder = arma, archm=archm,archpow=archpow,
include.mean=include.mean), distribution.model = udist)
dir.create(paste0(path,"EPKPlot_SP500"), showWarnings = FALSE)
# 4y 6y 8y 10y
rolling = c(4, 6, 8, 10)
rolling = 4
# tau = 30
# tau_files <- grep( paste0("raw_Q_density.*tau",tau,"\\.csv$"), directories, value = TRUE)
# dates <- gsub("raw_Q_density_([0-9]{4}-[0-9]{2}-[0-9]{2})_tau.*", "\\1", tau_files)
# dates_Q <- dates[1:(length(dates) - 1)]
date_tau = read_excel('SP500_Classic_date.xlsx')
date_tau$dates_Q = as.character(date_tau$dates_Q )
for (i in c(1:nrow(date_tau))){
setwd(paste0(path, 'Q_density_files_SP500'))
tau = date_tau$tau[i]
figure_save = paste0(path,"EPKPlot_SP500/tau_",tau)
dir.create(figure_save, showWarnings = FALSE)
a <- paste0(path_Qfile,"raw_Q_density_", date_tau$dates_Q[i], "_tau", date_tau$tau[i], ".csv")
# 检查文件是否存在
if (!file.exists(a)) {
print(paste("no files for", date_tau$dates_Q[i], "tau", date_tau$tau[i]))
next # 如果文件不存在,跳过这个循环
}
data_q = read.csv(a)
data_q = data_q[order(data_q$m),]
data_q$Strike = data_q$x
data_q$Q_density = data_q$y
SpotPrice = mean(data_q$Strike * data_q$m)
# data_q$Q_density = data_q$y
# sp1_h <- sp1[as.Date(sp1$Date) < as.Date(dates_Q[i]), ]
for (iRoll in rolling){
sp1_h <- sp1[as.Date(sp1$Date) < as.Date(date_tau$dates_Q[i]), ]
sp1_h <- sp1[(nrow(sp1_h)-iRoll*360):nrow(sp1_h),]
sp1.retts = ts(log(sp1_h$Close)[2:nrow(sp1_h)]-log(sp1_h$Close)[1:(nrow(sp1_h)-1)])
garchfit = ugarchfit(data=sp1.retts, spec=spec, solver = "hybrid")
HDE = HDEgarch(garchfit, sp1.retts, data_q$Strike,
tau, N =5000, SpotPrice)
EPK = data.frame(M = data_q$m,EPK = data_q$Q_density / HDE, Q = data_q$Q_density, P = HDE,Strike = data_q$Strike )
EPK = EPK[EPK$EPK>0&EPK$M<1.07&EPK$M>0.93,]
# Save the plot to a PNG file
png(paste0(figure_save, "/SP500_", date_tau$dates_Q[i], "_tau_", tau, "_", iRoll, "YearRoll_Classical.png"), width = 800, height = 600, bg = "transparent")
# Ensure there are no missing or infinite values in EPK$M and EPK$EPK
EPK <- EPK[!is.na(EPK$M) & !is.na(EPK$EPK) & !is.infinite(EPK$M) & !is.infinite(EPK$EPK), ]
# Check if the data frame is not empty after removing NA and Inf values
if (nrow(EPK) > 0) {
# Calculate xlim and ylim ensuring finite values
xlim_vals <- range(EPK$M, na.rm = TRUE, finite = TRUE)
ylim_vals <- quantile(EPK$EPK, probs = c(0.05, 0.95), na.rm = TRUE, finite = TRUE)
# Debugging: Print the calculated xlim and ylim values
print(paste("xlim:", xlim_vals))
print(paste("ylim:", ylim_vals))
# Plot only if xlim and ylim values are finite
if (all(is.finite(xlim_vals)) && all(is.finite(ylim_vals))) {
plot(EPK$M, EPK$EPK, type = 'l', col = 'black', lwd = 2,
xlab = "Moneyness", ylab = "EPK",
cex.lab = 1.25, # 坐标轴标签字体大小
cex.axis = 1.25,
xlim = xlim_vals, ylim = ylim_vals, # x 和 y 轴的范围
cex.main = 1.25)
} else {
warning("Non-finite xlim or ylim values, plot not created.")
}
} else {
warning("Data frame is empty after removing NA and Inf values, plot not created.")
}
# Close the graphics device
dev.off()
# plot(EPK$Strike, EPK$Q, type = 'l', col = 'red',
# xlab = "Strike", ylab = "Q density",
# xlim = c(min(EPK$Strike), max(EPK$Strike)), ylim = c(quantile(EPK$Q, probs = c(0.01)),quantile(EPK$Q, probs = c(0.99))),
# main = paste(dates_Q[i], "Q density")
# )
# lines(EPK$Strike, EPK$P, col = 'blue')
#
#
# plot(EPK$Strike, EPK$P, type = 'l', col = 'black',
# xlab = "Strike", ylab = "P density",
# xlim = c(min(EPK$Strike), max(EPK$Strike)), ylim = c(quantile(EPK$P, probs = c(0.01)),quantile(EPK$P, probs = c(0.99))),
# main = paste(dates_Q[i], "Classical EPK")
# )
#
Plot_Out = data.frame(x = rep(EPK$M,2), density = c(EPK$Q,EPK$P), line = factor(rep(c("Q_density","P_density"), each = nrow(EPK))))
my_plot <-ggplot(Plot_Out, aes(x = x, y = density, color = line)) +
geom_line(size = 1) +
labs(x=NULL,y = "Density")+
theme(legend.key = element_rect(fill = "transparent"),
axis.ticks.length = unit(-0.2, "cm"),
panel.grid = element_blank(),
axis.line = element_line(color = "black", linewidth = 0.5),
plot.background = element_rect(fill = "transparent"),
legend.background = element_rect(fill = "transparent"), # Set legend background to transparent
panel.background = element_rect(fill = "transparent"),
)
plot(my_plot)
ggsave(paste0(figure_save,"/SP500_Density_",date_tau$dates_Q[i],"_tau_",tau,"_",iRoll,"YearRoll.png"), my_plot, width = 3200, height = 1600, units = "px")
}
}
for (i in c(1:length(dates_Q))) {
setwd(paste0(path, 'Q_density_files_SP500'))
a <- paste0(path_Qfile,"raw_Q_density_", dates_Q[i], "_tau", tau, ".csv")
# 检查文件是否存在
if (!file.exists(a)) {
print(paste("no files for", dates_Q[i], "tau", tau))
next # 如果文件不存在,跳过这个循环
}
data_q = read.csv(a)
data_q = data_q[order(data_q$m),]
data_q$Strike = data_q$x
data_q$Q_density = data_q$y
SpotPrice = mean(data_q$Strike * data_q$m)
# data_q$Q_density = data_q$y
# sp1_h <- sp1[as.Date(sp1$Date) < as.Date(dates_Q[i]), ]
sp1_h <- sp1_h[(nrow(sp1_h)-4*360):nrow(sp1_h),]
sp1.retts = ts(log(sp1_h$Close)[2:nrow(sp1_h)]-log(sp1_h$Close)[1:(nrow(sp1_h)-1)])
garchfit = ugarchfit(data=sp1.retts, spec=spec, solver = "hybrid")
HDE = HDEgarch(garchfit, sp1.retts, data_q$Strike,
tau, N = length(data_q$Strike), SpotPrice)
EPK = data.frame(M = data_q$m,EPK = data_q$Q_density / HDE, Q = data_q$Q_density, P = HDE,Strike = data_q$Strike )
EPK = EPK[EPK$EPK>0&EPK$M<1.05&EPK$M>0.93,]
png(paste0(figure_save,"/SP500_",dates_Q[i],"_tau_",tau,"_Classical.png"), width = 800, height = 600, bg = "transparent")
plot(EPK$M, EPK$EPK, type = 'l', col = 'black',
xlab = "Moneyness", ylab = "EPK",
xlim = c(min(EPK$M), max(EPK$M)), ylim = c(quantile(EPK$EPK, probs = c(0.05)),quantile(EPK$EPK, probs = c(0.95))),
main = paste(dates_Q[i], "Classical EPK")
)
dev.off()
# plot(EPK$Strike, EPK$Q, type = 'l', col = 'red',
# xlab = "Strike", ylab = "Q density",
# xlim = c(min(EPK$Strike), max(EPK$Strike)), ylim = c(quantile(EPK$Q, probs = c(0.01)),quantile(EPK$Q, probs = c(0.99))),
# main = paste(dates_Q[i], "Q density")
# )
# lines(EPK$Strike, EPK$P, col = 'blue')
#
#
# plot(EPK$Strike, EPK$P, type = 'l', col = 'black',
# xlab = "Strike", ylab = "P density",
# xlim = c(min(EPK$Strike), max(EPK$Strike)), ylim = c(quantile(EPK$P, probs = c(0.01)),quantile(EPK$P, probs = c(0.99))),
# main = paste(dates_Q[i], "Classical EPK")
# )
#
Plot_Out = data.frame(x = rep(EPK$M,2), density = c(EPK$Q,EPK$P), line = factor(rep(c("Q_density","P_density"), each = nrow(EPK))))
my_plot <-ggplot(Plot_Out, aes(x = x, y = density, color = line)) +
geom_line(size = 1) +
labs(x=NULL,y = "Density")+
theme(legend.key = element_rect(fill = "transparent"),
axis.ticks.length = unit(-0.2, "cm"),
panel.grid = element_blank(),
axis.line = element_line(color = "black", linewidth = 0.5),
plot.background = element_rect(fill = "transparent"),
legend.background = element_rect(fill = "transparent"), # Set legend background to transparent
panel.background = element_rect(fill = "transparent"),
)
plot(my_plot)
ggsave(paste0(figure_save,"/SP500_Density_",dates_Q[i],"_tau_",tau,".png"), my_plot, width = 3200, height = 1600, units = "px")
}