-
Notifications
You must be signed in to change notification settings - Fork 2
/
bitcoin_spillovers.Rmd
294 lines (197 loc) · 12.1 KB
/
bitcoin_spillovers.Rmd
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
---
title: "Bitcoin prices across different cyryptocurrency markets"
author: "Maciej Nasinski"
date: "November 8, 2017"
fontsize: 11pt
output:
html_document:
toc: true
---
```{r setup, include=FALSE,message=F}
options(scipen = 999)
knitr::opts_chunk$set(echo = F,message=F,warning=F,cache = F)
pacman::p_load(rvest,
tidyverse,
stringr,
lubridate,
data.table,
doParallel,
scales,
Hmisc,
MSBVAR,
ggthemes,
rjags)
updating = FALSE
```
## Executive Summary
There is no a one particular pattern across all examined Bitcoin markets. It was observed two significant scenarios, positive and negative mean spillovers - i.e. some Bitcoin markets influence positively/negatively future returns at other markets. This results provide some evidence of an cryptomarkets inefficiency. It is very probable that it is a first research on this subject. Further steps will be to add a GARCH component to examine volatile spillovers.
## Intro
```{r}
#Most important steps of the statistical modeling process are:
#Problem -> Understanding -> Gather Data -> Explore -> Modeling -> Validation -> Implementation
```
In this research it will be investigated price mean spillover across Bitcoin markets. It will be used Bayesian statistics methodology to assess if prices at certain market are influenced by other markets. The aspect of currency is not important in this analysis so it were used only US dollar denominated markets. There was used a Bayesian version of VAR (Vector Autoregression) model which provides clear solution for analyzing mean spillover across markets.
Why VAR model was chosen? VAR is one of the most popular tool for exploring multi-equations models. Additionally in accordance with literature this model could be improved by adding variance of errors (GARCH) enabling examination of volatility spillovers.
[**(Abidin&others,2015)**](http://ro.uow.edu.au/cgi/viewcontent.cgi?article=1515&context=aabfj) [**(Zhang&others,2008)**](https://www.sciencedirect.com/science/article/pii/S0161893808000197) [**(Beirne&others,2010)**](https://www.sciencedirect.com/science/article/pii/S1566014110000282)
What is difference between frequentist and Bayesian VAR model. It allows for a more general specification and can produce a tractable multivariate normal posterior distribution. A consequence is that the estimation of the VAR coefficients is no longer done on an equation-by-equation basis as in the reduced form version. Instead, we estimate the parameters for the full system in a multivariate regression. [**(Brandt&others,2006)**](http://www.utdallas.edu/~pbrandt/Patrick_Brandts_Website/Replication_files/BrandtFreeman-2006-PA.pdf)
Database was built from data offered by [**bitcoincharts**](https://bitcoincharts.com). First of all there was downloaded files in [**csv.gz**](http://api.bitcoincharts.com/v1/csv/) format which contain quotes from active USD Bitcoin markets. Procedure assume that csv files are frequently update so if files are change re-run of script will cause downloading of files with a new upload time-stamp. The certain csv file contains all transactions from a particular bitcoin market at specific time frame. There are 3 attributes describing each file - time-stamp,price and volume of every transaction. This files could be merged and/or aggregate by time-stamp. Aggregating could be helpful because of the big size of decompressed files but at expense of lossing information. Data could be aggregate by every minute,hour or day. Data aggregation with 1 hour interval was implemented. Then statistics like mean,max.min,first and/or last price was evaluated.
\newpage
## Data
[**blockexplorer**](https://blockexplorer.com/b/100000) is an API which allows downloading information from certain blocks. It could be used to gather all bitcoin transactions by web scarping subsequent blocks. However it is much faster and easier to use data already downloaded which are offered for free on the Internet.
[**bitcoincharts**](https://bitcoincharts.com/markets/currency/USD.html) summarize prices on most important markets.
At the same website we are able to find database of csv files of historic prices on different markets. Some markets are update constantly others with few months delay.
```{r, eval = FALSE}
csvs = function(){
markets_raw <- read_html("http://api.bitcoincharts.com/v1/csv/")
csv_markets = markets_raw %>%
html_nodes("a") %>%
html_text()
csv_dates = markets_raw %>%
html_nodes(xpath="/html/body/pre/text()") %>%
html_text() %>%
str_extract("\\d\\d-[a-zA-z].+-\\d\\d\\d\\d \\d\\d:\\d\\d")
tibble(csv_dates,csv_markets)
}
###Active Markets List
active_markets = function(){
a_markets=read_html("https://bitcoincharts.com/markets/list/") %>%
html_nodes("body > div.container_16.content.padding > div > div.grid_7.alpha > ul") %>% html_text() %>% str_replace_all("\\n","") %>% str_replace_all("\\s+"," ") %>% str_trim()
a_currency = read_html("https://bitcoincharts.com/markets/list/") %>%
html_nodes("body > div.container_16.content.padding > div > div.grid_7.alpha > h3") %>% html_text()
clean_nams = function(x) gsub(")$","",trimws(unlist(str_split(x,"\\(|\\)\\s"))))
by_pos = function(x,by,pos) x[seq(pos,length(x),by)]
DF = tibble(a_currency,a_markets) %>% rowwise() %>% mutate(nam1=list(by_pos(clean_nams(a_markets),2,1)),nam2=list(by_pos(clean_nams(a_markets),2,2)))
DF
}
active_m = active_markets() %>% filter(grepl("USD",a_currency))
csv_files = csvs()
sub = gsub(".csv.gz","",csv_files$csv_markets) %in% unlist(active_m$nam1)
markets_sub = csv_files$csv_markets[sub]
cl <- makePSOCKcluster(max(parallel::detectCores()-1,1))
doParallel::registerDoParallel(cl)
bitcoin_merged = foreach(i = 1:length(markets_sub),.combine = "rbind") %dopar%
{
my_data = tryCatch(readr::read_csv(paste0("http://api.bitcoincharts.com/v1/csv/",markets_sub[i]),col_names = c("time","price","vol"),col_types = "idd"),
error= function(e) data.frame(time=NA,price=NA,vol=NA))
my_data$name = gsub(".csv.gz","",markets_sub[i])
my_data
}
stopCluster(cl)
bitcoin_merged$name = factor(bitcoin_merged$name)
saveRDS(bitcoin_merged,paste0("bitcoinUSD.Rds"))
```
```{r}
bitcoin_merged = readRDS("bitcoinUSD.Rds")
setDT(bitcoin_merged)
bitcoin_merged[,c('ymd_hm','ymd_h'):=list(as.POSIXct(time-time%%60,origin="1970-01-01"),as.POSIXct(time-time%%(60*60),origin="1970-01-01"))]
bitcoin_agg = bitcoin_merged %>%
.[,.(
price_max=max(price,na.rm=T),
price_min = min(price,na.rm=T),
price_mean = mean(price,na.rm=T),
price_median = median(price,na.rm=T),
price_first = first(price),
price_last = last(price),
vol_sum = sum(vol,na.rm=T),
vol_max = max(vol,na.rm=T)),
by=list(name,ymd_h)]
bitcoin_agg[,ret_median := (log(price_median)-lag(log(price_median))),by=list(name)]
#rm(bitcoin_merged)
bitcoin_spread = data.table::dcast(bitcoin_agg[,.(ymd_h,name,ret_median)],ymd_h ~ name,value.var="ret_median")
###Deleting markets with high NA ratio
low_NA = colnames(sort(bitcoin_spread[,lapply(.SD,function(x) sum(is.na(x))/length(x))]))[1:5]
bitcoin_spread = na.omit(bitcoin_spread[,low_NA,with=F])
frams = bitcoin_agg[name %in% low_NA,.(min_t=min(ymd_h),max_t=max(ymd_h)),by=.(name)][,.(min=max(min_t),max=min(max_t))]
dat = bitcoin_agg[ymd_h>=frams$min & ymd_h<frams$max & name %in% low_NA,,][order(ymd_h)]
```
In most cases it is much easier to analyse returns not prices because of stationarity of a former. Example of a stationary process is the white noise process which probability distribution does not changed during time. The returns are calculated as log difference between first and last transaction price at a specific hour.
List of six active and most volatile USD Bitcoin markets: `r toupper(low_NA[-1])`
```{r,fig.height=6,fig.width=6}
g1 = ggplot(dat,
aes(x=ymd_h,y=price_median,col=name)) +
ggthemes::theme_tufte()+
geom_point(size=1,alpha=0.1) +
scale_x_datetime(breaks = date_breaks("6 month"),labels = date_format("%Y-%m")) +
theme(axis.text.x = element_text(angle = 90, vjust=0.5)) +
facet_wrap(~name,scales = "fix",ncol=2) +
ggtitle("Bitcoin prices at most volatile Bitcoin USD markets \n 1 hour interval")
g2 = ggplot(dat,
aes(x=ymd_h,y=ret_median,col=name)) +
ggthemes::theme_tufte()+
geom_point(size=1,alpha=0.3) +
scale_x_datetime(breaks = date_breaks("6 month"),labels = date_format("%Y-%m")) +
theme(axis.text.x = element_text(angle = 90, vjust=0.5)) +
facet_wrap(~name,scales = "free",ncol=2) +
labs(title = "Bitcoin returns at most volatile Bitcoin USD markets \n 1 hour interval - free scale")
g3 = ggplot(dat,
aes(x=ymd_h,y=vol_sum,col=name)) +
ggthemes::theme_tufte()+
geom_point(size=1,alpha=0.1) +
scale_x_datetime(breaks = date_breaks("6 month"),labels = date_format("%Y-%m")) +
theme(axis.text.x = element_text(angle = 90, vjust=0.5)) +
facet_wrap(~name,scales = "free",ncol=2) +
ggtitle("Bitcoin volume at most volatile Bitcoin USD markets \n 1 hour interval - free scale")
g2
```
## Estimation
There was used rJAGS and MSBVAR (offers Bayesian approach for VAR models) packages. Latter package was implement to validate results from JAGS simulation.
Every variable is described by p lags of their own and all others variables. If a variable which represents other market is significant then there is mean spillover effect - some market influence other market prices.
Structural:
$$ A_0y + A_+X = E $$
Reduce form:
$$y_t = c + B_1*y_{t-1} + B_2*y_{t-1} + ... + B_p*y_{t-p} + u_t$$
where:
$$ B_l = A_0^{-1} * A_l \text{ and } u_t = A_0^{-1} * \epsilon_t $$
```{r}
#Coefficients and significance[^1]:
#knitr::kable(tabs)
```
[^1]: where \*,\*\*,\*\*\* is respectively 0.1,0.01,0.001 significance level
```{r}
mod_string = "
data { D <- dim(Z) }
model {
for (i in 3:D[1]) {
for (j in 1:D[2]){
Z[i,j] ~ dnorm(mu[i,j], prec[j])
mu[i,j] = b[1:4,j] %*% Z[i-1,1:4] + b[5:8,j] %*% Z[i-2,1:4] + b[9,j]
}
}
for (j in 1:D[2]){
for (i in 1:(2*D[2]+1)){
b[i,j] ~ dnorm(0.0, 1.0/1.0e6)
}
prec[j] ~ dgamma(1.0/2.0, 1.0*1/2.0)
sig2[j] = 1.0 / prec[j]
sig[j] = sqrt(sig2[j])
}}"
Z = list(Z = as.matrix(bitcoin_spread[bitcoin_spread$ymd_h>=as.Date("2018-01-01"),-1]))
params = c("b")
mod = jags.model(textConnection(mod_string), data=Z, n.chains=3,quiet=T)
update(mod, 50) # burn-in
mod_sim = coda.samples(model=mod,
variable.names=params,
n.iter=500)
mod_csim = do.call(rbind, mod_sim) # combine multiple chains
```
\newpage
Final parameters was chosen in accordance with MSE criteria and MCMC chain characteristics.
Model with two lags was used and uninformative normal and gamma priors (value for variance of returns equal one - which is huge).
Every tested model has (nr_lag\*6\+1)\*6 coefficients, so for two lags there are 78 of them. It is very hard to vizualize properties of final model so you have to belife that it passed all diag tests from the coda package.
Bayesian approach probability that coefficient is smaller/larger than 0, it is calculated as mean of boolen values (0/1) which was calculated form chain for certain coefficient :
```{r}
bigger = apply(mod_csim,2,function(x) mean(x>0))
smaller = apply(mod_csim,2,function(x) mean(x<0) )
coef = apply(mod_csim,2,function(x) mean(x) )
nams = colnames(bitcoin_spread)[-1]
res_bay = matrix(paste0(round(smaller,2),"/",round(bigger,2),ifelse(round(bigger,2)>0.9|round(smaller,2)>0.9,"!!!","")),length(nams),length(nams)*2+1)
rownames(res_bay) = nams
colnames(res_bay) = c(paste0(nams,"_lag1"),paste0(nams,"_lag2"),"intercept")
knitr::kable(t(res_bay))
```
Important relations (p>90%) was highlighted by three exclamation marks (!!!)
```{r}
tab_res = data.frame(impact = as.vector(apply(res_bay,1,function(x) paste(colnames(res_bay)[grepl("!!!",x)],collapse=" "))) , on =nams)
knitr::kable(tab_res)
```
We could observe that there are a few mean spillover effects. This discovery suggested that there could exists a bitcoin market ineffciency. However It will be advisable to perform further examination on this subject. The main reason why arbitrage dont stabilize prices across markets could be high costs of implementing it.