别再死记硬背公式了!用Python实战推导远期/期货定价(附沪深300、国债案例代码)

张开发
2026/4/16 19:26:29 15 分钟阅读

分享文章

别再死记硬背公式了!用Python实战推导远期/期货定价(附沪深300、国债案例代码)
用Python实战推导金融衍生品定价从理论到代码的完整指南金融衍生品定价一直是量化金融领域的核心课题但传统教材往往停留在数学公式层面让学习者陷入看得懂推不出推得出用不了的困境。今天我们将彻底改变这一现状——用Python代码完整复现远期合约与期货定价的全过程涵盖沪深300指数、国债、商品期货等典型场景。这不是简单的公式翻译而是从第一性原理出发通过代码重新发明这些定价模型。1. 环境准备与基础工具搭建在开始定价模型之前我们需要配置一个高效的Python量化分析环境。推荐使用Jupyter Notebook或VS Code作为开发环境它们提供了完美的代码、文档和可视化整合体验。核心工具包安装pip install numpy pandas matplotlib scipy提示建议使用Python 3.8版本以获得最佳性能金融计算中对浮点精度要求较高新版Python在数值运算上有明显优化让我们先构建几个金融计算的基础工具函数这些将成为后续定价模型的基石import numpy as np import pandas as pd from math import exp, log from datetime import datetime, timedelta def continuous_compound_rate(r, t): 连续复利计算器 return exp(r * t) def present_value(cashflow, r, t): 现金流现值计算 return cashflow * exp(-r * t)这个基础模块虽然简单但已经包含了金融工程最核心的两个计算要素时间价值折算和连续复利处理。注意我们直接使用math模块的exp函数而非numpy的版本因为在单值计算时前者效率更高。2. 无套利定价原理的代码实现无套利原则是衍生品定价的基石其核心思想是相同的未来现金流在当前必须具有相同的价格。让我们用Python将这一抽象原则转化为可验证的代码逻辑。2.1 远期合约定价的基本模型考虑一个最简单的无分红资产的远期合约其理论价格应满足def forward_price_spot(spot, r, T): 计算无分红资产的远期价格 参数 spot: 现货价格 r: 无风险利率(年化连续复利) T: 到期时间(年) 返回 远期理论价格 return spot * continuous_compound_rate(r, T)验证案例假设沪深300指数当前为3850点无风险利率3%3个月期远期合约的理论价格应该是spot 3850 r 0.03 T 3/12 fair_price forward_price_spot(spot, r, T) print(f沪深300指数3个月远期理论价格{fair_price:.2f}点)注意这里的T必须用年化时间表示金融领域的时间计算必须保持单位一致性2.2 套利机会检测系统根据无套利原理我们可以构建一个实时监测市场套利机会的工具def arbitrage_checker(market_forward, theoretical_forward, transaction_cost0.0005): 套利机会检测器 参数 market_forward: 市场实际远期价格 theoretical_forward: 理论远期价格 transaction_cost: 交易成本比例 返回 套利方向和利润空间 lower_bound theoretical_forward * (1 - transaction_cost) upper_bound theoretical_forward * (1 transaction_cost) if market_forward upper_bound: return (卖出远期买入现货, market_forward - upper_bound) elif market_forward lower_bound: return (买入远期卖出现货, lower_bound - market_forward) else: return (无套利机会, 0)实战测试当市场远期报价比理论价格高0.8%时arb_direction, arb_profit arbitrage_checker( market_forward3880, theoretical_forward3850*exp(0.03*0.25) ) print(f套利策略{arb_direction}预期利润{arb_profit:.2f}点)3. 持有成本模型的Python实现持有成本模型(Cost of Carry)是期货定价的更通用框架它系统性地考虑了融资成本、存储费用和持有收益三大要素。3.1 股票指数期货定价对于沪深300这类支付连续股息的指数期货其定价公式需要调整股息收益率def equity_index_future(spot, r, q, T): 股票指数期货定价模型 参数 spot: 现货指数点位 r: 无风险利率 q: 连续股息收益率 T: 到期时间(年) 返回 期货理论价格 return spot * continuous_compound_rate(r - q, T)案例验证以2023年沪深300数据为例spot 3825 # 当前指数点位 r 0.025 # 无风险利率2.5% q 0.018 # 股息收益率1.8% T 6/12 # 半年期合约 future_price equity_index_future(spot, r, q, T) print(f沪深300指数6个月期货理论价格{future_price:.2f}点)3.2 国债期货定价模型国债期货的定价需要处理离散付息问题这是与指数期货的关键区别def bond_future_price(clean_price, coupon_rate, last_coupon, next_coupon, r, T): 国债期货定价模型 参数 clean_price: 债券净价 coupon_rate: 票面利率(年化) last_coupon: 上次付息日(天数前) next_coupon: 下次付息日(天数后) r: 无风险利率 T: 期货到期时间(天数) 返回 国债期货理论全价 # 计算应计利息 coupon_period last_coupon next_coupon accrued_interest 100 * (last_coupon / coupon_period) * (coupon_rate / 2) # 计算现货全价 dirty_price clean_price accrued_interest # 计算利息现值 coupon_pv (100 * coupon_rate / 2) * exp(-r * next_coupon / 365) # 期货理论价格 future_price (dirty_price - coupon_pv) * exp(r * T / 365) return future_price国债期货计算示例bond_future bond_future_price( clean_price98.36, coupon_rate0.06, last_coupon60, next_coupon122, r0.08, T270 ) print(f国债期货理论价格{bond_future:.2f}元)4. 商品期货与外汇期货的定价实践4.1 包含仓储成本的商品期货模型商品期货需要考虑仓储成本和便利收益这两个特殊因素def commodity_future(spot, r, u, z, T): 商品期货定价模型 参数 spot: 现货价格 r: 无风险利率 u: 仓储成本率(连续复利) z: 便利收益率(连续复利) T: 到期时间(年) 返回 商品期货理论价格 return spot * continuous_compound_rate(r u - z, T)螺纹钢期货案例steel_future commodity_future( spot4200, # 螺纹钢现货价格(元/吨) r0.03, # 无风险利率 u0.02, # 年仓储成本2% z0.01, # 便利收益率1% T90/365 # 90天合约 ) print(f螺纹钢90日期货理论价格{steel_future:.2f}元/吨)4.2 外汇期货定价与利率平价外汇期货定价遵循利率平价理论反映两种货币的利率差异def currency_future(spot, r_domestic, r_foreign, T): 外汇期货定价模型 参数 spot: 即期汇率 r_domestic: 本币利率 r_foreign: 外币利率 T: 到期时间(年) 返回 外汇期货理论价格 return spot * continuous_compound_rate(r_domestic - r_foreign, T)美元/人民币期货示例usdcny_future currency_future( spot6.85, r_domestic0.025, # 人民币利率 r_foreign0.04, # 美元利率 T3/12 ) print(f3个月美元/人民币期货理论价格{usdcny_future:.4f})5. 现实市场中的定价修正完全市场的假设在现实中并不成立我们需要对基本模型进行现实性修正。5.1 考虑交易成本的定价区间def no_arbitrage_band(theoretical_price, transaction_cost, r_borrow, r_lend, T, short_restrictionNone): 计算无套利区间 参数 theoretical_price: 理论价格 transaction_cost: 交易成本比例 r_borrow: 借款利率 r_lend: 贷款利率 T: 到期时间(年) short_restriction: 卖空限制比例 返回 (价格下限, 价格上限) upper theoretical_price * (1 transaction_cost) * continuous_compound_rate(r_borrow, T) if short_restriction: lower (1 - short_restriction) * theoretical_price * (1 - transaction_cost) * continuous_compound_rate(r_lend, T) else: lower theoretical_price * (1 - transaction_cost) * continuous_compound_rate(r_lend, T) return (lower, upper)黄金期货案例gold_spot 450 # 美元/盎司 r 0.03 # 基准利率 gold_theoretical gold_spot * exp(r * 1) # 1年期 band no_arbitrage_band( theoretical_pricegold_theoretical, transaction_cost0.001, r_borrow0.035, r_lend0.025, T1, short_restriction0.2 ) print(f黄金期货无套利区间[{band[0]:.2f}, {band[1]:.2f}])5.2 市场冲击与流动性调整def liquidity_adjustment(mid_price, bid_ask_spread, position_size, market_depth): 流动性调整模型 参数 mid_price: 市场中间价 bid_ask_spread: 买卖价差比例 position_size: 头寸规模 market_depth: 市场深度系数 返回 经流动性调整后的实际执行价格 impact_factor position_size / market_depth adjusted_price mid_price * (1 bid_ask_spread/2 * impact_factor) return adjusted_price实际应用示例actual_execution liquidity_adjustment( mid_price102.35, bid_ask_spread0.001, position_size500000, market_depth2000000 ) print(f考虑流动性后的实际执行价格{actual_execution:.4f})6. 完整定价系统的构建现在我们将所有模块整合成一个完整的期货定价系统class FuturesPricingSystem: def __init__(self, risk_free_rate0.03): self.risk_free_rate risk_free_rate self.market_data {} def update_market_data(self, asset_type, **kwargs): 更新市场数据 self.market_data[asset_type] kwargs def calculate_fair_price(self, asset_type, T): 计算各类资产的期货理论价格 data self.market_data.get(asset_type, {}) if asset_type equity_index: return equity_index_future( spotdata[spot], rself.risk_free_rate, qdata[dividend_yield], TT ) elif asset_type bond: return bond_future_price( clean_pricedata[clean_price], coupon_ratedata[coupon_rate], last_coupondata[last_coupon], next_coupondata[next_coupon], rself.risk_free_rate, TT ) elif asset_type commodity: return commodity_future( spotdata[spot], rself.risk_free_rate, udata[storage_cost], zdata[convenience_yield], TT ) elif asset_type currency: return currency_future( spotdata[spot], r_domesticself.risk_free_rate, r_foreigndata[foreign_rate], TT ) else: raise ValueError(Unsupported asset type) # 系统使用示例 pricing_system FuturesPricingSystem(risk_free_rate0.025) # 更新沪深300数据 pricing_system.update_market_data( asset_typeequity_index, spot3825, dividend_yield0.018 ) # 计算3个月期货价格 future_price pricing_system.calculate_fair_price(equity_index, T3/12) print(f系统计算的沪深300期货理论价格{future_price:.2f})这个定价系统类可以轻松扩展支持更多资产类型并保持统一的接口。在实际应用中可以将其与实时数据源连接构建自动化的定价监控系统。

更多文章