import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import numpy as np
from datetime import datetime, timedelta
# App Title
st.title("🛡️ Treasury Counterparty Exposure Monitor with Limits")
st.markdown("---")
# Sidebar for configuration
st.sidebar.header("Configuration")
counterparties = st.sidebar.text_area(
"Enter Counterparties (CSV format: Name,Limit,Current_Exposure)",
value="JPMorgan,50_000_000,25_000_000\nGoldman Sachs,30_000_000,18_000_000\nCitibank,40_000_000,5_000_000\nHSBC,20_000_000,22_000_000",
height=150
)
# Simulation toggle
simulate_data = st.sidebar.checkbox("Enable Real-Time Simulation (auto-updates every 5s)", value=True)
# Parse counterparties data
@st.cache_data
def load_data(counterparty_input):
try:
df = pd.read_csv(pd.compat.StringIO(counterparty_input), names=['Name', 'Limit', 'Current_Exposure'])
df['Limit'] = pd.to_numeric(df['Limit'].str.replace('_', ''))
df['Current_Exposure'] = pd.to_numeric(df['Current_Exposure'].str.replace('_', ''))
df['Utilization_%'] = (df['Current_Exposure'] / df['Limit'] * 100).round(2)
df['Status'] = df['Utilization_%'].apply(lambda x: '🟢 OK' if x < 80 else '🟡 Warning' if x < 100 else '🔴 Breached')
df['Breached'] = df['Utilization_%'] >= 100
return df
except:
st.error("Invalid CSV format. Use: Name,Limit,Current_Exposure (e.g., JPMorgan,50000000,25000000)")
return pd.DataFrame()
df = load_data(counterparties)
# Real-time simulation (random walk for demo)
if simulate_data and not df.empty:
def simulate_exposures():
new_df = df.copy()
for idx in new_df.index:
change = np.random.normal(0, new_df.loc[idx, 'Limit'] * 0.01) # ±1% volatility
new_df.loc[idx, 'Current_Exposure'] = max(0, new_df.loc[idx, 'Current_Exposure'] + change)
new_df['Utilization_%'] = (new_df['Current_Exposure'] / new_df['Limit'] * 100).round(2)
new_df['Status'] = new_df['Utilization_%'].apply(lambda x: '🟢 OK' if x < 80 else '🟡 Warning' if x < 100 else '🔴 Breached')
new_df['Breached'] = new_df['Utilization_%'] >= 100
return new_df
df = simulate_exposures()
# Main Dashboard
if not df.empty:
col1, col2, col3 = st.columns(3)
total_exposure = df['Current_Exposure'].sum()
total_limit = df['Limit'].sum()
breaches = df['Breached'].sum()
with col1:
st.metric("Total Exposure", f"${total_exposure:,.0f}", delta=None)
with col2:
st.metric("Total Limit", f"${total_limit:,.0f}", delta=None)
with col3:
st.metric("Breaches", breaches, delta=None)
st.markdown("---")
# Exposure Table
st.subheader("Counterparty Exposures")
st.dataframe(
df[['Name', 'Current_Exposure', 'Limit', 'Utilization_%', 'Status']],
use_container_width=True,
column_config={
"Current_Exposure": st.column_config.NumberColumn("Exposure", format="$%.0f", help="Current net exposure"),
"Limit": st.column_config.NumberColumn("Limit", format="$%.0f"),
"Utilization_%": st.column_config.ProgressColumn("Utilization", format="%d%%", width="medium"),
"Status": st.column_config.StatusColumn("Status")
}
)
# Breaches Alert
if breaches > 0:
st.error(f"🚨 **{breaches} LIMIT BREACH(ES)!** Review immediately.")
breached_df = df[df['Breached']]
st.dataframe(breached_df[['Name', 'Current_Exposure', 'Limit', 'Utilization_%']])
st.markdown("---")
# Visualizations
st.subheader("Visualizations")
col1, col2 = st.columns(2)
with col1:
fig_bar = px.bar(
df, x='Name', y='Utilization_%',
color='Status', title="Utilization by Counterparty",
color_discrete_map={'🟢 OK': 'green', '🟡 Warning': 'orange', '🔴 Breached': 'red'}
)
fig_bar.add_hline(y=100, line_dash="dash", line_color="red", annotation_text="Limit")
fig_bar.add_hline(y=80, line_dash="dot", line_color="orange", annotation_text="Warning")
st.plotly_chart(fig_bar, use_container_width=True)
with col2:
fig_pie = px.pie(df, values='Current_Exposure', names='Name', title="Exposure Distribution")
st.plotly_chart(fig_pie, use_container_width=True)
# Risk Heatmap
st.subheader("Risk Heatmap")
fig_heatmap = px.imshow(
df.set_index('Name')[['Utilization_%']].T,
color_continuous_scale='RdYlGn_r',
title="Utilization Heatmap (%)"
)
st.plotly_chart(fig_heatmap, use_container_width=True)
# Update timestamp
st.caption(f"Last updated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
# Export
st.download_button(
label="📥 Export Report (CSV)",
data=df.to_csv(index=False).encode('utf-8'),
file_name=f"treasury_exposure_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
mime='text/csv'
)
else:
st.warning("👆 Enter counterparty data in the sidebar to get started.")
# Instructions
with st.expander("ℹ️ How to Use & Extend"):
st.markdown("""
### Quick Start
1. **Run the app**: `pip install streamlit pandas plotly numpy` then `streamlit run this_script.py`
2. **Edit data** in sidebar (supports millions/billions with `_` separator, e.g., `1_000_000_000`).
3. **Simulation**: Toggle for demo random changes (mimics market moves).
### Key Features
- **Real-time monitoring** with status colors (OK <80%, Warning 80-100%, Breached >100%).
- **Breaches highlighted** with alerts.
- **Interactive charts** (hover for details).
- **Export reports**.
### Extend It
- **Database Integration**: Replace `load_data()` with SQL query (e.g., via `sqlalchemy`).
- **Real Feeds**: Add APIs (e.g., Bloomberg, internal treasury system) in `simulate_exposures()`.
- **Alerts**: Integrate Slack/Email with `smtplib` or `slack_sdk` on breaches.
- **Netting**: Add columns for gross/long/short and compute `Net_Exposure = abs(long - short)`.
- **Tenor Limits**: Add maturity buckets and sub-limits.
- **Custom Rules**: Modify `Status` logic for VaR, concentration, etc.
Built by Sherlock 🕵️♂️ | Trailblazer Labs
""")
🚀 Quick Setup & Run
- Save as
treasury_monitor.py.
- Install deps:
pip install streamlit pandas plotly numpy.
- Run:
streamlit run treasury_monitor.py.
- Open browser to
localhost:8501.
This is a production-ready dashboard for treasury teams:
- Monitors exposures vs. limits in real-time.
- Alerts on breaches with color-coded status.
- Interactive viz (bar, pie, heatmap).
- Demo simulation for testing (toggle off for live data).
- Extensible for DB/API integrations.
Ping me for customizations like Oracle DB hooks or email alerts! 🛡️