--- title: "Price charts in R" description: "Download cryptocurrency prices in R and draw interactive candlestick charts, compare coins and see their monthly returns." output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Price charts in R} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set(collapse = TRUE, comment = "#>", out.width = "100%", fig.width = 7, fig.height = 5) # The article downloads its prices from CoinMarketCap while it is built. The downloads are # made here first, out of sight, so the chunks below get them from the disk cache, and # without them the code is shown without its results instead of failing the build. online <- tryCatch( { btc <- golemcrypto::get_history("Bitcoin (BTC)", as.Date("2013-04-29")) three <- golemcrypto::get_history(c("Bitcoin (BTC)", "Ethereum (ETH)", "Solana (SOL)")) !is.null(btc) && !is.null(three) && length(unique(three$name_symbol)) == 3 }, error = function(e) FALSE ) knitr::opts_chunk$set(eval = online) ``` `r if (!online) "> The prices could not be downloaded when this page was built, so the code is shown without its results."` The charts of the [golemcrypto app](https://sedzinfo-golemcrypto.share.connect.posit.cloud/) are also R functions. Each one takes the prices you download with `get_history()` and returns an interactive [plotly](https://plotly.com/r/) chart. Run it in the console and the chart opens in the RStudio Viewer or your browser. In an R Markdown or Quarto document it appears in the page. This article shows the price charts. [Volatility, drawdowns and seasonality](analyses.html) shows the charts of the analyses, and [The top 100 coins](market.html) shows the market treemap and table. ## Install and load the package ```{r install, eval = FALSE} install.packages("golemcrypto", repos = c("https://sedzinfo.r-universe.dev", "https://cloud.r-project.org")) ``` ```{r library} library(golemcrypto) ``` The prices need no API key. They come from CoinMarketCap through the crypto2 package. ## Find a coin Coins are picked by their label, such as `"Bitcoin (BTC)"`. `get_coins()` lists all active coins, and its `name_symbol` column holds the labels: ```{r coins} coins <- get_coins() head(coins$name_symbol) grep("^Ethereum", coins$name_symbol, value = TRUE) ``` ## Download the prices `get_history()` downloads the daily prices of one or more coins from a start date on, a year ago by default. CoinMarketCap's data starts on 29 April 2013: ```{r history} btc <- get_history("Bitcoin (BTC)", as.Date("2013-04-29")) tail(btc[, c("timestamp", "open", "high", "low", "close", "volume")]) ``` Each coin's prices are kept on disk between R sessions. Later calls download only the days since the last one, so they are fast. ## Candlestick chart `plot_timeseries()` draws the daily open, high, low and close prices of one coin as candles, with a line through the close and its 50- and 200-day moving averages. The smaller charts underneath show the trading volume and the drawdown: how far the price is below its all-time high so far. ```{r timeseries, fig.height = 9} plot_timeseries(btc) ``` Zoom with the range buttons (1 year, 6 months, 7 days, ...) or the slider under the chart. The Linear and Log buttons switch the axis of the prices, and a click on a legend entry hides or shows that line. The averages and the drawdown are calculated over the history you pass. Pass all of it and zoom on the chart, rather than downloading a shorter history. Choose other moving averages with `averages`, or none with `averages = NULL`. Leave out the drawdown chart with `show_drawdown = FALSE`. A chart of the whole history is large, so this one is not drawn here, to keep the page light: ```{r timeseries-options, eval = FALSE} plot_timeseries(btc, averages = c(20, 100), show_drawdown = FALSE) ``` ## Compare coins To compare several coins, download them together and pass them through `normalize_prices()`. It starts every coin at 100 on the first date on which all of them have data, so 150 means the price rose by half since that date: ```{r compare, fig.height = 7} history <- get_history(c("Bitcoin (BTC)", "Ethereum (ETH)", "Solana (SOL)")) prices <- normalize_prices(history) tail(prices[, c("name_symbol", "timestamp", "close", "index")]) plot_compare(prices) ``` ## Monthly returns `monthly_returns()` turns a coin's prices into a matrix of returns in percent, with a row per year and a column per month. `plot_returns_calendar()` draws it as a heatmap, from red for falls to green for rises: ```{r calendar} returns <- monthly_returns(btc) tail(returns, 3) plot_returns_calendar(returns, "Bitcoin (BTC)") ``` ## Dark mode Every chart function has a `mode` argument. `mode = "dark"` uses light text and grid lines on a transparent background, for a page with a dark background. On this page, which is light, its text would not show, so the code is not run here: ```{r dark, eval = FALSE} plot_timeseries(btc, mode = "dark") ``` ## Save or change a chart The charts are plotly objects, so the functions of the plotly and htmlwidgets packages work on them. To save a chart as a web page that opens in any browser: ```{r save, eval = FALSE} chart <- plot_compare(prices) htmlwidgets::saveWidget(chart, "compare.html") ``` To change the layout, for example to add a title: ```{r layout, eval = FALSE} plotly::layout(chart, title = "Bitcoin, Ethereum and Solana over the last year") ```