-
Notifications
You must be signed in to change notification settings - Fork 3
/
bitcoin_anomalies.r
34 lines (28 loc) · 1.12 KB
/
bitcoin_anomalies.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
# Source: https://towardsdatascience.com/tidy-anomaly-detection-using-r-82a0c776d523
# Author: AbdulMajedRaja RS - https://towardsdatascience.com/@amrwrites
# See https://github.com/amrrs/anomaly_detection_tidy_way/
library(anomalize) #tidy anomaly detectiom
library(tidyverse) #tidyverse packages like dplyr, ggplot, tidyr
library(coindeskr) #bitcoin price extraction from coindesk
btc <- get_historic_price(start = "2017-01-01")
#Convert to time series
btc_ts <- btc %>% rownames_to_column() %>% as_tibble() %>%
mutate(date = as.Date(rowname)) %>% select(-one_of('rowname'))
head(btc_ts)
#Decompose time series
btc_ts %>%
time_decompose(Price, method = "stl", frequency = "auto", trend = "auto") %>%
anomalize(remainder, method = "gesd", alpha = 0.05, max_anoms = 0.2) %>%
plot_anomaly_decomposition()
# Detect anomalies
btc_ts %>%
time_decompose(Price) %>%
anomalize(remainder) %>%
time_recompose() %>%
plot_anomalies(time_recomposed = TRUE, ncol = 3, alpha_dots = 0.5)
# Extract anomaly obervations
btc_ts %>%
time_decompose(Price) %>%
anomalize(remainder) %>%
time_recompose() %>%
filter(anomaly == 'Yes')