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

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 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


pip install -r requirements.txt

We will create a 3 python file as below.

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

The project structure should be as below

C:/Financial Portfolio Dashboard
CSS files

Building the UI

Let us start adding all the UI components.

Header section

style={"text-align": "left", 'font-size': 30,
'font-weight': 'bold', 'color': '#f8f9fa'}),
className="logo", src= "./assets/dash-logo-new.png"


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

Data picker

id = 'id-start-date',
month_format='YYYY, MM, DD',
placeholder='START DATE',, 2, 2),
style = {"text-align": "center"}

], width = 2, style = box_bound),
id = 'id-end-date',
month_format='YYYY, MM, DD',
placeholder='END DATE',, 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

id = 'id_low_risk',
label="Volatility (%)",

Please access the complete 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):
df = pd.DataFrame()

for i in range(len(ticker)):

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):
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 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

Output('store-data', 'data'),
Output("alert-wip-data", "is_open")

def update_storeData(company, start_date, end_date):
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


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':


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,
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}')

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

Please access the complete 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

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.

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 *