-
Notifications
You must be signed in to change notification settings - Fork 1
/
beast.R
40 lines (34 loc) · 1.24 KB
/
beast.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
library(dplyr)
library(xts)
library(Rbeast)
library(DBI)
# Prevent scientific notation
options(scipen=999)
# Decimals to be saved
n_dec <- 7
data_path <- file.path(getwd(), "elaborations")
# Flag for prices or stock
#flag <- "cpi"
flag <- "stock"
con <- dbConnect(RSQLite::SQLite(),
dbname = file.path(data_path, paste0(flag, ".db")))
# Perform BEAST on all tables and save back the results
for (table in dbListTables(con)) {
df <- dbReadTable(con, table)
df$date <- as.Date(df$date, format = "%Y-%m-%d")
ts <- as.xts(df$index, order.by = df$date)
# add missing dates
ts <- merge(ts, seq.Date(min(df$date), max(df$date), by = "week"))
# Compute Beast algorithm
res_beast <- beast(ts, season = "none")
# Setup dataframe for saving
ts$cp_prob <- round(res_beast[["trend"]][["cpOccPr"]], n_dec)
ts$slope_pos <- round(res_beast[["trend"]][["slpSgnPosPr"]], n_dec)
ts$slope_zero <- round(res_beast[["trend"]][["slpSgnZeroPr"]], n_dec)
ts <- data.frame(date=index(ts), coredata(ts))
colnames(ts) <- c("date", "index", "cp_prob", "slope_pos", "slope_zero")
ts$date <- as.character.Date(ts$date)
dbWriteTable(con, table, ts, overwrite = TRUE)
}
# Disconnect from DB
dbDisconnect(conn = con)