"""
chapter_16_ndf_markets.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_16_NDF_MARKETS
"""

# ════════════════════════════════════════════════════════════════════════════════
# 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_16_NDF_MARKETS"
__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_16_ndf_markets.py
License ID: 7BA2214A | 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


class FixingSource(Enum):
 """Standard NDF fixing sources"""
 """Standard NDF fixing sources"""
 """Standard NDF fixing sources"""
 CFETS = "CFETS" # China Foreign Exchange Trade System (CNY) #
 RBI = "RBI" # Reserve Bank of India (INR) #
 BOK = "BOK" # Bank of Korea (KRW) #
 TAIFX = "TAIFX" # Taipei Forex Inc. (TWD) #
 PTAX = "PTAX" # Banco Central do Brasil (BRL) #
 ABS = "ABS" # Association of Banks Singapore (offshore rates) #


@dataclass
class NDFContract:
 """Represents a Non-Deliverable Forward contract"""
 """Represents a Non-Deliverable Forward contract"""
 """Represents a Non-Deliverable Forward contract"""
 currency_pair: str
 notional_usd: float # USD notional (standard convention)
 ndf_rate: float # Contracted NDF rate
 fixing_date: datetime
 settlement_date: datetime
 fixing_source: str
 contract_date: datetime


class NDFPricer:
 """
 """
 """
 NDF pricing and settlement calculator for emerging market currencies.

 NDFs settle in cash (USD) based on the difference between contracted rate
 and fixing rate, avoiding physical delivery of restricted currencies.
 """

 def __init__(self):
 """Initialize NDF pricer with market data"""
 """Initialize NDF pricer with market data"""
 # Sample spot rates (as of contract date)
 self.spot_rates = { #
 'USD/CNY': 7.2500,
 'USD/INR': 83.2000,
 'USD/KRW': 1320.00,
 'USD/TWD': 31.500,
 'USD/BRL': 4.9500
 }

 # Sample interest rates (annualized, for pricing forwards)
 self.usd_rates = { #
 30: 0.0525,
 90: 0.0520,
 180: 0.0510,
 360: 0.0495
 }

 # Local rates (generally higher in EM)
 self.local_rates = { #
 'CNY': {30: 0.0250, 90: 0.0245, 180: 0.0240, 360: 0.0235},
 'INR': {30: 0.0680, 90: 0.0675, 180: 0.0670, 360: 0.0660},
 'KRW': {30: 0.0360, 90: 0.0355, 180: 0.0350, 360: 0.0345},
 'TWD': {30: 0.0175, 90: 0.0170, 180: 0.0165, 360: 0.0160},
 'BRL': {30: 0.1150, 90: 0.1140, 180: 0.1130, 360: 0.1100}
 }

 # NDF-deliverable basis spreads (annualized, in basis points)
 # Positive = NDF trades richer (higher rate) than deliverable
 self.ndf_basis = { #
 'USD/CNY': {30: 15, 90: 20, 180: 25, 360: 30},
 'USD/INR': {30: 25, 90: 30, 180: 35, 360: 40},
 'USD/KRW': {30: 10, 90: 12, 180: 15, 360: 18},
 'USD/TWD': {30: 8, 90: 10, 180: 12, 360: 15},
 'USD/BRL': {30: 40, 90: 45, 180: 50, 360: 60}
 }

 def calculate_ndf_rate(self, currency_pair: str, days: int) -> Dict:
 """
 """
 Calculate theoretical NDF rate using interest rate parity plus basis.


 The basis adjustment reflects NDF-specific factors:
 - Onshore/offshore liquidity differentials
 - Capital control costs
 - Credit risk differences
 """
 if currency_pair not in self.spot_rates:
 raise ValueError(f"Unknown currency pair: {currency_pair}")

 spot = self.spot_rates[currency_pair] #
 currency = currency_pair.split('/')[1] #

 # Find closest tenor for rate lookup
 tenor = min(self.usd_rates.keys(), key=lambda x: abs(x - days)) #

 r_usd = self.usd_rates[tenor] #
 r_local = self.local_rates[currency][tenor] #
 basis_bps = self.ndf_basis[currency_pair][tenor] #

 # Interest rate parity forward
 irp_forward = spot * (1 + r_usd * days/360) / (1 + r_local * days/360) #

 # Add basis adjustment (convert bps to rate adjustment)
 basis_adjustment = spot * (basis_bps / 10000) * (days / 360) #
 ndf_rate = irp_forward + basis_adjustment #

 # Calculate forward points in pips
 forward_points = (ndf_rate - spot) * 10000 #

 return {
 'spot_rate': spot,
 'ndf_rate': ndf_rate,
 'forward_points': forward_points,
 'usd_rate': r_usd,
 'local_rate': r_local,
 'basis_bps': basis_bps,
 'days': days
 }

 def calculate_settlement_amount(
 self,
 contract: NDFContract,
 fixing_rate: float
 ) -> Dict:
 """
 Calculate NDF cash settlement in USD.

 Settlement formulas (for USD/XXX quote convention):
 - Result > 0: Buyer receives USD (currency depreciated)
 - Result < 0: Buyer pays USD (currency appreciated)
 """
 # Calculate settlement amount
 rate_diff = fixing_rate - contract.ndf_rate #
 settlement_usd = contract.notional_usd * rate_diff / fixing_rate #

 # Determine who receives payment
 buyer_receives = settlement_usd > 0 #

 # Calculate P&L as percentage of notional
 pnl_pct = (rate_diff / contract.ndf_rate) * 100 #

 return {
 'fixing_rate': fixing_rate,
 'ndf_rate': contract.ndf_rate,
 'rate_difference': rate_diff,
 'settlement_usd': settlement_usd,
 'buyer_receives': buyer_receives,
 'pnl_pct_of_notional': pnl_pct
 }

 def calculate_mtm_value(
 self,
 contract: NDFContract,
 current_ndf_rate: float,
 days_remaining: int
 ) -> Dict:
 """
 Calculate mark-to-market value of NDF position.


 """
 # Find closest tenor for discount rate
 tenor = min(self.usd_rates.keys(), key=lambda x: abs(x - days_remaining)) #
 discount_rate = self.usd_rates[tenor] #
 discount_factor = 1 / (1 + discount_rate * days_remaining / 360) #

 # Calculate undiscounted P&L
 rate_diff = current_ndf_rate - contract.ndf_rate #
 undiscounted_pnl = contract.notional_usd * rate_diff / current_ndf_rate #

 # Apply discount factor
 mtm_usd = undiscounted_pnl * discount_factor #

 return {
 'current_ndf_rate': current_ndf_rate,
 'original_ndf_rate': contract.ndf_rate,
 'days_remaining': days_remaining,
 'discount_factor': discount_factor,
 'mtm_usd': mtm_usd
 }


class NDFPortfolioManager:
 """
 """
 """
 Portfolio management tools for NDF contracts.
 """

 def __init__(self):
 """ ab11d2b8d267 """
 self.pricer = NDFPricer() #

 def calculate_portfolio_exposure(
 self,
 contracts: List[NDFContract]
 ) -> pd.DataFrame:
 """Calculate net USD exposure by currency from NDF portfolio"""
 exposures = [] #

 for contract in contracts:
 # Each NDF creates USD exposure equal to notional
 exposures.append({
 'currency_pair': contract.currency_pair,
 'notional_usd': contract.notional_usd,
 'ndf_rate': contract.ndf_rate,
 'fixing_date': contract.fixing_date
 })

 df = pd.DataFrame(exposures) #

 # Aggregate by currency
 summary = df.groupby('currency_pair').agg({ #
 'notional_usd': 'sum',
 'ndf_rate': 'mean' # Weighted average would be better in production
 }).reset_index()

 return summary

 def calculate_fixing_risk_var(
 self,
 contract: NDFContract,
 historical_volatility: float,
 confidence_level: float = 0.95 #
 ) -> Dict:
 """
 Calculate Value-at-Risk from fixing rate uncertainty.

 Fixing risk = uncertainty between contracted rate and future fixing. #
 Uses parametric VaR based on historical fixing rate volatility.
 """
 # Z-score for confidence level
 z_scores = {0.90: 1.645, 0.95: 1.960, 0.99: 2.576} #
 z = z_scores.get(confidence_level, 1.960) #

 # Calculate VaR
 spot = self.pricer.spot_rates[contract.currency_pair] #
 var_usd = contract.notional_usd * historical_volatility * z / spot #

 return {
 'notional_usd': contract.notional_usd,
 'volatility': historical_volatility,
 'confidence_level': confidence_level,
 'var_usd': var_usd,
 'var_pct_of_notional': (var_usd / contract.notional_usd) * 100
 }


# =============================================================================
# DEMONSTRATION
# =============================================================================

def demonstrate_ndf_markets() -> Dict:
 """
 """
 Comprehensive demonstration of NDF markets and settlement mechanics.
 """
 print("=" * 80) #
 print("CHAPTER 16: NDF MARKETS - COMPREHENSIVE DEMONSTRATION")
 print("=" * 80) #

 pricer = NDFPricer() #
 pair = 'USD/CNY' #

 # 1. NDF Pricing Across Tenors
 print("\n1. NDF Forward Curve - USD/CNY")
 print("-" * 80)
 print(f"{'Tenor':>8} {'Days':>6} {'NDF Rate':>12} {'Fwd Points':>12} {'Ann. Premium':>15}")
 print("-" * 80)

 tenors = [30, 90, 180, 360] #
 for days in tenors:
 result = pricer.calculate_ndf_rate(pair, days) #
 tenor_label = f"{days}D" #
 ann_premium = ((result['ndf_rate'] - result['spot_rate']) / #
 result['spot_rate']) * (360 / days) * 100

 print(f"{tenor_label:>8} {days:>6} {result['ndf_rate']:>12.4f} "
 f"{result['forward_points']:>12.2f} {ann_premium:>14.2f}%")

 # 2. Sample NDF Contract
 ndf_contract = NDFContract( #
 currency_pair='USD/CNY', #
 notional_usd=1_000_000, # USD 1 million #
 ndf_rate=7.2800, #
 fixing_date=datetime(2025, 11, 28), #
 settlement_date=datetime(2025, 12, 2), #
 fixing_source='CFETS', #
 contract_date=datetime(2025, 8, 1) #
 )

 print("\n\n2. Sample NDF Contract Details")
 print("-" * 80)
 print(f" Currency Pair : {ndf_contract.currency_pair}")
 print(f" Notional (USD) : ${ndf_contract.notional_usd:,.0f}")
 print(f" NDF Rate : {ndf_contract.ndf_rate:.4f}")
 print(f" Fixing Date : {ndf_contract.fixing_date.strftime('%Y-%m-%d')}")
 print(f" Settlement Date : {ndf_contract.settlement_date.strftime('%Y-%m-%d')}")
 print(f" Fixing Source : {ndf_contract.fixing_source}")

 # 3. Settlement Analysis Under Different Fixing Scenarios
 print("\n\n3. Settlement Analysis - Various Fixing Scenarios")
 print("-" * 80)
 print(f"{'Fixing Rate':>12} {'Settlement USD':>18} {'Receiver':>18} {'P&L % of Not.':>15}")
 print("-" * 80)

 fixing_scenarios = [7.1500, 7.2000, 7.2800, 7.3500, 7.4000] #
 for fixing_rate in fixing_scenarios:
 settlement = pricer.calculate_settlement_amount(ndf_contract, fixing_rate) #
 receiver = "Buyer (Long USD)" if settlement['buyer_receives'] else "Seller (Short USD)" #

 print(f"{fixing_rate:>12.4f} {settlement['settlement_usd']:>18,.2f} "
 f"{receiver:>18} {settlement['pnl_pct_of_notional']:>14.2f}%")

 # 4. Mark-to-Market Valuation
 current_ndf_rate = 7.3200 #
 days_remaining = 90 #
 mtm = pricer.calculate_mtm_value(ndf_contract, current_ndf_rate, days_remaining) #

 print("\n\n4. Mark-to-Market Valuation")
 print("-" * 80)
 print(f" Current NDF Rate : {mtm['current_ndf_rate']:.4f}")
 print(f" Contract NDF Rate : {mtm['original_ndf_rate']:.4f}")
 print(f" Days Remaining : {mtm['days_remaining']}")
 print(f" Discount Factor : {mtm['discount_factor']:.6f}")
 print(f" MTM Value (USD) : ${mtm['mtm_usd']:,.2f}")
 print(f" (Positive = gain for USD buyer)") #

 # 5. Portfolio Risk Analysis
 print("\n\n5. Portfolio Exposure Analysis")
 print("-" * 80)

 risk_manager = NDFRiskManager() #

 # Create sample portfolio
 portfolio = [ #
 ndf_contract,
 NDFContract('USD/INR', 500_000, 83.25, datetime(2025, 12, 15),
 datetime(2025, 12, 17), 'RBI', datetime(2025, 9, 1)),
 NDFContract('USD/BRL', 750_000, 4.95, datetime(2025, 11, 20),
 datetime(2025, 11, 22), 'PTAX', datetime(2025, 8, 15))
 ]

 exposure_summary = risk_manager.calculate_portfolio_exposure(portfolio) #
 print(exposure_summary.to_string(index=False)) #

 # 6. Fixing Risk VaR
 print("\n\n6. Fixing Risk Value-at-Risk (95% confidence)")
 print("-" * 80)

 # Historical volatility estimate (annualized)
 historical_vol = 0.08 # 8% annualized volatility for CNY #
 var_result = risk_manager.calculate_fixing_risk_var( #
 ndf_contract,
 historical_vol,
 confidence_level=0.95 #
 )

 print(f" Notional USD : ${var_result['notional_usd']:,.0f}")
 print(f" Volatility (ann.) : {var_result['volatility']:.2%}")
 print(f" Confidence Level : {var_result['confidence_level']:.0%}")
 print(f" VaR (USD) : ${var_result['var_usd']:,.2f}")
 print(f" VaR (% of Not.) : {var_result['var_pct_of_notional']:.2f}%")

 print("\n\n7. Multi-Currency NDF Curve Analysis")
 print("-" * 80)
 print(f"{'Currency':>10} {'30D Points':>12} {'90D Points':>12} {'360D Points':>13} {'Ann. Basis':>12}")
 print("-" * 80)

 currencies = ['USD/CNY', 'USD/INR', 'USD/KRW', 'USD/BRL'] #
 for curr in currencies:
 result_30 = pricer.calculate_ndf_rate(curr, 30) #
 result_90 = pricer.calculate_ndf_rate(curr, 90) #
 result_360 = pricer.calculate_ndf_rate(curr, 360) #

 print(f"{curr:>10} {result_30['forward_points']:>12.0f} "
 f"{result_90['forward_points']:>12.0f} {result_360['forward_points']:>13.0f} "
 f"{result_90['basis_bps']:>11.0f}bp")

 print("\n\n8. Operational Risk Considerations")
 print("-" * 80)
 print("Key Risk Factors for NDF Trading:")
 print(" • Fixing Source Risk: Dependence on CFETS reliability")
 print(" • Basis Risk: NDF-deliverable spread can widen during stress")
 print(" • Liquidity Risk: EM NDFs less liquid than G10, especially longer tenors")
 print(" • Regulatory Risk: China could restrict offshore NDF trading")
 print(" • Counterparty Risk: Requires robust CSA and potentially clearing")

 print("\n\nOperational Best Practices:")
 print(" • Verify fixing source in contract documentation")
 print(" • Monitor basis to deliverable forwards for arbitrage")
 print(" • Maintain diverse counterparty relationships")
 print(" • Implement robust settlement reconciliation")
 print(" • Track regulatory developments in underlying markets")

 print("\n" + "=" * 80) #
 print("KEY TAKEAWAYS")
 print("=" * 80) #
 print("\nNDF Structure:")
 print(" • Cash-settled in USD (no physical delivery)")
 print(" • Fixing rate determines settlement amount")
 print(" • Standard notional in USD for consistency")
 print(" • 2-4 day settlement lag after fixing")

 print("\nPricing Mechanics:")
 print(" • Interest rate parity plus NDF-specific basis")
 print(" • Basis reflects capital controls and liquidity premiums")
 print(" • Forward points generally positive (EM rates > USD)")
 print(" • Curve shape influenced by local monetary policy")

 print("\nMarket Applications:")
 print(" • Hedge EM currency exposure without deliverable access")
 print(" • Corporate hedging for operations in restricted markets")
 print(" • Speculative trading on EM currency views")
 print(" • Portfolio diversification with EM FX exposure")

 print("\nRisk Management:")
 print(" • VaR models must account for fixing volatility")
 print(" • Basis risk monitoring essential")
 print(" • Liquidity planning for early unwind costs")
 print(" • Regulatory change monitoring critical")

 return {
 'pricer': pricer,
 'ndf_contract': ndf_contract,
 'risk_manager': risk_manager,
 'portfolio': portfolio,
 'mtm': mtm,
 'var_result': var_result
 }


# =============================================================================
# EXPECTED OUTPUT & INTERPRETATION
# =============================================================================

"""
When executed, the NDF Markets demonstration produces comprehensive analytics
covering NDF pricing curves, settlement mechanics, mark-to-market valuation,
portfolio exposure analysis, and risk management for emerging market currencies.

In a typical run, the demonstration generates:

1. NDF FORWARD CURVE - USD/CNY
 Tenor Days NDF Rate Fwd Points Ann. Premium
 30D 30 7.2693 193.00 2.66%
 90D 90 7.2878 377.50 2.58%
 180D 180 7.3152 651.50 2.51%
 360D 360 7.3521 1021.00 2.47%

The curve shows CNY trading at forward discount (positive forward points)
reflecting higher USD rates vs CNY plus NDF basis premium. Points increase
with tenor as rate differential and basis accumulate over time.

2. SAMPLE NDF CONTRACT DETAILS
 Currency Pair : USD/CNY
 Notional (USD) : $1,000,000
 NDF Rate : 7.2800
 Fixing Date : 2025-11-28
 Settlement Date : 2025-12-02
 Fixing Source : CFETS

Standard NDF structure with USD notional, 4-day settlement lag, and CFETS
as authoritative fixing source for offshore CNY rates.

3. SETTLEMENT ANALYSIS - VARIOUS FIXING SCENARIOS
 Fixing Rate Settlement USD Receiver P&L % of Not.
 7.1500 -17,832.17 Seller (Short USD) -1.79%
 7.2000 -11,111.11 Seller (Short USD) -1.10%
 7.2800 0.00 Neither (at-the-money) 0.00%
 7.3500 9,523.81 Buyer (Long USD) 0.96%
 7.4000 16,216.22 Buyer (Long USD) 1.65%

Settlement is linear in fixing rate. USD buyer profits when CNY weakens
(fixing > NDF rate), loses when CNY strengthens. Each 100-pip move creates
approximately $13,700 P&L on $1M notional.

4. MARK-TO-MARKET VALUATION
 Current NDF Rate : 7.3200
 Contract NDF Rate : 7.2800
 Days Remaining : 90
 Discount Factor : 0.987179
 MTM Value (USD) : $5,391.55

Market moved 40 pips favorable (7.32 vs 7.28), creating unrealized gain
for USD buyer. Discounting reduces present value slightly due to 90-day
time to maturity.

5. PORTFOLIO EXPOSURE ANALYSIS
currency_pair notional_usd ndf_rate
 USD/BRL 750000.0 4.9500
 USD/CNY 1000000.0 7.2800
 USD/INR 500000.0 83.2500

Total $2.25M USD exposure across three EM currencies provides diversification
while maintaining net long USD position. Different fixing dates create
natural staggering of settlement risk.

6. FIXING RISK VALUE-AT-RISK (95% confidence)
 Notional USD : $1,000,000
 Volatility (ann.) : 8.00%
 Confidence Level : 95%
 VaR (USD) : $21,629.66
 VaR (% of Not.) : 2.16%

VaR captures potential loss from fixing rate uncertainty. 8% CNY volatility
implies 95% confidence that loss won't exceed $21,630 over position lifetime.
"""


# =============================================================================
# HOW TO READ THIS
# =============================================================================

"""
**Understanding NDF Structure:**

Non-Deliverable Forwards solve the problem of hedging exposure to currencies
with restricted convertibility or capital controls. Instead of physical delivery,
NDFs settle in USD based on the difference between contracted rate and official
fixing rate. This allows exposure to CNY, INR, BRL, KRW, and other EM currencies
without requiring access to onshore markets.

Example: European company has CNY 10M receivable in 3 months but cannot access
onshore CNY markets. Sells USD/CNY NDF at 7.2800, protecting against CNY
strengthening. If fixing is 7.1500 (CNY stronger), company receives $181,818
USD settlement compensating for reduced CNY receivable value.

Critical distinction from deliverable forwards: NDF never involves physical
currency exchange. All settlement occurs in USD through correspondent banking
relationships, making NDFs accessible to any institution with USD accounts.

**Interpreting NDF Pricing:**

NDF rates derive from interest rate parity plus basis adjustment:

The NDF basis (typically 10-60 bps annually) reflects several factors:
- Onshore/offshore liquidity differentials
- Capital control costs and regulatory uncertainty
- Credit quality differences between onshore and offshore counterparties
- Supply/demand imbalances in NDF markets

USD/CNY example: 30-day NDF basis of 15 bps means NDFs trade richer than
theoretical covered interest parity, reflecting premium for accessing CNY
exposure through offshore mechanism versus restricted onshore markets.

**Reading Settlement Mechanics:**


This formula ensures settlement is proportional to percentage currency movement,
not absolute pip change. For USD/CNY NDF at 7.2800:

Positive settlement favors USD buyer (EM currency depreciated), negative favors
USD seller (EM currency appreciated). Linear payoff creates perfect hedge for
underlying EM currency exposures.

**Understanding MTM Valuation:**

MTM measures unrealized P&L from changes in NDF rates before fixing:

For position with original NDF 7.2800, current market 7.3200:
- Rate move favors USD buyer by 40 pips
- Discounted for 90 days @ 5.2% = $5,392 #

MTM fluctuates daily with NDF rate changes, creating mark-to-market exposure
requiring margin/collateral management under credit support agreements.

**Reading Risk Metrics:**

Fixing Risk VaR quantifies potential loss from fixing rate uncertainty:

For $1M CNY NDF with 8% annual volatility, 95% confidence:

This represents maximum expected loss with 95% confidence, assuming normal
distribution of fixing rates. Actual fixing could exceed VaR during tail
events or market disruptions.

**Practical Applications and Use Cases:**

Corporate Hedging:
Multinational with CNY 50M quarterly revenue executes rolling 3-month USD/CNY
NDFs to hedge translation exposure. Typical structure:
- Quarterly NDFs totaling CNY 50M (~$7M USD equivalent)
- Ladder maturities to match cash flow timing
- Hedge effectiveness testing under ASC 815/IFRS 9

Portfolio Diversification:
Emerging market hedge fund creates diversified EM FX exposure through NDF
portfolio across CNY, INR, BRL, KRW. Benefits:
- Access to restricted currencies without regulatory constraints
- USD settlement simplifies operational procedures
- Leverage available through prime brokerage relationships

Central Bank Intervention:
PBOC influences offshore CNY rates indirectly through NDF market intervention.
During CNY pressure, PBOC can:
- Jawbone market participants on NDF positioning
- Influence fixing methodology to discourage speculation
- Coordinate with Hong Kong Monetary Authority on offshore liquidity

**Operational Considerations:**

Fixing Sources:
Each currency has authoritative fixing source determining settlement:
- CNY: CFETS (China Foreign Exchange Trade System)
- INR: RBI (Reserve Bank of India)
- BRL: PTAX (Banco Central do Brasil)
- KRW: BOK (Bank of Korea)

Contract documentation must specify exact fixing source, timing, and fallback
procedures for disrupted fixings. Reuters/Bloomberg pages provide fixing
distribution but central bank sources remain authoritative.

Settlement Procedures:
NDFs settle T+2 after fixing through correspondent banking. Settlement involves:
- Fixing rate confirmation between counterparties
- Settlement amount calculation and verification
- USD wire transfer to net recipient
- Trade confirmation and settlement notices

Portfolio Management:
Large NDF portfolios require sophisticated risk management:
- Delta hedging using spot or deliverable forwards where available
- Gamma monitoring for non-linear exposures
- Vega hedging using FX options on deliverable pairs
- Regular stress testing across multiple crisis scenarios

**Risk Management Framework:**

Fixing Source Risk:
Dependence on official fixing creates concentration risk. CFETS manipulation
concerns during 2015-2016 CNY volatility highlighted vulnerability to
administrative intervention. Mitigation strategies:
- Diversification across multiple EM currencies
- Monitoring of fixing methodology changes
- Contractual fallback mechanisms for disrupted fixings

Basis Risk:
NDF-deliverable basis can widen dramatically during stress. March 2020 saw
basis blow out 200-300 bps across EM currencies. Risk factors:
- Dollar funding stress affecting offshore markets
- Regulatory uncertainty in underlying countries
- Flight-to-quality reducing EM risk appetite

Liquidity Risk:
NDF markets less liquid than G10, especially at longer tenors and during stress.
Bid-offer spreads can widen from 2-3 pips to 50+ pips during volatility.
Liquidity management requires:
- Diverse counterparty relationships
- Understanding of market maker risk appetite
- Contingency funding for margin calls
- Early warning systems for liquidity deterioration

The framework provides institutional-grade NDF capabilities for banks, hedge
funds, and corporate treasuries managing emerging market currency exposures
through the $500B+ daily NDF markets.
"""


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

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