Personalized Portfolio Risk Analysis: Python VaR Simulator App to Safeguard Your Investments

Assess and Control Investment Risks Effectively with a Tailored VaR Simulation Tool in Python

In this blog, we will cover the below topics

  • Overview of the application
  • How to set up a project with all the dependencies
  • Building the user interface (UI)
  • Developing server-side logic (Server)
  • Establishing interactivity between the UI and the server
  • Visualizing the interactivity
  • Steps to run the application

By the end of the blog, we will have a working application as below.

Source: Author

As a pre-requisite, I recommend reading my previous blogs Risk Management Of Stocks Using Python and How To Build A Financial Portfolio Using PythonThis would help with a basic understanding of the financial portfolio, calculation of returns, value at risk, building a portfolio, and optimization but please feel free to continue reading.

Overview of the app

The objective of the app is to enable value at risk(VaR) risk assessment of the portfolio. The Value at Risk (VaR) is the most common metric used by an individual, firms, and banks to determine the extent of potential financial loss for a given period. Financial institutions use VaR to assess the risk associated with an investment to evaluate whether they have sufficient funds to cover potential losses, it also helps risk managers to re-evaluate and adjust their investments to reduce the risk of higher losses. The typical question that VaR helps answer is what is the maximum loss on investment of 100,000 over one year with a confidence of 95% ? or What is the probability that losses will be more than 3% next year? The standard way of representing these scenarios is in the form of a normal distribution which makes the analysis and interpretation much easier.

We will build a python app that will let us play with different combinations of stocks, and periods to evaluate to visualize the risk in the selected portfolio.

How to set up a project with all the dependencies

Create a virtual environment by the name

pip install virtualenv
virtualenv venv_portfolio
venv_portfolio\scripts\activate

Loading Python Packages

Once, the environment is ready, we will load the libraries. We can install these packages individually with the below command or use the requirement.txt from Github.

import dash
import pandas as pd
import numpy as np
import dash_daq as daq
import plotly.graph_objs as go
import plotly.express as px
import plotly.figure_factory as ff
from dash import Dash, html, dcc
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output, State

or

pip install -r requirements.txt

We will create a 3 python file as below.

  • layout.py — This file holds all the components needed on the UI
  • dataload.py — This file has all the data loading and processing logic
  • app.py — This file binds the front end (layout.py) and the backend (dataload.py) at the run time to load the app on the browser

The project structure should be as below

C:/Financial Portfolio Dashboard
| app.py
| dataload.py
| layout.py
|
\---assets
CSS files
\---venv_portfolio
layout.py

Building the UI

Let us start adding all the UI components.

Header section

    dbc.Row([
dbc.Col([
html.H1("VALUE AT RISK(VaR) SIMULATOR",
style={"text-align": "left", 'font-size': 30,
'font-weight': 'bold', 'color': '#f8f9fa'}),
html.Div(
className="div-logo",
children=html.Img(
className="logo", src= "./assets/dash-logo-new.png"
),
),

])

], className="study-browser-banner row"),

Data picker

dbc.Col([
dcc.DatePickerSingle(
id = 'id-start-date',
month_format='YYYY, MM, DD',
placeholder='START DATE',
date=datetime.date(2022, 2, 2),
style = {"text-align": "center"}
),

], width = 2, style = box_bound),
dbc.Col([
dcc.DatePickerSingle(
id = 'id-end-date',
month_format='YYYY, MM, DD',
placeholder='END DATE',
date=datetime.date(2023, 2, 2),
style = {"text-align": "center"}
)

], width = 2, style = box_bound),

DAQ components

We will use the LED component from DAQ for displaying the metrics

            dbc.Row([
dbc.Col([
daq.LEDDisplay(
id = 'id_low_risk',
label="Volatility (%)",
color="#FF5E5E",
labelPosition='top',
backgroundColor="#f2f2f2"
)
])
])

Please access the complete layout.py file from GitHub

Building the server-side logic

Data loading from NSEPY

We will use nsepy but feel free to use other APIs like yahoo finance or even load the data from a CSV file.

def load_stock_data(start_date, end_date, ticker):
try:
df = pd.DataFrame()

for i in range(len(ticker)):
....
data.rename(columns={'Close':data['Symbol'][0]},inplace=True)

return df
except Exception as e:
print(f'An exception occurred while executing data load: {e}')

Portfolio simulation logic

def sim_portfolio(weights, dd_returns):
try:
tmp_pp = (weights * dd_returns.values).sum(axis=1)
var_sim_port = np.percentile(tmp_pp, 5, interpolation = 'lower')
return var_sim_port
except Exception as e:
print(f'An exception occurred while executing sim_portfolio: {e}')

Please access the complete dataload.py file from GitHub

Establishing interactivity

Now, that we have UI and server logic in place, let us stitch them together with callbacks.

Update the DCC store

@app.callback(
[
Output('store-data', 'data'),
Output("alert-wip-data", "is_open")
],
[
Input("id-company-dropdown","value"),
Input("id-start-date","date"),
Input("id-end-date","date")
]

)
def update_storeData(company, start_date, end_date):
........
try:
dataset = dataload.load_stock_data(s_date, e_date, company)

dataset.reset_index(inplace = True)
return dataset.to_dict('records'), True
except Exception as e:
print(f'An exception occurred while updating the
data store: {e}')

Updating the DAQ components and the allocation(%) chart


@app.callback(

[
Output("id_low_risk", 'value'),
Output("id_high_risk", 'value'),
Output("fig_allocation_low", 'figure'),
Output("alert-wip", "is_open"),
Output("fig_allocation_high", 'figure'),
Output("id-info_low", 'children'),
Output("id-info_high", 'children'),

],
[
Input('id-btn-create', 'n_clicks'),
State('id-company-dropdown', 'value'),
State('store-data', 'data'),
State("alert-wip", "is_open")

],
prevent_initial_call = True
)
def update_allocation(btn_create, company, data, val_is_open):


if button_id == 'id-btn-create':

try:


fig_allocation_low_risk = px.pie(values = low_risk_wts, names = company, hole= 0.3)
fig_allocation_high_risk = px.pie(values = high_risk_wts, names = company, hole= 0.3)

return [low_risk_volatility,
high_risk_volatility,
fig_allocation_low_risk,
True,
fig_allocation_high_risk,
html.Div(f'At 95% confidence, the maximum loss expected will be {low_risk_volatility} %', id="id-info_low",style={'display': 'block', 'color': 'blue', 'fontSize': 15, 'font-weight': 'bold', "text-align": "center"}),
html.Div(f'At 95% confidence, the maximum loss expected will be {high_risk_volatility} %', id="id-info_low",style={'display': 'block', 'color': 'blue', 'fontSize': 15, 'font-weight': 'bold', "text-align": "center"}),
]


except Exception as e:
print(f'An exception occurred while executing update_trendsChart(): {e}')

else:
return [None, None, layout.blank_fig(), None,layout.blank_fig(), None, None]

Please access the complete app.py file from GitHub

Visualizing the interactivity

Plotly dash has a very nice feature that lets us visualize the interactivity between the components along with the run time.

Source: Author

How to run the application

If you have reached this far and faced no errors along the way, the next steps should allow you to run the application.

Step1: Open the terminal, navigate to the project directory

Step 2: Type the below command

<working directory>python app.py

Step 3: The terminal will run the application.

Source: Author

Step 4: Navigate to the browser and type the localhost URL. The app will be loaded as shown below and click on the CREATE button.

http:127.0.0.1:8050
Source: Author

Closing thoughts

We have successfully built our simulator app with a plotly dash that serves our purpose of experimenting with various combinations of stocks or periods. In a short time, we generated two extreme scenarios, one portfolio which is recommended (low risk) and one to be avoided (high risk). The result from every other combination of weights would fall between these two scenarios. A similar dashboard can also be developed using BI tools like Power BI or Tableau but the core logic would remain the same.

The application can be extended with additional features such as

  • Bring the fundamentals metrics like PE, PB ratios, etc
  • Implement efficient frontier
  • Add more interactivity for the user eg: Let the user select the stock weights

I hope you liked the article and it encouraged you enough to build an app of your own.

You can connect with me — on Linkedin and Github

Leave a Reply

Your email address will not be published. Required fields are marked *