Skip to content

Instantly share code, notes, and snippets.

@vmesel
Created January 24, 2019 10:29
Show Gist options
  • Save vmesel/1d9fb63b124ae81847eb336553c6d729 to your computer and use it in GitHub Desktop.
Save vmesel/1d9fb63b124ae81847eb336553c6d729 to your computer and use it in GitHub Desktop.
client_id <- "ABC"
install.packages("mongolite") # Instala o mongolite (biblioteca de conn com o mongo)
install.packages("tidyverse") # Instala o Tidyverse (biblioteca de filtros e aggs)
library(mongolite)
library(tidyverse)
# Pega cotacoes no MongoDB
cotacoes_con <- mongo(collection="cotacoes", db="database", url = "mongodb://readwrite:[email protected]:43942/aaaaa")
cotacoes <- cotacoes_con$find()
cotacoes_con$drop()
# Pega as movimentacoes de um cliente no MongoDB
movs_con <- mongo(collection="cotacoes", db="database", url = "mongodb://readwrite:[email protected]:43942/aaaaa")
movs <- movs_con$find('{"cliente": "', client_id, '"}')
movs_con$drop()
# Filtra movimentacoes do mes para poder guardar detalhadamente
movs_detalhadas <- movs %>% filter(data >= "2018/01/02" & data <= "2018/01/31")
# Transforma dataframe de formato de movimentações para formato requerido abaixo (c("data", "pl", "movs", "cota"))
# Cotizacao DF formatado c("data", "pl", "movs", "cota")
x <- data.frame("data" = c(as.Date('2018/01/01'), as.Date('2018/01/02'), as.Date('2018/01/03'), as.Date('2018/01/04'), as.Date('2018/01/05')) ,"pl" = c(100,101,102,103, 100), "movs" = c(100, 0, 0, 0, -4))
x$cota <- 100
for(i in 1:nrow(x)) {
if (i > 1){
x[i,]$cota <- ((x[i,]$pl - x[i,]$mov)/x[i-1,]$pl) * x[i-1,]$cota
}
}
x$qt <- x$pl / x$cota
# Plota grafico do data frame e faz linha de tendencia para cotas
print(x)
plot(x$data, x$cota)
abline(lm(x$cota ~ x$data))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment