Let me create a comprehensive, visually impressive system.
Sovereign Local-Currency Bond Market Depth Analyzer
This is a comprehensive financial analysis tool that simulates and visualizes a sovereign local-currency bond market with investor base composition, liquidity tiers, and central bank policy interventions.
python
import pygame
import numpy as np
import math
from dataclasses import dataclass, field
from typing import Dict, List, Tuple, Optional
from enum import Enum
import random
from collections import deque
# Initialize Pygame
pygame.init()
# Screen settings
SCREEN_WIDTH = 1600
SCREEN_HEIGHT = 950
FPS = 60
# Colors - Professional dark theme
COLORS = {
'bg_dark': (12, 12, 18),
'bg_panel': (18, 20, 28),
'bg_light': (25, 28, 38),
'border': (40, 45, 60),
'text_primary': (230, 235, 245),
'text_secondary': (140, 150, 170),
'text_dim': (80, 90, 110),
'accent_blue': (70, 150, 255),
'accent_green': (80, 220, 140),
'accent_red': (255, 90, 95),
'accent_orange': (255, 165, 70),
'accent_purple': (160, 100, 255),
'accent_cyan': (70, 220, 230),
'accent_yellow': (255, 220, 80),
'grid': (30, 35, 48),
'highlight': (50, 55, 75),
}
class InvestorType(Enum):
CENTRAL_BANK = "Central Bank"
COMMERCIAL_BANKS = "Commercial Banks"
PENSION_FUNDS = "Pension Funds"
INSURANCE = "Insurance Co."
FOREIGN_INVESTORS = "Foreign Investors"
MUTUAL_FUNDS = "Mutual Funds"
RETAIL = "Retail"
HEDGE_FUNDS = "Hedge Funds"
class LiquidityTier(Enum):
TIER1_DEEP = ("Tier 1: Deep Liquid", (80, 220, 140))
TIER2_LIQUID = ("Tier 2: Liquid", (70, 180, 255))
TIER3_SEMI = ("Tier 3: Semi-Liquid", (255, 200, 70))
TIER4_ILLIQUID = ("Tier 4: Illiquid", (255, 100, 100))
class PolicyType(Enum):
QUANTITATIVE_EASING = "Quantitative Easing"
YIELD_CURVE_CONTROL = "Yield Curve Control"
STANDING_FACILITY = "Standing Facility"
REPO_OPERATIONS = "Repo Operations"
TWIST_OPERATION = "Operation Twist"
EMERGENCY_PURCHASE = "Emergency Purchase"
@dataclass
class BondIssue:
isin: str
coupon: float
maturity_years: int
outstanding: float # in billions
yield_to_maturity: float
bid_yield: float
ask_yield: float
duration: float
tier: LiquidityTier
holdings: Dict[InvestorType, float] = field(default_factory=dict)
turnover_30d: float = 0.0
def get_spread(self) -> float:
return (self.ask_yield - self.bid_yield) * 100 # in basis points
@dataclass
class PolicyIntervention:
policy_type: PolicyType
target_maturity: str
amount: float # in billions
intensity: float # 0-100
active: bool = False
duration_days: int = 30
effect_on_yields: float = 0.0
@dataclass
class MarketOrder:
side: str # 'bid' or 'ask'
investor: InvestorType
yield_level: float
amount: float
timestamp: float
filled: bool = False
class InvestorBehavior:
"""Models different investor behaviors and constraints"""
def __init__(self, investor_type: InvestorType):
self.type = investor_type
self.risk_appetite = self._get_risk_appetite()
self.holding_horizon = self._get_holding_horizon()
self.yield_sensitivity = self._get_yield_sensitivity()
self.max_concentration = self._get_max_concentration()
def _get_risk_appetite(self) -> float:
appetites = {
InvestorType.CENTRAL_BANK: 0.1,
InvestorType.PENSION_FUNDS: 0.3,
InvestorType.INSURANCE: 0.35,
InvestorType.COMMERCIAL_BANKS: 0.5,
InvestorType.MUTUAL_FUNDS: 0.6,
InvestorType.FOREIGN_INVESTORS: 0.65,
InvestorType.HEDGE_FUNDS: 0.9,
InvestorType.RETAIL: 0.4,
}
return appetites.get(self.type, 0.5)
def _get_holding_horizon(self) -> int:
horizons = {
InvestorType.CENTRAL_BANK: 3650, # 10 years
InvestorType.PENSION_FUNDS: 3650,
InvestorType.INSURANCE: 1825, # 5 years
InvestorType.COMMERCIAL_BANKS: 365,
InvestorType.MUTUAL_FUNDS: 180,
InvestorType.FOREIGN_INVESTORS: 90,
InvestorType.HEDGE_FUNDS: 30,
InvestorType.RETAIL: 730,
}
return horizons.get(self.type, 365)
def _get_yield_sensitivity(self) -> float:
sensitivities = {
InvestorType.CENTRAL_BANK: 0.1,
InvestorType.PENSION_FUNDS: 0.4,
InvestorType.INSURANCE: 0.5,
InvestorType.COMMERCIAL_BANKS: 0.7,
InvestorType.MUTUAL_FUNDS: 0.8,
InvestorType.FOREIGN_INVESTORS: 0.9,
InvestorType.HEDGE_FUNDS: 1.0,
InvestorType.RETAIL: 0.3,
}
return sensitivities.get(self.type, 0.5)
def _get_max_concentration(self) -> float:
concentrations = {
InvestorType.CENTRAL_BANK: 0.5,
InvestorType.PENSION_FUNDS: 0.25,
InvestorType.INSURANCE: 0.2,
InvestorType.COMMERCIAL_BANKS: 0.15,
InvestorType.MUTUAL_FUNDS: 0.1,
InvestorType.FOREIGN_INVESTORS: 0.3,
InvestorType.HEDGE_FUNDS: 0.05,
InvestorType.RETAIL: 0.02,
}
return concentrations.get(self.type, 0.1)
class YieldCurve:
"""Manages the sovereign yield curve"""
def __init__(self):
self.maturities = [0.25, 0.5, 1, 2, 3, 5, 7, 10, 20, 30]
self.base_rates = {}
self.current_rates = {}
self._initialize_curve()
def _initialize_curve(self):
"""Initialize a realistic yield curve"""
base_yields = {
0.25: 3.2, 0.5: 3.3, 1: 3.5, 2: 3.7, 3: 3.9,
5: 4.1, 7: 4.3, 10: 4.4, 20: 4.6, 30: 4.5
}
for mat, rate in base_yields.items():
self.base_rates[mat] = rate
self.current_rates[mat] = rate
def apply_shock(self, short_shock: float, long_shock: float):
"""Apply shocks to different parts of the curve"""
for mat in self.maturities:
weight = min(1, mat / 10)
shock = short_shock * (1 - weight) + long_shock * weight
self.current_rates[mat] = max(0.1, self.base_rates[mat] + shock)
def get_rate(self, maturity: float) -> float:
"""Interpolate rate for given maturity"""
if maturity in self.current_rates:
return self.current_rates[maturity]
sorted_mats = sorted(self.maturities)
for i, m in enumerate(sorted_mats):
if m > maturity:
if i == 0:
return self.current_rates[sorted_mats[0]]
lower = sorted_mats[i-1]
upper = m
weight = (maturity - lower) / (upper - lower)
return self.current_rates[lower] * (1-weight) + self.current_rates[upper] * weight
return self.current_rates[sorted_mats[-1]]
class OrderBook:
"""Simulated order book for market depth"""
def __init__(self):
self.bids: List[MarketOrder] = []
self.asks: List[MarketOrder] = []
self.trade_history: deque = deque(maxlen=100)
def generate_depth(self, mid_yield: float, liquidity: LiquidityTier):
"""Generate realistic order book depth"""
self.bids.clear()
self.asks.clear()
# Spread depends on liquidity tier
spread_multipliers = {
LiquidityTier.TIER1_DEEP: 0.5,
LiquidityTier.TIER2_LIQUID: 1.0,
LiquidityTier.TIER3_SEMI: 2.5,
LiquidityTier.TIER4_ILLIQUID: 5.0,
}
spread_mult = spread_multipliers[liquidity]
for i in range(8):
bid_yield = mid_yield - (i + 1) * 0.01 * spread_mult
ask_yield = mid_yield + (i + 1) * 0.01 * spread_mult
# Size decreases with distance from mid
base_size = random.uniform(50, 200) * (0.7 ** i)
investor = random.choice(list(InvestorType))
self.bids.append(MarketOrder(
side='bid',
investor=investor,
yield_level=bid_yield,
amount=base_size * random.uniform(0.8, 1.2),
timestamp=pygame.time.get_ticks()
))
self.asks.append(MarketOrder(
side='ask',
investor=random.choice(list(InvestorType)),
yield_level=ask_yield,
amount=base_size * random.uniform(0.8, 1.2),
timestamp=pygame.time.get_ticks()
))
# Sort bids descending, asks ascending
self.bids.sort(key=lambda x: x.yield_level, reverse=True)
self.asks.sort(key=lambda x: x.yield_level)
class BondMarket:
"""Main bond market simulation"""
def __init__(self):
self.yield_curve = YieldCurve()
self.bonds: List[BondIssue] = []
self.order_books: Dict[str, OrderBook] = {}
self.investors: Dict[InvestorType, InvestorBehavior] = {}
self.policy_interventions: List[PolicyIntervention] = []
self.market_stats = {
'total_outstanding': 0,
'avg_yield': 0,
'avg_spread': 0,
'turnover_ratio': 0,
'foreign_share': 0,
}
self._initialize_investors()
self._initialize_bonds()
self._initialize_policies()
self._update_stats()
def _initialize_investors(self):
for it in InvestorType:
self.investors[it] = InvestorBehavior(it)
def _initialize_bonds(self):
"""Create a realistic set of bond issues"""
maturities = [
(2, '2Y'), (3, '3Y'), (5, '5Y'), (7, '7Y'),
(10, '10Y'), (20, '20Y'), (30, '30Y')
]
base_outstanding = {
2: 120, 3: 95, 5: 180, 7: 150, 10: 250, 20: 100, 30: 80
}
for mat, label in maturities:
# Create multiple issues per maturity
for i in range(random.randint(2, 4)):
coupon = self.yield_curve.get_rate(mat) + random.uniform(-0.2, 0.3)
outstanding = base_outstanding[mat] * random.uniform(0.7, 1.3)
ytm = self.yield_curve.get_rate(mat) + random.uniform(-0.1, 0.1)
# Determine liquidity tier
if mat <= 5 and outstanding > 100:
tier = LiquidityTier.TIER1_DEEP
elif mat <= 10 and outstanding > 50:
tier = LiquidityTier.TIER2_LIQUID
elif mat <= 20:
tier = LiquidityTier.TIER3_SEMI
else:
tier = LiquidityTier.TIER4_ILLIQUID
bond = BondIssue(
isin=f"GOV{mat:02d}{i:02d}",
coupon=round(coupon, 3),
maturity_years=mat,
outstanding=round(outstanding, 1),
yield_to_maturity=round(ytm, 3),
bid_yield=round(ytm - 0.02, 3),
ask_yield=round(ytm + 0.02, 3),
duration=round(mat * 0.85, 2),
tier=tier,
turnover_30d=random.uniform(0.3, 2.5)
)
# Distribute holdings among investors
self._distribute_holdings(bond)
self.bonds.append(bond)
# Create order book
ob = OrderBook()
ob.generate_depth(ytm, tier)
self.order_books[bond.isin] = ob
def _distribute_holdings(self, bond: BondIssue):
"""Distribute bond holdings among investor types"""
weights = {
InvestorType.CENTRAL_BANK: 0.25,
InvestorType.COMMERCIAL_BANKS: 0.22,
InvestorType.PENSION_FUNDS: 0.18,
InvestorType.INSURANCE: 0.12,
InvestorType.FOREIGN_INVESTORS: 0.12,
InvestorType.MUTUAL_FUNDS: 0.06,
InvestorType.RETAIL: 0.03,
InvestorType.HEDGE_FUNDS: 0.02,
}
# Adjust weights based on maturity
if bond.maturity_years <= 3:
weights[InvestorType.COMMERCIAL_BANKS] += 0.1
weights[InvestorType.PENSION_FUNDS] -= 0.05
weights[InvestorType.INSURANCE] -= 0.05
elif bond.maturity_years >= 20:
weights[InvestorType.PENSION_FUNDS] += 0.1
weights[InvestorType.INSURANCE] += 0.05
weights[InvestorType.COMMERCIAL_BANKS] -= 0.1
weights[InvestorType.FOREIGN_INVESTORS] -= 0.05
# Normalize and distribute
total = sum(weights.values())
for inv, weight in weights.items():
bond.holdings[inv] = round((weight / total) * bond.outstanding, 2)
def _initialize_policies(self):
"""Initialize available policy interventions"""
self.policy_interventions = [
PolicyIntervention(
policy_type=PolicyType.QUANTITATIVE_EASING,
target_maturity="All",
amount=50,
intensity=50
),
PolicyIntervention(
policy_type=PolicyType.YIELD_CURVE_CONTROL,
target_maturity="10Y",
amount=0,
intensity=70
),
PolicyIntervention(
policy_type=PolicyType.STANDING_FACILITY,
target_maturity="Short",
amount=20,
intensity=30
),
PolicyIntervention(
policy_type=PolicyType.REPO_OPERATIONS,
target_maturity="All",
amount=30,
intensity=40
),
PolicyIntervention(
policy_type=PolicyType.TWIST_OPERATION,
target_maturity="Curve",
amount=25,
intensity=60
),
PolicyIntervention(
policy_type=PolicyType.EMERGENCY_PURCHASE,
target_maturity="All",
amount=100,
intensity=90
),
]
def apply_policy(self, policy: PolicyIntervention):
"""Apply a policy intervention to the market"""
if policy.policy_type == PolicyType.QUANTITATIVE_EASING:
# QE lowers all yields
for bond in self.bonds:
reduction = 0.15 * (policy.intensity / 100)
bond.yield_to_maturity = max(0.1, bond.yield_to_maturity - reduction)
bond.bid_yield = max(0.05, bond.bid_yield - reduction)
bond.ask_yield = max(0.08, bond.ask_yield - reduction)
elif policy.policy_type == PolicyType.YIELD_CURVE_CONTROL:
# YCC targets 10Y yield
target = 3.5
for bond in self.bonds:
if bond.maturity_years >= 7:
adjustment = (target - bond.yield_to_maturity) * (policy.intensity / 200)
bond.yield_to_maturity += adjustment
bond.bid_yield += adjustment
bond.ask_yield += adjustment
elif policy.policy_type == PolicyType.TWIST_OPERATION:
# Sell short, buy long - steepens curve
for bond in self.bonds:
if bond.maturity_years <= 3:
bond.yield_to_maturity += 0.1 * (policy.intensity / 100)
elif bond.maturity_years >= 10:
bond.yield_to_maturity -= 0.15 * (policy.intensity / 100)
elif policy.policy_type == PolicyType.EMERGENCY_PURCHASE:
# Large scale buying
for bond in self.bonds:
reduction = 0.3 * (policy.intensity / 100)
bond.yield_to_maturity = max(0.05, bond.yield_to_maturity - reduction)
# Tighten spreads
spread = bond.get_spread()
if spread > 3:
bond.bid_yield += reduction * 0.3
bond.ask_yield -= reduction * 0.3
# Update order books
for isin, ob in self.order_books.items():
bond = next((b for b in self.bonds if b.isin == isin), None)
if bond:
ob.generate_depth(bond.yield_to_maturity, bond.tier)
self._update_stats()
def simulate_trading(self):
"""Simulate trading activity"""
for bond in self.bonds:
# Random yield movements
movement = random.gauss(0, 0.005)
bond.yield_to_maturity = max(0.1, bond.yield_to_maturity + movement)
bond.bid_yield = max(0.05, bond.bid_yield + movement)
bond.ask_yield = max(0.08, bond.ask_yield + movement)
# Update turnover
bond.turnover_30d = max(0.1, bond.turnover_30d + random.gauss(0, 0.05))
# Update order book
if bond.isin in self.order_books:
self.order_books[bond.isin].generate_depth(
bond.yield_to_maturity, bond.tier
)
self._update_stats()
def _update_stats(self):
"""Update market statistics"""
if not self.bonds:
return
self.market_stats['total_outstanding'] = sum(b.outstanding for b in self.bonds)
self.market_stats['avg_yield'] = np.mean([b.yield_to_maturity for b in self.bonds])
self.market_stats['avg_spread'] = np.mean([b.get_spread() for b in self.bonds])
self.market_stats['turnover_ratio'] = np.mean([b.turnover_30d for b in self.bonds])
foreign_total = sum(
b.holdings.get(InvestorType.FOREIGN_INVESTORS, 0)
for b in self.bonds
)
self.market_stats['foreign_share'] = foreign_total / self.market_stats['total_outstanding']
class Button:
"""Interactive button component"""
def __init__(self, x: int, y: int, width: int, height: int,
text: str, color: Tuple[int, int, int]):
self.rect = pygame.Rect(x, y, width, height)
self.text = text
self.color = color
self.hover = False
self.active = False
def draw(self, surface: pygame.Surface, font: pygame.font.Font):
color = self.color
if self.hover:
color = tuple(min(255, c + 30) for c in self.color)
if self.active:
color = tuple(min(255, c + 60) for c in self.color)
pygame.draw.rect(surface, color, self.rect, border_radius=6)
pygame.draw.rect(surface, COLORS['border'], self.rect, 2, border_radius=6)
text_surf = font.render(self.text, True, COLORS['text_primary'])
text_rect = text_surf.get_rect(center=self.rect.center)
surface.blit(text_surf, text_rect)
def handle_event(self, event: pygame.event.Event) -> bool:
if event.type == pygame.MOUSEMOTION:
self.hover = self.rect.collidepoint(event.pos)
elif event.type == pygame.MOUSEBUTTONDOWN:
if self.rect.collidepoint(event.pos):
return True
return False
class MarketDepthAnalyzer:
"""Main visualization application"""
def __init__(self):
self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Sovereign Bond Market Depth Analyzer")
self.clock = pygame.time.Clock()
self.running = True
# Fonts
self.font_large = pygame.font.Font(None, 32)
self.font_medium = pygame.font.Font(None, 24)
self.font_small = pygame.font.Font(None, 20)
self.font_tiny = pygame.font.Font(None, 16)
# Market simulation
self.market = BondMarket()
# UI State
self.selected_bond_idx = 0
self.selected_policy_idx = -1
self.animation_time = 0
# Buttons
self.policy_buttons: List[Button] = []
self._create_policy_buttons()
# Trading animation
self.trade_particles: List[dict] = []
# Chart data history
self.yield_history: Dict[int, deque] = {
2: deque(maxlen=100),
5: deque(maxlen=100),
10: deque(maxlen=100),
30: deque(maxlen=100),
}
def _create_policy_buttons(self):
"""Create policy intervention buttons"""
start_x = 50
start_y = 680
btn_width = 140
btn_height = 40
spacing = 10
colors = [
COLORS['accent_green'],
COLORS['accent_blue'],
COLORS['accent_cyan'],
COLORS['accent_orange'],
COLORS['accent_purple'],
COLORS['accent_red'],
]
for i, policy in enumerate(self.market.policy_interventions):
row = i // 3
col = i % 3
x = start_x + col * (btn_width + spacing)
y = start_y + row * (btn_height + spacing)
self.policy_buttons.append(
Button(x, y, btn_width, btn_height,
policy.policy_type.value, colors[i])
)
def handle_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
self.running = False
elif event.key == pygame.K_UP:
self.selected_bond_idx = max(0, self.selected_bond_idx - 1)
elif event.key == pygame.K_DOWN:
self.selected_bond_idx = min(
len(self.market.bonds) - 1,
self.selected_bond_idx + 1
)
# Handle policy buttons
for i, btn in enumerate(self.policy_buttons):
if btn.handle_event(event):
policy = self.market.policy_interventions[i]
policy.active = not policy.active
btn.active = policy.active
if policy.active:
self.market.apply_policy(policy)
def update(self):
self.animation_time += 1
# Simulate market activity
if self.animation_time % 30 == 0:
self.market.simulate_trading()
# Update yield history
for bond in self.market.bonds:
if bond.maturity_years in self.yield_history:
self.yield_history[bond.maturity_years].append(
bond.yield_to_maturity
)
# Add trade particles
if random.random() < 0.3:
self._add_trade_particle()
# Update particles
for particle in self.trade_particles[:]:
particle['y'] -= particle['speed']
particle['alpha'] -= 3
if particle['alpha'] <= 0:
self.trade_particles.remove(particle)
def _add_trade_particle(self):
if not self.market.bonds:
return
bond = random.choice(self.market.bonds)
self.trade_particles.append({
'x': random.randint(400, 600),
'y': random.randint(400, 500),
'text': f"{'BUY' if random.random() > 0.5 else 'SELL'} {bond.isin}",
'color': COLORS['accent_green'] if random.random() > 0.5 else COLORS['accent_red'],
'alpha': 255,
'speed': random.uniform(1, 2)
})
def draw(self):
self.screen.fill(COLORS['bg_dark'])
# Draw panels
self._draw_header()
self._draw_yield_curve_panel()
self._draw_investor_composition_panel()
self._draw_liquidity_tiers_panel()
self._draw_order_book_panel()
self._draw_market_stats_panel()
self._draw_policy_panel()
self._draw_bond_list_panel()
# Draw trade particles
for particle in self.trade_particles:
if particle['alpha'] > 0:
font = pygame.font.Font(None, 18)
color = (*particle['color'][:3], max(0, int(particle['alpha'])))
text = font.render(particle['text'], True, particle['color'])
text.set_alpha(max(0, int(particle['alpha'])))
self.screen.blit(text, (particle['x'], particle['y']))
pygame.display.flip()
def _draw_header(self):
# Title bar
pygame.draw.rect(self.screen, COLORS['bg_panel'],
(0, 0, SCREEN_WIDTH, 50))
pygame.draw.line(self.screen, COLORS['border'],
(0, 50), (SCREEN_WIDTH, 50), 2)
title = self.font_large.render(
"Sovereign Local-Currency Bond Market Depth Analyzer",
True, COLORS['text_primary']
)
self.screen.blit(title, (20, 12))
# Status indicators
status_x = SCREEN_WIDTH - 250
indicators = [
("Market Status", COLORS['accent_green'], "OPEN"),
("Data Feed", COLORS['accent_green'], "LIVE"),
]
for i, (label, color, value) in enumerate(indicators):
x = status_x + i * 120
pygame.draw.circle(self.screen, color, (x, 25), 6)
text = self.font_small.render(f"{label}: {value}", True, COLORS['text_secondary'])
self.screen.blit(text, (x + 12, 18))
def _draw_panel(self, x: int, y: int, width: int, height: int,
title: str) -> pygame.Rect:
"""Draw a panel with title"""
rect = pygame.Rect(x, y, width, height)
pygame.draw.rect(self.screen, COLORS['bg_panel'], rect, border_radius=8)
pygame.draw.rect(self.screen, COLORS['border'], rect, 2, border_radius=8)
# Title bar
title_rect = pygame.Rect(x, y, width, 30)
pygame.draw.rect(self.screen, COLORS['bg_light'], title_rect,
border_top_left_radius=8, border_top_right_radius=8)
title_text = self.font_medium.render(title, True, COLORS['text_primary'])
self.screen.blit(title_text, (x + 10, y + 6))
return pygame.Rect(x, y + 30, width, height - 30)
def _draw_yield_curve_panel(self):
content = self._draw_panel(20, 60, 450, 280, "Yield Curve")
# Draw grid
margin_left = 60
margin_bottom = 40
chart_width = content.width - margin_left - 20
chart_height = content.height - margin_bottom - 20
chart_x = content.x + margin_left
chart_y = content.y + 10
# Grid lines
for i in range(6):
y = chart_y + chart_height * i / 5
pygame.draw.line(self.screen, COLORS['grid'],
(chart_x, y), (chart_x + chart_width, y), 1)
# Y-axis labels
yield_val = 5.5 - i * 0.5
label = self.font_tiny.render(f"{yield_val:.1f}%", True, COLORS['text_dim'])
self.screen.blit(label, (content.x + 5, y - 8))
# X-axis labels
maturities = ['3M', '6M', '1Y', '2Y', '3Y', '5Y', '7Y', '10Y', '20Y', '30Y']
for i, mat in enumerate(maturities):
x = chart_x + chart_width * i / (len(maturities) - 1)
pygame.draw.line(self.screen, COLORS['grid'],
(x, chart_y), (x, chart_y + chart_height), 1)
label = self.font_tiny.render(mat, True, COLORS['text_dim'])
self.screen.blit(label, (x - 10, chart_y + chart_height + 5))
# Draw yield curve
curve_points = []
for i, mat_label in enumerate([0.25, 0.5, 1, 2, 3, 5, 7, 10, 20, 30]):
x = chart_x + chart_width * i / 9
rate = self.market.yield_curve.get_rate(mat_label)
y = chart_y + chart_height * (5.5 - rate) / 2.5
y = max(chart_y, min(chart_y + chart_height, y))
curve_points.append((x, y))
# Draw curve with glow effect
if len(curve_points) > 1:
# Glow
for offset in range(3, 0, -1):
alpha = 50 + (3 - offset) * 30
color = (*COLORS['accent_cyan'][:3],)
points = [(p[0], p[1]) for p in curve_points]
pygame.draw.lines(self.screen, color, False, points, offset * 2)
# Main line
pygame.draw.lines(self.screen, COLORS['accent_cyan'], False, curve_points, 3)
# Points
for px, py in curve_points:
pygame.draw.circle(self.screen, COLORS['accent_cyan'], (int(px), int(py)), 5)
pygame.draw.circle(self.screen, COLORS['text_primary'], (int(px), int(py)), 3)
def _draw_investor_composition_panel(self):
content = self._draw_panel(20, 350, 450, 300, "Investor Base Composition")
# Calculate totals per investor type
investor_totals = {}
for inv_type in InvestorType:
total = sum(b.holdings.get(inv_type, 0) for b in self.market.bonds)
investor_totals[inv_type] = total
total_outstanding = sum(investor_totals.values())
# Draw horizontal bar chart
bar_height = 25
bar_spacing = 8
start_y = content.y + 20
max_width = content.width - 160
colors = [
COLORS['accent_orange'], COLORS['accent_blue'], COLORS['accent_green'],
COLORS['accent_purple'], COLORS['accent_cyan'], COLORS['accent_yellow'],
COLORS['accent_red'], (180, 180, 200)
]
for i, (inv_type, amount) in enumerate(investor_totals.items()):
y = start_y + i * (bar_height + bar_spacing)
# Label
label = self.font_small.render(inv_type.value, True, COLORS['text_secondary'])
self.screen.blit(label, (content.x + 10, y + 3))
# Bar
bar_x = content.x + 130
bar_width = (amount / total_outstanding) * max_width if total_outstanding > 0 else 0
pygame.draw.rect(self.screen, COLORS['bg_light'],
(bar_x, y, max_width, bar_height), border_radius=4)
pygame.draw.rect(self.screen, colors[i],
(bar_x, y, bar_width, bar_height), border_radius=4)
# Percentage
pct = (amount / total_outstanding * 100) if total_outstanding > 0 else 0
pct_text = self.font_small.render(f"{pct:.1f}%", True, COLORS['text_primary'])
self.screen.blit(pct_text, (bar_x + max_width + 10, y + 3))
def _draw_liquidity_tiers_panel(self):
content = self._draw_panel(480, 60, 340, 280, "Liquidity Tiers Analysis")
# Group bonds by tier
tier_stats = {}
for tier in LiquidityTier:
bonds_in_tier = [b for b in self.market.bonds if b.tier == tier]
if bonds_in_tier:
tier_stats[tier] = {
'count': len(bonds_in_tier),
'total': sum(b.outstanding for b in bonds_in_tier),
'avg_spread': np.mean([b.get_spread() for b in bonds_in_tier]),
'avg_turnover': np.mean([b.turnover_30d for b in bonds_in_tier]),
}
else:
tier_stats[tier] = {
'count': 0, 'total': 0, 'avg_spread': 0, 'avg_turnover': 0
}
# Draw tier cards
card_height = 55
card_spacing = 5
start_y = content.y + 10
for i, (tier, stats) in enumerate(tier_stats.items()):
y = start_y + i * (card_height + card_spacing)
# Card background
card_rect = pygame.Rect(content.x + 10, y, content.width - 20, card_height)
pygame.draw.rect(self.screen, COLORS['bg_light'], card_rect, border_radius=6)
# Tier indicator
pygame.draw.rect(self.screen, tier.value[1],
(content.x + 10, y, 5, card_height),
border_top_left_radius=6, border_bottom_left_radius=6)
# Tier name
name_text = self.font_small.render(tier.value[0], True, tier.value[1])
self.screen.blit(name_text, (content.x + 25, y + 5))
# Stats
stats_text = self.font_tiny.render(
f"Bonds: {stats['count']} | Outstanding: ${stats['total']:.0f}B | "
f"Spread: {stats['avg_spread']:.1f}bp | Turnover: {stats['avg_turnover']:.2f}x",
True, COLORS['text_secondary']
)
self.screen.blit(stats_text, (content.x + 25, y + 28))
def _draw_order_book_panel(self):
content = self._draw_panel(480, 350, 340, 300, "Market Depth (Order Book)")
if not self.market.bonds:
return
selected_bond = self.market.bonds[self.selected_bond_idx]
order_book = self.market.order_books.get(selected_bond.isin, OrderBook())
# Bond info header
header_text = self.font_medium.render(
f"{selected_bond.isin} | {selected_bond.maturity_years}Y | "
f"Coupon: {selected_bond.coupon:.2f}%",
True, COLORS['text_primary']
)
self.screen.blit(header_text, (content.x + 10, content.y + 5))
# Column headers
col_y = content.y + 35
headers = ["BID ($M)", "BID YLD", "SPREAD", "ASK YLD", "ASK ($M)"]
col_x_positions = [content.x + 10, content.x + 70, content.x + 135,
content.x + 195, content.x + 260]
for i, header in enumerate(headers):
text = self.font_tiny.render(header, True, COLORS['text_dim'])
self.screen.blit(text, (col_x_positions[i], col_y))
# Order book entries
row_height = 22
start_y = content.y + 55
for i in range(min(8, len(order_book.bids), len(order_book.asks))):
y = start_y + i * row_height
bid = order_book.bids[i]
ask = order_book.asks[i]
# Alternating row background
if i % 2 == 0:
pygame.draw.rect(self.screen, COLORS['bg_light'],
(content.x + 5, y - 2, content.width - 10, row_height - 2),
border_radius=3)
# Bid side (green)
bid_amount_text = self.font_small.render(
f"{bid.amount:.1f}", True, COLORS['accent_green']
)
self.screen.blit(bid_amount_text, (col_x_positions[0], y))
bid_yield_text = self.font_small.render(
f"{bid.yield_level:.3f}", True, COLORS['accent_green']
)
self.screen.blit(bid_yield_text, (col_x_positions[1], y))
# Spread (center)
spread = (ask.yield_level - bid.yield_level) * 100
spread_color = COLORS['accent_yellow'] if spread < 3 else COLORS['accent_orange']
spread_text = self.font_small.render(f"{spread:.1f}bp", True, spread_color)
spread_rect = spread_text.get_rect(center=(content.x + content.width // 2, y + 8))
self.screen.blit(spread_text, spread_rect)
# Ask side (red)
ask_yield_text = self.font_small.render(
f"{ask.yield_level:.3f}", True, COLORS['accent_red']
)
self.screen.blit(ask_yield_text, (col_x_positions[3], y))
ask_amount_text = self.font_small.render(
f"{ask.amount:.1f}", True, COLORS['accent_red']
)
self.screen.blit(ask_amount_text, (col_x_positions[4], y))
# Depth visualization bar
bar_y = start_y + 9 * row_height + 10
total_bid = sum(b.amount for b in order_book.bids)
total_ask = sum(a.amount for a in order_book.asks)
total = total_bid + total_ask
if total > 0:
mid_x = content.x + content.width // 2
# Bid bar (left)
bid_width = (total_bid / total) * (content.width // 2 - 20)
pygame.draw.rect(self.screen, COLORS['accent_green'],
(mid_x - bid_width, bar_y, bid_width, 15),
border_radius=4)
# Ask bar (right)
ask_width = (total_ask / total) * (content.width // 2 - 20)
pygame.draw.rect(self.screen, COLORS['accent_red'],
(mid_x, bar_y, ask_width, 15),
border_radius=4)
depth_text = self.font_tiny.render(
f"Total Depth: ${total:.0f}M | Bid/Ask Ratio: {total_bid/total_ask:.2f}",
True, COLORS['text_secondary']
)
self.screen.blit(depth_text, (content.x + 10, bar_y + 20))
def _draw_market_stats_panel(self):
content = self._draw_panel(830, 60, 350, 280, "Market Statistics")
stats = self.market.market_stats
# Create stat cards
stat_items = [
("Total Outstanding", f"${stats['total_outstanding']:.1f}B", COLORS['accent_blue']),
("Average Yield", f"{stats['avg_yield']:.2f}%", COLORS['accent_cyan']),
("Average Spread", f"{stats['avg_spread']:.1f}bp", COLORS['accent_orange']),
("Turnover Ratio", f"{stats['turnover_ratio']:.2f}x", COLORS['accent_green']),
("Foreign Share", f"{stats['foreign_share']*100:.1f}%", COLORS['accent_purple']),
]
card_width = (content.width - 30) // 2
card_height = 55
for i, (label, value, color) in enumerate(stat_items):
row = i // 2
col = i % 2
x = content.x + 10 + col * (card_width + 10)
y = content.y + 10 + row * (card_height + 10)
# Card
card_rect = pygame.Rect(x, y, card_width, card_height)
pygame.draw.rect(self.screen, COLORS['bg_light'], card_rect, border_radius=6)
# Color indicator
pygame.draw.rect(self.screen, color, (x, y, 4, card_height),
border_top_left_radius=6, border_bottom_left_radius=6)
# Label
label_text = self.font_tiny.render(label, True, COLORS['text_secondary'])
self.screen.blit(label_text, (x + 12, y + 8))
# Value
value_text = self.font_medium.render(value, True, color)
self.screen.blit(value_text, (x + 12, y + 28))
# Mini yield trend chart
trend_y = content.y + 190
trend_height = 60
trend_width = content.width - 20
pygame.draw.rect(self.screen, COLORS['bg_light'],
(content.x + 10, trend_y, trend_width, trend_height),
border_radius=6)
trend_title = self.font_tiny.render("10Y Yield Trend", True, COLORS['text_dim'])
self.screen.blit(trend_title, (content.x + 15, trend_y + 3))
if len(self.yield_history[10]) > 1:
points = []
history = list(self.yield_history[10])
min_y, max_y = min(history), max(history)
range_y = max(0.01, max_y - min_y)
for i, val in enumerate(history):
px = content.x + 15 + i * (trend_width - 10) / len(history)
py = trend_y + trend_height - 10 - (val - min_y) / range_y * (trend_height - 25)
points.append((px, py))
if len(points) > 1:
pygame.draw.lines(self.screen, COLORS['accent_cyan'], False, points, 2)
def _draw_policy_panel(self):
content = self._draw_panel(830, 350, 350, 300, "Policy Interventions")
# Instructions
inst_text = self.font_tiny.render(
"Click policy to activate/deactivate", True, COLORS['text_dim']
)
self.screen.blit(inst_text, (content.x + 10, content.y + 5))
# Draw policy buttons
for i, btn in enumerate(self.policy_buttons):
btn.y = content.y + 30 + (i // 3) * 50
btn.draw(self.screen, self.font_small)
# Show active status
if self.market.policy_interventions[i].active:
active_text = self.font_tiny.render("ACTIVE", True, COLORS['accent_green'])
self.screen.blit(active_text, (btn.rect.x + btn.rect.width - 45, btn.rect.y - 12))
# Policy effect summary
active_policies = [p for p in self.market.policy_interventions if p.active]
if active_policies:
effect_y = content.y + 140
effect_text = self.font_small.render(
f"Active Policies: {len(active_policies)}",
True, COLORS['accent_yellow']
)
self.screen.blit(effect_text, (content.x + 10, effect_y))
total_effect = sum(p.effect_on_yields for p in active_policies)
direction = "Easing" if total_effect <= 0 else "Tightening"
direction_color = COLORS['accent_green'] if total_effect <= 0 else COLORS['accent_red']
direction_text = self.font_small.render(
f"Net Effect: {direction}", True, direction_color
)
self.screen.blit(direction_text, (content.x + 10, effect_y + 25))
def _draw_bond_list_panel(self):
content = self._draw_panel(1190, 60, 390, 590, "Bond Universe")
# Column headers
headers = ["ISIN", "Mat.", "YTM%", "Spr.", "Tier"]
col_widths = [70, 40, 50, 45, 60]
col_x = content.x + 10
header_y = content.y + 5
for i, header in enumerate(headers):
text = self.font_tiny.render(header, True, COLORS['text_dim'])
self.screen.blit(text, (col_x, header_y))
col_x += col_widths[i]
# Bond list
row_height = 24
start_y = content.y + 25
for i, bond in enumerate(self.market.bonds):
y = start_y + i * row_height
# Highlight selected
if i == self.selected_bond_idx:
pygame.draw.rect(self.screen, COLORS['highlight'],
(content.x + 5, y - 2, content.width - 10, row_height),
border_radius=4)
# Alternating background
elif i % 2 == 0:
pygame.draw.rect(self.screen, COLORS['bg_light'],
(content.x + 5, y - 2, content.width - 10, row_height),
border_radius=4)
# Bond data
col_x = content.x + 10
# ISIN
isin_text = self.font_tiny.render(bond.isin, True, COLORS['text_primary'])
self.screen.blit(isin_text, (col_x, y))
col_x += col_widths[0]
# Maturity
mat_text = self.font_tiny.render(f"{bond.maturity_years}Y", True, COLORS['text_secondary'])
self.screen.blit(mat_text, (col_x, y))
col_x += col_widths[1]
# YTM
ytm_color = COLORS['accent_green'] if bond.yield_to_maturity < 4 else COLORS['accent_orange']
ytm_text = self.font_tiny.render(f"{bond.yield_to_maturity:.2f}", True, ytm_color)
self.screen.blit(ytm_text, (col_x, y))
col_x += col_widths[2]
# Spread
spread = bond.get_spread()
spread_color = COLORS['accent_green'] if spread < 3 else (
COLORS['accent_yellow'] if spread < 5 else COLORS['accent_red']
)
spread_text = self.font_tiny.render(f"{spread:.0f}", True, spread_color)
self.screen.blit(spread_text, (col_x, y))
col_x += col_widths[3]
# Tier indicator
tier_short = bond.tier.value[0].split(':')[0]
tier_text = self.font_tiny.render(tier_short, True, bond.tier.value[1])
self.screen.blit(tier_text, (col_x, y))
# Scroll hint
hint_y = content.y + content.height - 20
hint_text = self.font_tiny.render(
"↑↓ Navigate bonds | ESC Exit",
True, COLORS['text_dim']
)
self.screen.blit(hint_text, (content.x + 10, hint_y))
def run(self):
"""Main application loop"""
while self.running:
self.handle_events()
self.update()
self.draw()
self.clock.tick(FPS)
pygame.quit()
def main():
"""Entry point"""
analyzer = MarketDepthAnalyzer()
analyzer.run()
if __name__ == "__main__":
main()
Features
1. Yield Curve Visualization
Real-time sovereign yield curve display
Animated curve with grid overlay
Support for curve shocks and policy effects
2. Investor Base Composition
8 investor types: Central Bank, Commercial Banks, Pension Funds, Insurance, Foreign Investors, Mutual Funds, Retail, Hedge Funds
Visual breakdown of holdings
Each investor has unique risk appetite and behavior
3. Liquidity Tiers
Tier 1 (Deep Liquid): High volume, tight spreads (<2bp)
Tier 2 (Liquid): Good volume, moderate spreads (2-5bp)