Last active
July 11, 2018 22:52
-
-
Save slopp/721e84ba595da5c3dc074a1957aa7929 to your computer and use it in GitHub Desktop.
More complicated plumber API example showing how to parse JSON inputs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(plumber) | |
library(dplyr) | |
library(tidyquant) | |
library(jsonlite) | |
get_volatility <- function(ticker = 'GOOG') { | |
price <- tq_get(ticker, from = "2018-01-01") | |
volatility <- price %>% | |
select(date, adjusted) %>% | |
mutate(returns = (log(adjusted) - log(lag(adjusted)))) %>% | |
na.omit() %>% | |
summarize(volatility = var(returns)) %>% | |
pull(volatility) | |
return(volatility) | |
} | |
get_volatilities <- function(json_input) { | |
tickers <- fromJSON(json_input) | |
volatilities <- sapply(tickers, get_volatility) | |
volatilities | |
} | |
# create test inputs using toJSON | |
#tickers <- c('GOOG', 'TSLA') | |
#test_input <- toJSON(tickers) | |
#get_volatilities(test_input) | |
#* @apiTitle Stock Volatilities | |
#* Return the stock volatilties for the input stock tickers | |
#* @put /volatilities | |
function(req) { | |
print(req$postBody) | |
get_volatilities(req$postBody) | |
} | |
#* @apiTitle Stock Volatility | |
#* Return the stock volatiltiy for the input stock ticker | |
#* @param ticker The stock ticker | |
#* @get /volatiltiy | |
function(ticker = 'GOOG') { | |
get_volatility(ticker) | |
} | |
## Sample Requests: | |
# curl -X PUT "http://ec2-54-202-230-54.us-west-2.compute.amazonaws.com/content/2/volatilities" -H "accept: application/json" --data '["GOOG","TSLA"]' | |
# curl -X GET "http://ec2-54-202-230-54.us-west-2.compute.amazonaws.com/content/2/volatiltiy?ticker=TSLA" -H "accept: application/json" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment