In our 3 previous posts, we walked through how to calculate portfolio volatility, then how to calculate rolling volatility, and then how to visualize rolling volatility. Today, we will wrap all of that work into a Shiny app that allows a user to construct his or her own five-asset portfolio, choose a benchmark and a time period, and visualize the rolling volatilities over time.
Here is the final app:
There will be a slight departure in form today because we will use a helpers.r file to hold our functions - those same functions that we worked so hard to create in the previous three posts. There are a few reasons to put them into a helper file.
The end user won’t be able to see them, which leads to a tangent on the idea of reproducibility. We need to ask, “Reproducible by whom?”. In this case, the Shiny app is 100% reproducible by anyone who has access to that helper file, which would be my colleagues with access to my files or Github repository. But, if the end user is an external client, for example, that end user wouldn’t have access and the analytic functions would remain a black box. In the world of finance, that’s necessary most of the time.
From a workflow perspective, that helper file allows us to test those functions in different formats. I can create an R Markdown report that uses the file, test different Shiny apps, or tweak the functions themselves without having to alter the actual application code.
From a stylistic perspective, the helper file keeps the Shiny app code a bit cleaner and much shorter. It’s not right or wrong to use a helpers file, but it’s worth thinking about as our Shiny apps get more involved.
Here’s how we load that file and have access to the functions and objects in it:
source(&quot;function-folder/simple-vol-helpers.r&quot;)
Since this is a blog post and we want to be complete, the code chunk below contains all the code from that simple-vol-helpers.r file.
# Calculate component returns
componentReturns_df %
`colnames% select(date, everything())
}
# Calculate rolling Portfolio Standard Deviation
rolling_portfolio_sd