How to Build Interactive Dashboard in R shiny for Cryptocurrency Analysis

Posted on Mar 2, 2023

 

Introduction

Oxford Language Dictionary defines bitcoin as “a type of digital currency in which a record of transactions is maintained and new units of currency are generated by the computational solution of mathematical problems, and which operates independently of a central bank." It was first introduced in 2008 as a decentralized currency by Satoshi Nakamoto. Bitcoin (BTC) is the world's most popular cryptocurrency, inspiring the development of many other cryptocurrencies.
In this step-by-step tutorial, we will learn how to build an interactive dashboard in R shiny to track the historic prices of bitcoin. R shiny app is a great analytical tool that can be used for cryptocurrencies and stocks.

Libraries used

I used the following libraries for my app, but you can modify along the way when creating your own version:

library(shiny)
library(shinythemes)
library(lubridate)
library(dygraphs)
library(xts)
library(tidyverse)

Data

The dataset for this project was collected from Kaggle.com. It consists of 2747 observations, 7 variables and covers the period from September 17th of 2014 to March 25th of 2022. It doesn’t have any missing values, so there is no need for cleaning. You can find this dataset by following this link.

Use read.csv() function to load the data from the csv file into data frame:

bitcoin <-read.csv(file = 'BTC-USD.csv', stringsAsFactors = F)

Make sure to convert the “Date” column to year/month/day format:

bitcoin$Date <- ymd(bitcoin$Date)

App Design

R shiny package makes it easy to build interactive web applications with R. You will not need in-depth experience with web development, nor will you need to know html, css or javascript languages.

The structure of the shiny app

R shiny app consists of three parts: ui (user interface) object, server and shinyApp functions. In this tutorial, we will use the single file layout meaning that our app will contain all three components in one single app.R file.

UI

The user interface (UI) object is responsible for the layout and appearance of the application. It starts with fluidPage function as demonstrated below:

ui <- fluidPage(
  theme = shinytheme("cosmo"),

I used the “cosmo” theme for my app, but there are other options you can explore for your app's overall appearance. Find out more by following this link.

Our sidebar panel which appears on the left side of the application contains the following elements:

  • Title of the application
  • 5 variables (open, high, low, close, volume)
  • Date that ranges from September of 2014 to March of 2022
  • The box with the log scale option for price variables only

This can be achieved by using the codes below:

# App title ----
titlePanel(strong("Bitcoin Dashboard")),

sidebarLayout(
 sidebarPanel(
  h4(strong("Bitcoin closing prices 2014-2022")),
  br(),
  selectInput('selectOutput',
         'Select output',
         choices = colnames(bitcoin)[c(2,3,4,5,7)]),
  dateRangeInput('selectDate',
         'Select date',
         start = min(bitcoin$Date),
         end = max(bitcoin$Date)),
  br(),
  br(),
  checkboxInput("logInput", "Plot y axis on log scale", value = FALSE),

 ),

dygraphOutput() function will help us to create the interactive time series graph to visualize the historical prices and the trading volume of bitcoin:

  mainPanel(dygraphOutput("priceGraph", width = "100%", height = "800px"))
 )
)

Server

This is where the magic happens. Server function makes an application reactive to what you defined in the user interface. It typically starts with the code below:

server <- function(input, output) {

Based on the selected date range, the application will visualize the time series interactive graph for open, high, low, close prices along with the trading volume from our dataframe. In other words, our application will be responsive and change the display according to the user input. Please, note the code for converting the variables into log scale will not work on volume output. This was done on purpose.

getData <- reactive({

 # get inputs 
 selectedOutput <- input$selectOutput
 startDate <- input$selectDate[1]
 endDate <- input$selectDate[2]


 # filter data
 data <- bitcoin %>%
  select(Date, selectedOutput) %>%
  filter(Date >= startDate & Date <= endDate)


 # formatting in case of market cap
 if(selectedOutput == "Volume"){
   data["Volume"] <- lapply(data["Volume"], FUN = function(x) x/1000000000)
 }


 # converting to logscale for bitcoin price
 if(input$logInput == TRUE & input$selectOutput != "Volume"){
   data[selectedOutput] = log(data[selectedOutput])

  }

 data
 })

 output$priceGraph <- renderDygraph({
  data <- getData()
  time_series <- xts(data, order.by = data$Date)
  dygraph(time_series)
 })

}

shinyApp 

This is the final step in our web development. This line of code allows us to run the application by binding user interface and server parts.

shinyApp(ui = ui, server = server)

 

Congratulations! You have just developed your application and it is ready to run. I hope this tutorial was helpful. Here is the complete code for the bitcoin tracker app:

Shiny App | Github | LinkedIn 

 

 


About Author

Liliya Lopez

Dedicated professional with comprehensive skills in quantitative science, analysis, research, predictive models, and working with cross-functional teams to achieve goals. Known as an innovative thinker with statistics, data analytics, R and Python development, visualization, machine learning models, and...
View all posts by Liliya Lopez >

Related Articles

Leave a Comment

No comments found.

View Posts by Categories


Our Recent Popular Posts


View Posts by Tags

#python #trainwithnycdsa 2019 2020 Revenue 3-points agriculture air quality airbnb airline alcohol Alex Baransky algorithm alumni Alumni Interview Alumni Reviews Alumni Spotlight alumni story Alumnus ames dataset ames housing dataset apartment rent API Application artist aws bank loans beautiful soup Best Bootcamp Best Data Science 2019 Best Data Science Bootcamp Best Data Science Bootcamp 2020 Best Ranked Big Data Book Launch Book-Signing bootcamp Bootcamp Alumni Bootcamp Prep boston safety Bundles cake recipe California Cancer Research capstone car price Career Career Day citibike classic cars classpass clustering Coding Course Demo Course Report covid 19 credit credit card crime frequency crops D3.js data data analysis Data Analyst data analytics data for tripadvisor reviews data science Data Science Academy Data Science Bootcamp Data science jobs Data Science Reviews Data Scientist Data Scientist Jobs data visualization database Deep Learning Demo Day Discount disney dplyr drug data e-commerce economy employee employee burnout employer networking environment feature engineering Finance Financial Data Science fitness studio Flask flight delay gbm Get Hired ggplot2 googleVis H20 Hadoop hallmark holiday movie happiness healthcare frauds higgs boson Hiring hiring partner events Hiring Partners hotels housing housing data housing predictions housing price hy-vee Income Industry Experts Injuries Instructor Blog Instructor Interview insurance italki Job Job Placement Jobs Jon Krohn JP Morgan Chase Kaggle Kickstarter las vegas airport lasso regression Lead Data Scienctist Lead Data Scientist leaflet league linear regression Logistic Regression machine learning Maps market matplotlib Medical Research Meet the team meetup methal health miami beach movie music Napoli NBA netflix Networking neural network Neural networks New Courses NHL nlp NYC NYC Data Science nyc data science academy NYC Open Data nyc property NYCDSA NYCDSA Alumni Online Online Bootcamp Online Training Open Data painter pandas Part-time performance phoenix pollutants Portfolio Development precision measurement prediction Prework Programming public safety PwC python Python Data Analysis python machine learning python scrapy python web scraping python webscraping Python Workshop R R Data Analysis R language R Programming R Shiny r studio R Visualization R Workshop R-bloggers random forest Ranking recommendation recommendation system regression Remote remote data science bootcamp Scrapy scrapy visualization seaborn seafood type Selenium sentiment analysis sentiment classification Shiny Shiny Dashboard Spark Special Special Summer Sports statistics streaming Student Interview Student Showcase SVM Switchup Tableau teachers team team performance TensorFlow Testimonial tf-idf Top Data Science Bootcamp Top manufacturing companies Transfers tweets twitter videos visualization wallstreet wallstreetbets web scraping Weekend Course What to expect whiskey whiskeyadvocate wildfire word cloud word2vec XGBoost yelp youtube trending ZORI