Quickstart to Visualising and Analysing Financial Data with Pandas
One of the best ways to demonstrate the usefulness of the Pandas library is to use it to analyse financial data.
In this notebook, we will compute a few financial measures with Pandas — returns, volatilities and Value at Risk, and visualise/plot these measures.
The comments in the notebook should help you understand the code, but just to explain a few key parts of the code.
First, computing returns. We compute relative returns here. With Pandas, we need not loop through the whole time series. We simply divide the time series data by a shifted time series — i.e. we shift the time series data we have forward by 1, 2 or 3 days (based on our needs). This is pretty simple in Pandas as there is a built in shift function
sgd_series['Returns1'] = sgd_series['High']/sgd_series['Low'].shift(1)-1
Next computing rolling volatilities. If you have any experience doing this, you would most likely remember counting rows in Excel and then dragging down to compute daily rolling volatilities. In Pandas, we just use a built in function rolling_std(time series, window period) to compute the rolling volatilities.
sgd_series['Volatility252_1'] = pd.rolling_std(sgd_series['Returns1'], window=252)
Once you have the volatilities, it’s trivial to compute the Value at Risk. We compute the parametric Value at Risk here, which essentially means that we assume the distribution of returns is normal, and the shape of the curve can be completely specified with just two moments — mean and standard deviation. With the volatility (which is essentially the standard deviation), we just need a multiplier to compute the requisite confidence level. Here we use 2.33 as we want the 99% Value at Risk ( we would apply a multiplier of 2 if we wanted a 95% Value at Risk).
sgd_series['99Volatility252_1'] = sgd_series['Volatility252_1']*2.33
And that’s it. I won’t go into the details on how to plot the measures in the post but there are comments in the notebook to help with that.