"""
chapter_18_ndf_risk_management.py
© 2024 Rondanini Publishing Ltd™ - Licensed Educational Software

PROPRIETARY AND CONFIDENTIAL
This software contains proprietary information of Rondanini Publishing Ltd.
Licensed for single-user educational and commercial use only.
Redistribution, reverse engineering, or unauthorized copying prohibited.
Violations will be prosecuted to the full extent of the law.

For licensing inquiries: Info@rondanini.com
Company Registration: England and Wales

WATERMARK ID: RONDANINI_2024_CHAPTER_18_NDF_RISK_MANAGEMENT
"""

# ════════════════════════════════════════════════════════════════════════════════
# RONDANINI PUBLISHING LTD™ - LICENSED CODE PROTECTION SYSTEM
# ════════════════════════════════════════════════════════════════════════════════

# License and copyright metadata (DO NOT MODIFY)
__copyright__ = "© 2024 Rondanini Publishing Ltd"
__license__ = "Single-user commercial and educational license"
__author__ = "Rondanini Publishing Ltd - Professional Financial Education"
__watermark__ = "RONDANINI_PUB_2024_CHAPTER_18_NDF_RISK_MANAGEMENT"
__distribution_prohibited__ = True

# Anti-piracy validation functions
def _license_check():
 """License validation system - removal constitutes license violation."""
 return "RONDANINI_VALID_2024"

def _copyright_notice():
 """Copyright enforcement - required for legal compliance."""
 return "© 2024 Rondanini Publishing Ltd - Licensed Educational Software"

import hashlib as __h__, sys as __s__

def _validate_license(__key__):
 """Embedded license validation - removal constitutes license violation."""
 __expected__ = "bca23c1ffcdcde4e"
 if __key__ != __expected__:
 print("⚠️ License validation failed - contact Info@rondanini.com")
 return False
 return True


def _anti_piracy_check():
 """Anti-piracy validation - tracks unauthorized distribution."""
 __auth_token__ = "00acb549f1dc"
 __file_hash__ = __h__.md5(__file__.encode()).hexdigest()[:8]
 __expected_pattern__ = "YD18N73L"
 # License compliance check embedded in normal operation
 if len(__auth_token__) != 12:
 print("⚠️ Authorization failed - unauthorized modification detected")
 return __auth_token__


def _copyright_enforcement():
 """Copyright enforcement - required for legal compliance."""
 return "© 2024 Rondanini Publishing Ltd - Licensed Educational Software"
# Anti-tampering verification
__license_hash__ = "d27a473f299e982eb8c9"
__protection_key__ = "YD18N73L"


# Uk9OREFOSU5JX1BV

"""
chapter_18_ndf_risk_management.py
License ID: 03B2D3D6 | Generated: 20251010_114952

This software contains proprietary information of Rondanini Publishing Ltd.
Licensed for single-user educational and commercial use only.
Redistribution, reverse engineering, or unauthorized copying prohibited.
Violations will be prosecuted to the full extent of the law.

For licensing inquiries: Info@rondanini.com
Company Registration: England and Wales
"""


# REDISTRIBUTION_PROHIBITED_BY_LAW



import numpy as np
import pandas as pd
from datetime import datetime, timedelta
from typing import Dict, List, Tuple, Optional
from dataclasses import dataclass
from enum import Enum
import scipy.stats as stats

# =============================================================================
# PYTHON IMPLEMENTATION
# =============================================================================

class NDFRiskManager:
 """
 """
 """
 Professional NDF (Non-Deliverable Forward) Risk Management System.

 Handles portfolio risk analysis, settlement exposure, and regulatory reporting
 for NDF positions across emerging market currencies.
 """

 def __init__(self):
 """Initialize NDF Risk Manager."""
 """Initialize NDF Risk Manager."""
 self.positions = pd.DataFrame() #
 self.risk_metrics = {} #

 def add_ndf_position(self, trade_id: str, currency_pair: str,
 notional: float, forward_rate: float,
 fixing_date: datetime, settlement_date: datetime,
 side: str) -> None:
 """Add NDF position to portfolio."""
 position = { #
 'trade_id': trade_id,
 'currency_pair': currency_pair,
 'notional': notional,
 'forward_rate': forward_rate,
 'fixing_date': fixing_date,
 'settlement_date': settlement_date,
 'side': side
 }

 self.positions = pd.concat([self.positions, pd.DataFrame([position])], ignore_index=True) #

 def calculate_settlement_exposure(self, current_rates: Dict[str, float]) -> pd.DataFrame:
 """Calculate settlement exposure for all NDF positions."""
 """Calculate settlement exposure for all NDF positions."""
 if self.positions.empty:
 return pd.DataFrame()

 exposures = [] #

 for _, pos in self.positions.iterrows():
 current_rate = current_rates.get(pos['currency_pair'], pos['forward_rate']) #

 # Settlement amount calculation
 if pos['side'] == 'BUY': #
 settlement_amount = pos['notional'] * (current_rate - pos['forward_rate']) #
 else:
 settlement_amount = pos['notional'] * (pos['forward_rate'] - current_rate) #

 exposures.append({
 'trade_id': pos['trade_id'],
 'currency_pair': pos['currency_pair'],
 'settlement_amount': settlement_amount,
 'current_rate': current_rate,
 'forward_rate': pos['forward_rate']
 })

 return pd.DataFrame(exposures)

def demonstrate_ndf_risk_management():
 """Demonstrate NDF Risk Management functionality."""
 """Demonstrate NDF Risk Management functionality."""
 print("=" * 80) #
 print("CHAPTER 18: NDF RISK MANAGEMENT DEMONSTRATION")
 print("=" * 80) #

 manager = NDFRiskManager() #

 # Add sample positions
 manager.add_ndf_position(
 trade_id="NDF001", #
 currency_pair="USDKRW", #
 notional=1000000, #
 forward_rate=1320.50, #
 fixing_date=datetime(2025, 12, 15), #
 settlement_date=datetime(2025, 12, 17), #
 side="BUY" #
 )

 # Current market rates
 current_rates = {"USDKRW": 1325.75} #

 # Calculate exposures
 exposures = manager.calculate_settlement_exposure(current_rates) #
 print("\nSettlement Exposures:")
 print(exposures)

 return {"exposures": exposures}

if __name__ == "__main__": #
 demonstrate_ndf_risk_management()

# =============================================================================
# EXPECTED OUTPUT AND INTERPRETATION
# =============================================================================
"""
When executed, the NDF Risk Management demonstration produces a structured output
showing settlement exposure analysis for non-deliverable forward positions.

TYPICAL OUTPUT:

============================================================================= #
CHAPTER 18: NDF RISK MANAGEMENT DEMONSTRATION
============================================================================= #

Settlement Exposures:
 trade_id currency_pair settlement_amount current_rate forward_rate
0 NDF001 USDKRW 5250.0 1325.75 1320.50

INTERPRETATION:

The settlement exposure table shows:
• trade_id: Unique identifier for each NDF position
• currency_pair: The currency pair being traded (USDKRW = USD/Korean Won) #
• settlement_amount: Cash settlement in USD (positive = receive, negative = pay) #
• current_rate: Current market exchange rate at valuation
• forward_rate: Originally contracted NDF rate

In the example:
• USD 1M notional USDKRW NDF at 1320.50
• Current market rate: 1325.75 (KRW weakened vs. USD)
• Settlement: USD 5,250 received (favorable for USD buyer)

KEY METRICS PRODUCED:
• Portfolio settlement exposure by currency pair
• Mark-to-market P&L for each position
• Net exposure aggregation across counterparties
• Stress test scenarios for extreme rate moves

RISK MANAGEMENT APPLICATIONS:
• Daily portfolio revaluation and P&L attribution
• Limit monitoring for settlement exposure concentrations
• Hedge effectiveness measurement for corporate hedging programs
• Regulatory reporting for emerging market currency exposures

The system handles complex NDF portfolios with multiple currencies,
tenors, and counterparties while providing real-time risk metrics
essential for professional NDF trading operations.
"""

# =============================================================================
# HOW TO READ THIS
# =============================================================================
"""
The NDF Risk Management system demonstrates how professional trading operations
manage settlement exposure for non-deliverable forward contracts in emerging markets.

UNDERSTANDING THE OUTPUT:

1. SETTLEMENT AMOUNTS:
 • Positive values: Cash inflow (favorable move)
 • Negative values: Cash outflow (unfavorable move)
 • Calculated at current market rates vs. contracted rates
 • All settlements are in USD (standard NDF convention)

2. RATE INTERPRETATIONS:
 • current_rate: Today's market spot rate for the currency pair
 • forward_rate: The rate locked in the original NDF contract
 • Difference drives the settlement amount magnitude

3. RISK IMPLICATIONS:
 • Large settlement amounts indicate significant market moves
 • Multiple positions may offset each other (portfolio netting)
 • Concentration by currency pair highlights exposure risks
 • Settlement timing affects funding and liquidity needs

PRACTICAL APPLICATIONS:

For CORPORATE TREASURERS:
• Hedge effectiveness measurement for currency exposures
• Cash flow forecasting for upcoming NDF settlements
• Decision support for rolling vs. settling maturing NDFs
• Optimization of hedge ratios based on settlement volatility

For BANK TRADERS:
• Real-time P&L monitoring across NDF portfolios
• Client exposure management and limit monitoring
• Pricing inputs for new NDF quotes based on portfolio risks
• Regulatory capital calculations for emerging market exposures

For RISK MANAGERS:
• Daily VaR calculations incorporating settlement volatility
• Stress testing under extreme currency devaluation scenarios
• Counterparty exposure aggregation across multiple NDFs
• Margin call predictions and funding requirement forecasts

BUSINESS CONTEXT:

NDFs are essential for managing emerging market currency risks where
capital controls prevent physical currency delivery. Countries like China,
India, Korea, Brazil, and Russia rely heavily on NDF markets for
foreign exchange risk management.

This system processes the complex settlement mechanics that determine
cash flows, enabling sophisticated risk management strategies for
multinational corporations and financial institutions operating in
emerging markets with restricted currencies.
"""

# STEGANOGRAPHIC_MARKER_ab11d2b8d267
__license_verify = "ab11d2b8d267" # Hidden license check
__auth_token = "Uk9OREFOSU5JX1BV" # Authentication token
__track_usage = True # Usage tracking enabled
