Risk Measures

The risk module provides a set of risk metrics to measure the risk associated with a portfolio such as Value at Risk (VaR) and Conditional Value at Risk (CVaR).

import pandas as pd
from sqlalchemy import create_engine
from quantmod.timeseries import dailyReturn
from quantmod.risk import RiskInputs, VaRMetrics, VaRAnalyzer

if __name__ == "__main__":
    engine = create_engine("sqlite:///../Nifty50")
    assets = sorted(["ICICIBANK", "ITC", "RELIANCE", "TCS", "ADANIENT"])
    single_stock = "ICICIBANK"
    # Query close price from database
    df = pd.DataFrame()
    for asset in assets:
        query = f"SELECT Date, Close FROM {asset}"
        with engine.connect() as connection:
            df1 = pd.read_sql_query(query, connection, index_col="Date")
            df1.columns = [asset]
        df = pd.concat([df, df1], axis=1)

    logreturn = dailyReturn(df).dropna()
    single_stock_returns = logreturn[[single_stock]].dropna()

    # Portfolio
    portfolio_risk_metrics = VaRMetrics(
        RiskInputs(
            confidence_level=0.95,
            lookback_period=252,
            num_simulations=10000,
            portfolio_weights=[
                0.1212,
                0.1056,
                0.2724,
                0.1506,
                0.3503,
            ],  # This is from lab3
            portfolio_returns=logreturn,
            is_single_stock=False,
        )
    )

    # Single Stock
    single_stock_risk_metrics = VaRMetrics(
        RiskInputs(
            confidence_level=0.95,
            lookback_period=252,
            num_simulations=10000,
            portfolio_weights=None,
            portfolio_returns=single_stock_returns,
            is_single_stock=True,
        )
    )

    # Print results
    print("Portfolio VaR and CVaR for the given confidence level")
    print(f"Parametric VaR : {portfolio_risk_metrics.parametric_var:.4f}")
    print(f"Historical VaR : {portfolio_risk_metrics.historical_var:.4f}")
    print(f"Monte Carlo VaR : {portfolio_risk_metrics.monte_carlo_var:.4f}")
    print(f"Expected Shortfall : {portfolio_risk_metrics.expected_shortfall:.4f}")

    print(
        f"\nSingle Stock ({single_stock}) VaR and CVaR for the given confidence level"
    )
    print(f"Parametric VaR : {single_stock_risk_metrics.parametric_var:.4f}")
    print(f"Historical VaR : {single_stock_risk_metrics.historical_var:.4f}")
    print(f"Monte Carlo VaR : {single_stock_risk_metrics.monte_carlo_var:.4f}")
    print(f"Expected Shortfall : {single_stock_risk_metrics.expected_shortfall:.4f}")

    # VaR Backtest
    backtest_results = VaRAnalyzer(
        inputs=RiskInputs(returns=single_stock_returns, confidence_level=0.99)
    ).run
    print(f"Backtested VaR Results: \n {backtest_results}")