MinsaitEU's picture
Claude Opus 5.5
Load VaR inputs from the Coral zip; add backtesting and stress tests
cbdae8d
Raw History Blame Contribute Delete
3.65 kB
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from data.schema import Out
def metrics_dataframe(metrics):
df = pd.DataFrame(metrics)
return df
def plot_loss_distribution(
metrics,
):
df = pd.DataFrame(metrics)
df[Out.CONFIDENCE] = (
df[Out.CONFIDENCE] * 100
)
fig = px.bar(
df,
x=Out.CONFIDENCE,
y=Out.VAR,
title="VaR by Confidence Level",
text=Out.VAR,
)
fig.update_layout(
template="plotly_white",
xaxis_title="Confidence Level (%)",
yaxis_title="VaR",
)
return fig
def plot_var_es(
metrics,
):
df = pd.DataFrame(metrics)
df[Out.CONFIDENCE] = (
df[Out.CONFIDENCE] * 100
)
fig = go.Figure()
fig.add_trace(
go.Bar(
x=df[Out.CONFIDENCE],
y=df[Out.VAR],
name=Out.VAR,
)
)
fig.add_trace(
go.Bar(
x=df[Out.CONFIDENCE],
y=df[Out.ES],
name=Out.ES,
)
)
fig.update_layout(
title="VaR vs Expected Shortfall",
xaxis_title="Confidence Level (%)",
yaxis_title="Loss",
barmode="group",
template="plotly_white",
)
return fig
def plot_component_var(component_metrics, level="Item"):
"""
Bar chart of Component VaR by item (plant, factor, ...).
"""
df = pd.DataFrame(component_metrics)
if df.empty:
raise ValueError(
"No Component VaR results to plot."
)
confidence = df[Out.CONFIDENCE].iloc[0] * 100
df = df.sort_values(
Out.COMPONENT_VAR,
ascending=True,
)
fig = px.bar(
df,
x=Out.COMPONENT_VAR,
y=Out.ITEM,
orientation="h",
text=Out.COMPONENT_VAR,
title=(
f"Component VaR by {level} "
f"({confidence:.1f}% confidence)"
),
hover_data=[
Out.STANDALONE_VAR,
Out.CONTRIBUTION,
Out.DIVERSIFICATION,
Out.COMPONENT_ES,
],
)
fig.add_vline(
x=0,
line_color="black",
line_width=1,
)
fig.update_layout(
template="plotly_white",
xaxis_title="Component VaR",
yaxis_title=level,
)
return fig
def plot_component_var_contribution(
component_metrics,
level="Item",
):
"""
Bar chart of percentage contribution to portfolio VaR.
Negative contributions can indicate hedging effects.
"""
df = pd.DataFrame(component_metrics)
if df.empty:
raise ValueError(
"No Component VaR results to plot."
)
confidence = df[Out.CONFIDENCE].iloc[0] * 100
df = df.sort_values(
Out.CONTRIBUTION,
ascending=True,
)
fig = px.bar(
df,
x=Out.CONTRIBUTION,
y=Out.ITEM,
orientation="h",
text=Out.CONTRIBUTION,
title=(
f"VaR Contribution by {level} "
f"({confidence:.1f}% confidence)"
),
hover_data=[
Out.COMPONENT_VAR,
Out.PORTFOLIO_VAR,
Out.STANDALONE_VAR,
],
)
fig.add_vline(
x=0,
line_color="black",
line_width=1,
)
fig.update_layout(
template="plotly_white",
xaxis_title="Contribution to Portfolio VaR (%)",
yaxis_title=level,
)
return fig