# Analyzing Bitcoin in R - Part 8 - Calculating and plotting statistics, rolling windows

Pub: 04.12.17

In Finance.

Tags: coding r bitcoin analysis .

Rolling windows allow you to see changes in time series dynamics over time.

# rolling stuff
sdannual <- rollapply(dailyret, width = 250, FUN = sd.annualized)
sharpeannual <- rollapply(dailyret, width = 250, FUN = SharpeRatio.annualized)

meandaily <- rollapply(dailyret, width = 250, FUN = mean)
sddaily <- rollapply(dailyret, width = 250, FUN = sd)


Calculate a rolling correlation between the two.

cormeansd <- rollapply(data.frame(meandaily, sddaily), 250, function(x) cor(x[,1], x[,2]), by.column = FALSE)


Gather the data together for plotting.

plotdata <- merge(meandaily, sddaily, as.matrix(c(rep(NA, 249), cormeansd)))
colnames(plotdata) <- c("Mean", "Std.Dev.", "Correlation")

# plot with horizontal long run mean
png('btc_plot_daily_rolling1.png')
par(mfrow = c(3,1))
par(mar = c(3, 2, 3, 2))
plot(plotdata$Mean) abline(h = mean(meandaily, na.rm = TRUE), col = 2, lty = 3) plot(plotdata$Std.Dev.)
abline(h = mean(sddaily, na.rm = TRUE), col = 2, lty = 3)
plot(plotdata$Correlation) abline(h = mean(cormeansd, na.rm = TRUE), col = 2, lty = 3) dev.off() To show how the mean, standard deviation, and correlation move in patterns over time (compared to random data), we can do the following: png('btc_plot_daily_rolling2.png') par(mfrow = c(3,1)) par(mar = c(4, 4, 4, 2)) plot(x = as.vector(plotdata$Mean), y = as.vector(plotdata$Std.Dev.), pch=20) plot(x = as.vector(plotdata$Mean), y = as.vector(plotdata$Correlation), pch=20) plot(x = as.vector(plotdata$Std.Dev.), y = as.vector(plotdata\$Correlation), pch=20)
dev.off() The classic plot of previous days returns to next days returns shows very little structure.

T <- nrow(dailyret)
png('btc_plot_daily_lagscatter.png')
plot(x = as.vector(dailyret[1:(T-1)]), y = as.vector(dailyret[2:T]), pch = 20)
dev.off() png('btc_plot_daily_acf.png')
par(mfrow = c(2,1))
acf(dailyret, na.action = na.pass)
pacf(dailyret, na.action = na.pass)
dev.off() For fun, I will next show you what kind of technical analysis indicators there are: Technical analysis plots of Bitcoin