How to Develop a Stock Market Analytical Tool using Shiny and R

Sergey Malchevskiy
Apr 17, 2018 · 6 min read

I’ve been developing once an analytical tool for analyzing the Russian stock market. The purpose was building CAPM for stocks that are included in RTSI. I carried out this analytical pipeline in R: data recieving, CAPM calculation, and chart drawing. It was implemented as R script. I periodically launched this script to apply in an investment decision-making. It looked something like this:

R script and SML plot

This project had been solving a problem, but it was a little inconvenient. First of all, it needs R environment. The main issue is data manipulation, such as changing a period of analysis, ordering of a result, and etc. For these purposes, I had to change lines of code. Eventually, I decided to build an interactive graphical solution to automate routine operations using Shiny web framework.

CAPM solution and Shiny web framework

Introduction to CAPM

The capital asset pricing model (CAPM) is a model that describes the relationship between systematic risk and expected return for assets, particularly stocks. CAPM is widely used throughout finance for the pricing of risky securities, generating expected returns for assets given the risk of those assets and calculating costs of capital. Read more here.

Expected return formula

Beta for i-th stock is

Beta formula

Alpha or Jensen Index (invented my Michael Jensen in the 1970s) is an index that is used in some financial models such as the CAPM to determine the highest possible return on an investment for the least amount of risk.

In other words, Alpha measures how well an investment performed compared to its benchmark.

Alpha formula

The security market line (SML) is a line drawn on a chart that serves as a graphical representation of the CAPM, which shows different levels of systematic, or market, risk of various marketable securities plotted against the expected return of the entire market at a given point in time. Also known as the “characteristic line,” the SML is a visual of the CAPM, where the x-axis of the chart represents risk in terms of beta, and the y-axis of the chart represents expected return. The market risk premium of a given security is determined by where it is plotted on the chart in relation to the SML. Read more here.

The security market line is commonly used by investors in evaluating a security for inclusion in an investment portfolio in terms of whether the security offers a favorable expected return against its level of risk. When the security is plotted on the SML chart, if it appears above the SML, it is considered undervalued because the position on the chart indicates that the security offers a greater return against its inherent risk. Conversely, if the security plots below the SML, it is considered overvalued in price because the expected return does not overcome the inherent risk.


What is Shiny?

Shiny’s examples

Shiny is an open source R package that provides an elegant and powerful web framework for building web applications using R. Shiny helps you turn your analyses into interactive web applications without requiring HTML, CSS, or JavaScript knowledge.

You can can find here a lot of interactive examples. First steps to get started are described here.


UI part

UI code is contained in ui.R file. First of all, we should decide what UI elements will be presented on the main webpage:

· Parameters. This block contains input parameters for analysis (index ticker, file contained stock tickers, risk-free rate, time period, and so on).

Parameters

· Output table. This table presents key values of done analysis for a particular stock (alpha, beta, return, adjusted R-squared, etc.).

Result table

· Plots. This block visualizes the data of research (stock market line plot, alpha distribution histogram, scatter plot of market and stock prices, price plot).

Examples of plots

The next code allows to define these UI elements:


Server part

Code for data downloading, calculation expressions, and charts building should be implemented in server.R file. Main function looks like this:

Other code of server logics is placed inside this function.

Our solution has the set of parameters. When one parameter has been changed, the entire analysis must be recalculated. Reactive expressions are using for this purposes. The reactive expression will update this value whenever the original widget changes. To create a reactive expression use the reactive function, which takes an R expression surrounded by braces (just like the render* functions).

Next code carries out the calculation pipeline of analysis:

As the result of this code, generalData object contains the completed data for the next visualization and demonstration. For long operations it is convenient to use withProgress function that displays the status of the process.

Progress bar

This code block presents the result table and uses advanced JS-code and DataTable library to change a color of rows depending on alpha value:

Undervalued stocks are marked by green color, and overvalued ones by red.

Most of the charts are using ggplot2 library, but price plot with two Y-axes is using plotly library. Further, ggplot2 charts are converted to plotly format by ggplotly function. It allows getting a similar appearance and interactive behavior as plotly chart.

This code processes the clicks on buttons for changing a time period and it is using observeEvent:


Deployment

I used shinyapps.io for deploying my web application to the Internet (free plan). This is a self-service platform that makes it easy for you to share your shiny applications on the web in just a few minutes. The service runs in the cloud on shared servers that are operated by RStudio. Each application is self-contained and operates on either data that is uploaded with the application, or data that the code pulls from third-party data stores, such as databases or web services.

Admin panel

This tutorial is what you need to get started with shinyapps.io.


Summary

In this article I showed how to easily turn some research into an interactive tool from scratch. Eventually my solution looks like this:

Shiny automatically tries to adopt a user interface to mobile screen resolutions:

CAPM solution (mobile version)

This web application is located here. Theoretically, might be some access troubles due to free plan (limited server time or high load). Code of project is allowed on GitHub.

I would be glad if this practical case helped you.

Sergey Malchevskiy

Written by

Data science, quantitative finance http://malchevskiy.pro

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade