import streamlit as st
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
import numpy as np
from datetime import datetime, timedelta
import random
# ==========================================
# 1. CONFIGURATION & SIMULATION ENGINE
# ==========================================
st.set_page_config(page_title="Intraday Liquidity Cockpit", layout="wide")
# Simulated Time
if "current_time" not in st.session_state:
st.session_state.current_time = datetime.now().replace(hour=8, minute=0, second=0)
def generate_payment_queue():
"""Simulates a dataframe of pending payments"""
data = []
channels = ['RTGS', 'SWIFT', 'SEPA', 'CLS']
statuses = ['Pending', 'Awaiting Funds', 'Compliance Check']
for _ in range(random.randint(10, 30)):
channel = random.choice(channels)
amount = random.uniform(10000, 50000000)
priority = "High" if amount > 10000000 else "Normal"
status = random.choice(statuses)
# Logic: High value payments more likely to be stuck waiting for funds
if amount > 40000000: status = "Awaiting Funds"
age = random.randint(1, 30) # minutes in queue
data.append({
"ID": f"TX{random.randint(100000, 999999)}",
"Channel": channel,
"Amount ($M)": round(amount / 1_000_000, 2),
"Priority": priority,
"Status": status,
"Age (Min)": age
})
return pd.DataFrame(data)
def generate_liquidity_curve():
"""Simulates the intraday liquidity balance"""
times = [datetime.now().replace(hour=8, minute=0) + timedelta(minutes=i*15) for i in range(40)]
balances = []
current_balance = 5_000_000_000 # Start with 5 Billion
for t in times:
# Simulate heavy outflows in the morning
change = random.uniform(-500_000_000, 200_000_000)
# Simulate a market stress scenario around midday
if 11 <= t.hour < 13:
change -= random.uniform(100_000_000, 400_000_000)
current_balance += change
balances.append(current_balance / 1_000_000) # Convert to Millions
df = pd.DataFrame({"Time": times, "Balance ($M)": balances})
# Add a threshold line
df["Threshold ($M)"] = 500 # Critical minimum
return df
def generate_collateral():
return {
"Central Bank Reserves": {"Total": "5.2B", "Available": "1.1B", "Pledged": "4.1B"},
"HQLA Securities (L1)": {"Total": "12.5B", "Available": "8.2B", "Pledged": "4.3B"},
"Corporate Bonds (L2)": {"Total": "3.0B", "Available": "2.9B", "Pledged": "0.1B"}
}
# ==========================================
# 2. DASHBOARD UI
# ==========================================
st.title("🚀 Intraday Liquidity Monitoring Cockpit")
st.markdown(f"**Simulation Time:** {st.session_state.current_time.strftime('%Y-%m-%d %H:%M:%S')} | **Currency:** USD")
# --- TOP ROW: KEY METRICS ---
st.subheader("System Health Overview")
col1, col2, col3, col4 = st.columns(4)
# Logic to calculate metrics for display
sample_queue = generate_payment_queue()
blocked_funds = sample_queue[sample_queue['Status'] == 'Awaiting Funds']['Amount ($M)'].sum()
total_outgoing = sample_queue['Amount ($M)'].sum()
with col1:
st.metric(label="Net Available Liquidity", value="$1.45B", delta="-$200M", delta_color="inverse")
with col2:
st.metric(label="Payments in Queue", value=f"{len(sample_queue)}", delta=f"Val: ${total_outgoing:.1f}M")
with col3:
st.metric(label="Blocked (Funds Await)", value=f"${blocked_funds:.1f}M", delta_color="inverse")
if blocked_funds > 500:
st.error("⚠️ High Bottleneck")
with col4:
st.metric(label="Utilization Rate", value="86%", delta="High Risk")
st.markdown("---")
# --- MAIN BODY: TABS ---
tab1, tab2, tab3, tab4 = st.tabs(["Payment Queues", "Liquidity Trajectory", "Collateral Mobility", "Alerts"])
# TAB 1: PAYMENT QUEUES
with tab1:
st.subheader("Real-time Payment Queues")
# Filters
f_col1, f_col2 = st.columns([1, 3])
channel_filter = f_col1.multiselect("Filter Channel", ['RTGS', 'SWIFT', 'SEPA', 'CLS'], default=['RTGS', 'SWIFT', 'SEPA', 'CLS'])
# Display Data
display_queue = sample_queue[sample_queue['Channel'].isin(channel_filter)]
# Color coding the dataframe
def highlight_status(row):
if row['Status'] == 'Awaiting Funds':
return ['background-color: #ffcccc'] * len(row)
elif row['Priority'] == 'High':
return ['background-color: #fff2cc'] * len(row)
return [''] * len(row)
st.dataframe(display_queue.style.apply(highlight_status, axis=1), use_container_width=True)
c1, c2 = st.columns(2)
with c1:
# Queue Distribution
fig_q = px.pie(display_queue, values='Amount ($M)', names='Channel', title='Queue Distribution by Value')
st.plotly_chart(fig_q, use_container_width=True)
with c2:
# Aging
fig_age = px.histogram(display_queue, x="Age (Min)", title="Queue Aging (Minutes)", nbins=10, color_discrete_sequence=['#3366cc'])
st.plotly_chart(fig_age, use_container_width=True)
# TAB 2: LIQUIDITY TRAJECTORY (EWS)
with tab2:
st.subheader("Projected Intraday Liquidity Position")
liq_df = generate_liquidity_curve()
fig_liq = go.Figure()
# Balance Line
fig_liq.add_trace(go.Scatter(
x=liq_df['Time'], y=liq_df['Balance ($M)'],
mode='lines+markers', name='Projected Balance',
line=dict(color='#00cc96', width=3)
))
# Threshold Line
fig_liq.add_trace(go.Scatter(
x=liq_df['Time'], y=liq_df['Threshold ($M)'],
mode='lines', name='Min Required Threshold',
line=dict(color='red', dash='dash')
))
# Shade danger zone
fig_liq.add_trace(go.Scatter(
x=liq_df['Time'], y=[0]*len(liq_df),
mode='none', fill='tozeroy', fillcolor='rgba(255, 0, 0, 0.1)'
))
fig_liq.update_layout(title='Intraday Liquidity Flow (D-Account)', xaxis_title='Time', yaxis_title='Amount ($M)')
st.plotly_chart(fig_liq, use_container_width=True)
st.warning("⚠️ **Early Warning:** Based on current outflows, projected balance hits safety threshold at 14:00. Recommend collateral optimization.")
# TAB 3: COLLATERAL MOBILITY
with tab3:
st.subheader("Collateral Inventory & Optimization")
coll_data = generate_collateral()
coll_df = pd.DataFrame(coll_data).T.reset_index()
coll_df.columns = ['Asset Class', 'Available', 'Pledged', 'Total']
# Visualization
c1, c2 = st.columns([2, 1])
with c1:
st.dataframe(coll_df, use_container_width=True, hide_index=True)
if st.button("🚀 Trigger Auto-Collateralization"):
with st.spinner("Moving assets from HQLA pool to Central Bank..."):
import time
time.sleep(2)
st.success("Success! $500M L1 Securities converted to Central Bank Reserves.")
with c2:
st.info("Collateral Efficiency Score: **72/100**\n\n- Too much idle cash.\n- High concentration in L1 Assets.")
# TAB 4: ALERTS & LOGS
with tab4:
st.subheader("System Event Feed")
logs = [
{"Time": "08:05:12", "Level": "INFO", "Message": "System Start: Liquidity Manager initialized."},
{"Time": "08:45:00", "Level": "INFO", "Message": "Settlement Window Opened."},
{"Time": "09:15:33", "Level": "WARNING", "Message": "RTGS Queue backlog exceeds 50 items."},
{"Time": "10:05:11", "Level": "CRITICAL", "Message": "Large Value Payment (TX882211) blocked due to insufficient funds."},
{"Time": "10:06:00", "Level": "INFO", "Message": "Automated sweep triggered from Nostro account."},
]
log_df = pd.DataFrame(logs)
def color_logs(row):
if row['Level'] == 'CRITICAL': return ['color: red; font-weight: bold'] * 3
if row['Level'] == 'WARNING': return ['color: orange'] * 3
return ['color: gray'] * 3
st.dataframe(log_df.style.apply(color_logs, axis=1), use_container_width=True, hide_index=True)