金融工程综合实验与实践


吴克坤


中南财经政法大学
金融工程系

课程介绍

  • 教学内容:

    • 公文写作、学术论文写作
    • 金工/金融系列专题
    • 金融职业规划指导
  • 教学形式:

    • 专题讲座
    • 与金融系合上

文献与资源:kktim.cn

  • 考核方式与成绩构成

    • 课程项目:100%
    • 内容与形式:量化交易策略、金融产品设计、案例分析、研究报告、学术论文
    • 要求:选题与金融工程密切相关;应用金融工程方法、原理
  • DDLs:

    • 提交选题:2024-03-29 (wk5)
    • 提交报告:2024-06-14 (wk16)
  • 提交方式(链接/二维码):见下页

提交选题
提交报告/PPT/视频
  • 二维码

关于金融与金融工程

“金融”的意义

  • 黄洪:
    • 金融一词并非古已有之。‘金’与‘融’这两个字,是极古老的中国字,可是这两个字连在一起组成一个既不能单独用‘金’字解释也不能单独用‘融’字解释的词—金融—则不见于任何古籍。《康熙字典》(1716)及其以前的所有辞书均无金与融连用的记栽。作为一个词条,最早见于1915年初版的《辞源》和1937年初版的《辞海》。这说明,至迟在19世纪下半叶,金与融这两个字组成的词已经定型并在经济领域中相当广泛地使用;两部辞书的释义均指通过信用中介机构的货币资金融通。”
    • 连起来的‘金融’始于何时,无确切考证,最大可能是来自明治维新的日本。那一阶段,有许多西方经济学的概念就是从日本引进的—直接把日语翻译西文的汉字搬到中国来。
  • 艾俊川:古籍中“金融”义指“黄金融制而成”。

  • 张辑颜:金融者,金币之融通状况之谓也。故金融学科,为研究金币之融通状况,及其与国家财政,民生经济,所生各种关系之学科也。金融之名词译自日本:盖日本以金币为本位,故称金融。”

  • 艾俊川:

    • (日本)“金融”二字连用之词,显然是“金钱融通”的缩略(1875)
    • 将“金融”译为英文The Circulation of Money(1897,1911)
    • 在此后十年间,日本书籍报刊中“金融”一词爆发性使用,词义也开始转变,被用来指称与货币和信用有关的交易与经济活动,日译本“金融”对应英语名词“money market"(1883)
  • 孙大权:
    • 1902年4月22日,梁启超独自编辑的《新民丛报》登载了关于“金融“一词的“问答”。东京爱读生问:“日本书中金融二字其意云何?中国当以何译之?”梁启超答道: “金融者指金银行情之变动涨落。……日本言金融,取金钱融通之意,如吾古者以泉名币也。沿用之似亦可乎。
    • Finance最初在中国和日本均为与“财政”有关的含义1929年3月,萧纯锦在编译自美国的《经济学》里指出:“‘金融’(在英文为Finance)
    • 1941 年,由何廉、陈岱孙、陈启修等 32 位著名经济学家审查通过,由国民政府教育部公布的《经济学名词》中,Finance 对译为“财政,金融”; Money Market 对译为“金融市场”;Money对译为“货币”;Currency 对译为“通货”“金融”唯一的对应译词为Finance,这样,金融与Finance对译就成为民国主流经济学家认可的用法。

金融活动

金融课程

金融研究

  • 学术期刊
期刊 创刊年份
The Journal of Finance 1946
Journal of Financial and Quantitative Analysis 1966
Journal of Financial Economics 1974
金融研究 1980
The Review of Financial Studies 1988
  • 学会/协会
协会 创办年份
The American Finance Association 1939
中国金融学会 1950
Western Finance Association 1965
European Finance Association 1974
Society for Financial Studies 1987

什么是金融?

  • 金融学研究资源如何有效地在不确定的条件下跨期分配

  • 金融学研究的几个重要问题:

    • 资产定价
    • 风险管理
    • 资产配置

与金融相关的诺贝尔经济学奖

  • 1981: James Tobin “for his analysis of financial markets and their relations to expenditure decisions, employment, production and prices”.

  • 1985: Franco Modigliani “for his pioneering analyses of saving and of financial markets”.

  • 1990: Harry M. Markowitz, Merton H. Miller and William F. Sharpe “for their pioneering work in the theory of financial economics”.

  • 1997: Robert C. Merton and Myron S. Scholes “for a new method to determine the value of derivatives”.

  • 2003: Robert F. Engle III “for methods of analyzing economic time series with time-varying volatility (ARCH)”. Clive W.J. Granger “for methods of analyzing economic time series with common trends (cointegration)

  • 2013: Eugene F. Fama, Lars Peter Hansen and Robert J. Shiller “for their empirical analysis of asset prices”.

  • 2017: Richard H. Thaler “for his contributions to behavioural economics”.

什么是金融工程?


什么是工程?

  • 工程是...

    • 利用基本的材料、工具、部件、器材、结构
    • 在相关基础理论的指导下、按照某(些)种工艺、技术进行组合、装配
    • 实现一定的功能、满足特定需求、解决具体问题

兹维博迪的定义


Financial engineering is the application of science-based mathematical models to decisions about saving, investing, borrowing, lending, and managing risk. -- by Zvi Bodie


  • 金融工程是金融理论工程方法的结合
  • 金融工程不是一个工程学科
  • 金融工程的发展基于现代金融理论
  • 金融工程是一个应用学科

国际数量金融协会(iaqf)对金融工程的介绍

  • Financial engineering is the application of mathematical methods to the solution of problems in finance. It is also known as financial mathematics, mathematical finance, and computational finance.

  • Financial engineering draws on tools from applied mathematics, computer science, statistics, and economic theory.

  • Investment banks, commercial banks, hedge funds, insurance companies, corporate treasuries, and regulatory agencies employ financial engineers.

  • These businesses apply the methods of financial engineering to such problems as new product development, derivative securities valuation, portfolio structuring, risk management, and scenario simulation.

  • Quantitative analysis has brought innovation, efficiency and rigor to financial markets and to the investment process.

  • As the pace of financial innovation accelerates, the need for highly qualified people with specific training in financial engineering continues to grow in all market environments.

金融工程的研究领域

金融工程的核心问题

  • 核心问题

    • 资产定价(基础资产、衍生工具、复杂的结构化产品)
    • 组合管理/优化
    • 风险管理
  • 原理与方法

    • 合成与复制
    • 无套利动态过程
    • 风险中性

金融工程:合成与复制

  • BofA Finds Way to Gain From Alibaba IPO Even After Advisory Snub

    • 思路:做多阿里巴巴的主要股东(Softbank、Yahoo),同时做空非阿里巴巴收入的成分
    • BAML的做法:买Soft bank,卖Sprint,卖Yahoo Japan,卖KDDI
  • 期权定价:用含有期权的组合复制无风险证券

    • 做空一份期权合约
    • 做多若干股股票

金融工程:无套利动态过程

  • 套利机会存在的条件

    • 存在两个不同的资产组合,它们的未来现金流相同,但它们的成本却不同
    • 存在两个成本相同的组合,第一个组合在所有可能状态下的现金流都不低于第二个组合,而且至少存在一种状态,在此状态下第一个组合的现金流大于第二个组合
    • 一个组合的成本为零,但在所有可能状态下,这个组合的损益都不小于零,而且至少存在一种状态,在此状态下这个组合的损益要大于零
  • 套利的实现

    • 买入被低估的资产(组合),卖出被高估的资产(组合)
    • 通过融资/融券使初始投资为零
    • 在期末获得正的利润
  • 无套利动态过程

金融工程:风险中性

  • 风险中性定价理论有两个最基本的假设:

    • 在一个投资者都是风险中性的世界里,所有证券的预期收益率均为无风险收益率
    • 投资者的投资成果体现为用无风险利率贴现收益现金流得到的现值
  • 无风险的套利机会出现时

    • 市场参与者的套利活动与其对风险的态度无关(套利分析时未用到风险偏好信息
    • 无套利均衡分析的过程和结果与市场参与者的风险偏好无关
    • 因此,假设风险中性世界(风险中性定价)简化分析
  • 从风险中性世界进入到风险厌恶或者风险喜好的世界时:

    • 概率分布发生变化)资产的预期收益率发生变化
    • 资产任何损益(或现金流)所适用的贴现率发生改变
    • 以上两个变化效果互相抵消

金融工程发展的时间线


Source: Beder T S, Marshall C M. Financial engineering: the evolution of a profession[M]. John Wiley & Sons, 2011.

金融工程发展的历史逻辑

  • 历史背景

    • 经济全球化与金融自由化
  • 理论基础

    • 现代投资组合理论:Markowitz (1952)
    • 资本资产定价模型:Sharpe (1964),Lintner (1964),Treynor (1964)
    • 期权定价理论:Black and Scholes (1973)
  • 技术条件

    • 信息技术与计算能力的发展(计算机、互联网、并行计算、云计算)
    • 最优化理论与算法的进展
    • 大数据、人工智能
  • 数理基础

    • 概率论与随机过程的严格化
    • 宇航科学与随机控制

金融工程与大数据

  • 金融数据
  • 大数据(4v)
    • Volume: The amount of data collected in files, records, and tables is very large, representing many millions, or even billions, of data points (GB->TB->PB->EB->ZB).
    • Velocity: The speed with which the data are communicated is extremely great. Real- time or near- real- time data have become the norm in many areas.
    • Variety: The data are collected from many different sources and in a variety of formats, including structured data (e.g., SQL tables or CSV files), semi-structured data (e.g., HTML code), and unstructured data (e.g., video messages).
    • Value: Low value density.

Model Building for Financial Forecasting Using Big Data


Source: 2020 CFA Program curriculum Reading 8

金融工程学科

  • 金融工程是创新性金融技术和金融工具的创造性应用,它用工程思维解决具体的金融问题
    • 金融工程是技术驱动
    • 金融工程是天生的交叉学科
    • 金融工程始终关注新技术
  • 金融工程的作用
    • 微观:通过创造性的方案更好地满足客户的金融需求
    • 宏观:提高金融资源配置效率
Scientists Engineers
understand things Build thing
observe the world seek to change the world
very theoretical more practical
embrace ambiguity often frustrated by it
work free work hard


Source: Lo, Andrew W.. “Robert C. Merton: The First Financial Engineer.” Review of Financial Economics 12 (2020): 1-18.

关于金融工程教育

  • 金融工程的学历教育项目
    • 几乎没有金融工程的本科项目
    • 有许多(授课式/专业型)硕士研究生项目 (Financial Engineering, Quantitative Finance, Mathematical Finance, Financial Mathematics)
    • 有一些博士项目专注该领域
    • 学位由工程学院、数学系、统计系、运筹与管理科学系等院系授予
    • Ranking & Placement: Quantnet Ranking, Program Websites, LinkedIn
  • 课程与技能

    • 经济学与金融学
    • 数学、理论物理
    • 运筹学与统计学
    • 信息理论、编程
  • 金融工程师的专业背景

    • 火箭科学家、应用数学家、运筹学、计算机科学家
    • 金融工程项目的毕业生

金融工程职业


Source: Beder T S, Marshall C M. Financial engineering: the evolution of a profession[M]. John Wiley & Sons, 2011.

我校金融工程专业的历史沿革及基本概况

  • 历史沿革
    • 90年代中期周骏教授积极倡导在金融学大框架内增设金融工程专业方向
    • 2003年成立金融工程教研室开始招收硕士研究生
    • 2005年开始在硕士研究生教育中设立金融工程专业,全面面向金融专业本科生讲授金融工程课程
    • 2007年开始招收本科生,2009年成立金融工程系
    • 2019年被评为首批国家级一流本科专业建设点
    • 2018年开始大类招生,分流后每年学生规模在50人左右
  • 专业排名
    • 《中国大学及学科专业评价报告》:20/258(2020),10/259(2021),8/264(2022),4/259(2023)
    • 校友会2022中国大学金融工程专业排名(研究型):全国第2(2022),全国第2(2023)

我校金融工程专业特色、目标及主要课程

  • 专业特色与培养目标
    • 专业特色:突出应用型、创新性、国际化人才的培养特色,强调交叉学科的思维培养,要求学生不仅具有扎实的经济学、金融学基础,同时具备管理学、法学等多学科知识背景,能综合运用数学、统计学、运筹学和计算机知识分析和解决实际金融问题。
    • 培养目标:坚持“面向现代化、面向世界、面向未来”的人才培养理念,培养具有良好政治素质和职业道德、宽厚扎实的现代经济金融和数理统计基础、掌握金融工程专门技术、富有创新精神和实践能力的应用型、创新性、国际化金融人才。
  • 主要课程
    • 专业必修课:证券投资学、公司金融(双语)、固定收益证券(双语)、金融工程、金融计量学(双语)、金融风险管理、数值计算与金融仿真(双语、实验)
    • 专业选修课:金融衍生工具、金融科技导论、证券投资分析(实验)、量化投资(实验)、投资银行学、金融经济学、金融工程前沿专题、机器学习等
    • 国家一流本科课程:证券投资学(线上线下混合,2020)、金融工程(线下,2023)、数值计算与金融仿真(虚拟仿真,2023)

金融工程专业历届推免情况


年份 推免生典型去向 推免至985比例
2017届 复旦、厦大、中山、外经贸等 53.85%
2018届 复旦、人大、中山、南大等 74.36%
2019届 北大、浙大、南大、华科等 44.68%
2020届 北大、华科、复旦等 56.10%
2021届 复旦、上财、中南大等 50.00%
2022届 北大、武大、华科、上财等 57.14%
2023届 北大、南大、浙大、华科等 50.00%

金融工程专业历届升学情况


年份 国内升学典型去向 海外升学典型去向
2017届 复旦、厦大、中山、外经贸等 哥伦比亚、纽约大学、南加州等
2018届 复旦、人大、中山、南大等 伯克利、约翰霍普金斯、圣路易斯华盛顿等
2019届 北大、浙大、南大、华科等 哥伦比亚、纽约大学、康奈尔等
2020届 北大、华科、复旦等 康奈尔、UCLA、牛津等
2021届 复旦、上财、中南大等 哥伦比亚、密歇根、香港大学
2022届 北大、武大、华科、上财等 LSE、哥伦比亚、纽约大学等
2023届 北大、南大、浙大、华科等 新加坡国立、格拉斯哥、杜伦大学等

金融工程的应用:量化投资

理解量化投资

  • 什么是量化投资?

    • 量化投资vs传统投资
    • 量化vs自动化vs算法
    • 基本分析、技术分析、量化投资
  • 量化投资策略

    • 按交易的工具的品种
    • 按策略的频率
    • ...
  • 量化投资产生和发展的基础

    • 国际政治经济形势
    • 计算能力(硬件)
    • 相关学科的发展

Developing a Quant Strategy


  • Specify the trading rules in a definitive, objective, and computer-testable form

  • Tranform a rouph idea into a set of trading rules

    • Entry & Exit
    • Risk Management
    • Position Sizing
  • Tranform the trading rules into computer programs

  • Example: a simple MA strategy

The Human Language Pseudocode


  1. Calculate a fast moving average
  2. Calculate a slow moving average
  3. Go long when yesterday the fast moving average was below the slow moving average and today the fast moving average is above the slow moving average
  4. Once long, stay long until a sell entry occurs
  5. Go short when yesterday the fast moving average was above the slow moving average and today the fast moving average is below the slow moving average
  6. Once short, stay short until a buy entry occurs

The Pseudocode

  1. is the close of the t-th day with , the present day
  2. is the length of moving average one (MA1)
  3. is the length of moving average one (MA2)
  4. is never less than 2 times
  5. If we have no position and and , then go long.
  6. If we are short and and , then go long.
  7. If we have no position and and , then go short.
  8. If we are short and and , then go short.

Example: Coding with Backtrader


# 导入必要的库
import backtrader as bt
import matplotlib as mpl  
import matplotlib.pyplot as plt
import tushare as ts
import pandas as pd
import os
from datetime import datetime

定义策略

class SmaCross(bt.Strategy):
    # list of parameters which are configurable for the strategy
    params = dict(
        pfast=10,  # period for the fast moving average
        pslow=30   # period for the slow moving average
    )
    def __init__(self):
        super().__init__()
        sma1 = bt.ind.SMA(period=self.p.pfast)  # fast moving average
        sma2 = bt.ind.SMA(period=self.p.pslow)  # slow moving average
        self.crossover = bt.ind.CrossOver(sma1, sma2)  # crossover signal
    def next(self):
        if not self.position:  # not in the market
            if self.crossover > 0:  # if fast crosses slow to the upside
                self.order_target_size(target=1)  # enter long
            elif self.crossover < 0:  # in the market & cross to the downside
            self.order_target_size(target=0)  # close long position

策略执行

data_path = './data/'
if not os.path.exists(data_path):
    os.makedirs(data_path)
    mytoken='f3244*****8addef6e******ad68fa95b18c*****c3a5238533*****'
class Strategy_runner:
    def __init__(self, strategy, ts_code, start_date, end_date, data_path=data_path, 
	pro=False, token=mytoken):
        self.ts_code = ts_code
        self.start_date = start_date
        self.end_date = end_date
        # convert to datetime
        self.start_datetime = datetime.strptime(start_date,'%Y%m%d')
        self.end_datetime = datetime.strptime(end_date,'%Y%m%d')
        if pro:
            csv_name = f'pro_day_{str(ts_code)}-{str(start_date)}-{str(end_date)}.csv'
        else:
            csv_name = f'day_{str(ts_code)}-{str(start_date)}-{str(end_date)}.csv'
            csv_path = os.path.join(data_path,csv_name)
        if os.path.exists(csv_path):
            if pro:
                self.df = pd.read_csv(csv_path)
            else:
                self.df = pd.read_csv(csv_path,index_col=0)
        else:
            if pro:
                ts.set_token(mytoken)
                self.pro = ts.pro_api()
                self.df = self.pro.daily(ts_code=self.ts_code, 
				start_date=self.start_date, 
				end_date=self.end_date)
                if not self.df.empty:
                    self.df.to_csv(csv_path, index=False)
            else:
                self.df = ts.get_hist_data(self.ts_code, 
				str(self.start_datetime), 
				str(self.end_datetime))
                if not self.df.empty:
                    self.df.to_csv(csv_path, index=True)
            
        self.df_bt = self.preprocess(self.df, pro)
        print(self.df_bt)
        self.strategy = strategy
        self.cerebro = bt.Cerebro()
    def preprocess(self, df, pro=False):
        if pro:
            features=['open','high','low','close','vol','trade_date']
            convert_datetime = lambda x: pd.to_datetime(str(x))
            df['trade_date'] = df['trade_date'].apply(convert_datetime)
            print(df)
            bt_col_dict = {'vol':'volume','trade_date':'datetime'}
            df = df.rename(columns=bt_col_dict)
            df = df.set_index('datetime')
            # df.index = pd.DatetimeIndex(df.index)
        else:
            features=['open','high','low','close','volume']
            df = df[features]
            df['openinterest'] = 0
            df.index = pd.DatetimeIndex(df.index)

        df = df[::-1]
        return df
    def run(self):
        data = bt.feeds.PandasData(dataname=self.df_bt, fromdate=self.start_datetime, 
		todate=self.end_datetime)
        self.cerebro.adddata(data)  # Add the data feed
        self.cerebro.addstrategy(self.strategy)  # Add the trading strategy
        self.cerebro.broker.setcash(100000.0)
        self.cerebro.addanalyzer(bt.analyzers.SharpeRatio,_name = 'SharpeRatio')
        self.cerebro.addanalyzer(bt.analyzers.DrawDown, _name='DW')
        self.results = self.cerebro.run()
        strat = self.results[0]
        print('Final Portfolio Value: %.2f' % self.cerebro.broker.getvalue())
        print('SR:', strat.analyzers.SharpeRatio.get_analysis())
        print('DW:', strat.analyzers.DW.get_analysis())
        return self.results
    
    def plot(self, iplot=False):
        self.cerebro.plot(iplot=iplot)

ts_code='002456.SZ'
start_date='20240101'
end_date='20241231'
strategy_runner = Strategy_runner(strategy=SmaCross, ts_code=ts_code, 
    start_date=start_date, end_date=end_date, pro=True)
results = strategy_runner.run()
strategy_runner.plot()

欧菲光(002456.SZ):2020-01-01 ~ 2020-12-31

欧菲光(002456.SZ):2021-01-01 ~ 2021-12-31

欧菲光(002456.SZ):2022-01-01 ~ 2022-12-31

欧菲光(002456.SZ):2023-01-01 ~ 2023-12-31

海南机场(600515.SH):2020-01-01 ~ 2020-12-31

海南机场(600515.SH):2021-01-01 ~ 2021-12-31

海南机场(600515.SH):2022-01-01 ~ 2022-12-31

海南机场(600515.SH):2023-01-01 ~ 2023-12-31

The Scientific Approach to Trading Strategy Development


  • Conceptualize and formulate the trading strategy
  • Specify the trading rules in a definitive, objective, and computer-testable form
  • Do a preliminary form of testing of the trading strategy
  • Optimize the trading strategy, which means arrive at the formulation of the strategy that features the most robust and highest level of risk-adjusted returns
  • Evaluate the robustness of the trading strategy and its ability to produce real-time trading profits with the Walk-Forward Analysis method
  • Trade the strategy in real time
  • Monitor the trading performance and make sure it agrees with the performance exhibited during historical simulation
  • Improve and refine the trading strategy

Early Performance Measures Techniques

  • Two Desirable Attributes

    • The ability to derive above-average returns for a given risk class. The superior risk-adjusted returns can be derived from either

      • Superior timing
      • Superior security selection
    • The ability to diversify the portfolio completely to eliminate

      • A completely diversified portfolio is perfectly correlated with the fully diversified benchmark portfolio
  • Portfolio Evaluation before 1960

    • Evaluate portfolio performance almost entirely on the basis of the rate of return
    • Rate of return within risk classes, but don’t know how to measure it and could not consider it explicitly
  • Peer Group Comparisons

    • Collects the returns produced by a representative universe of investors over a specific period of time
    • Potential problems
      • No explicit adjustment for risk
      • Difficult to form comparable peer group

"Modern" Performance Measures Techniques

Components of Investment Performance

  • Fama suggested overall performance, in excess of the risk-free rate, consists of two components:

  • The selectivity component represents the portion of the portfolio's actual return beyond that available to an unmanaged portfolio with identical systematic risk and is used to assess the manager's investment prowess
  • Evaluating Selectivity

    • : the actual return on the portfolio being evaluated
    • : the return on the combination of the riskless asset and the market portfolio that has risk equal to

Evaluateing Diversification

  • The gross selectivity component can be broken into two parts
    • Net selectivity
    • Diversification

  • : the return on the combination of the riskless asset and the market portfolio that has return volatility equivalent to that of the portfolio being evaluated

Performance Measurement with Downside Risk

  • The Sortino measure is a risk-adjusted measure that differs from the Sharpe ratio in two ways
    • It measures the portfolio's average return in excess of a user-selected minimum acceptable return threshold
    • It captures just the downside risk (DR) in the portfolio rather than the total risk as in Sharpe measure
  • The Form

    • : the minimum acceptable return threshold
    • : the downside risk coefficient for Portfolio

Factors That Affect Use of Performance Measures

  • Market Portfolio Is Difficult to Approximate
    • Benchmark Portfolios

      • Performance evaluation standard
      • Usually a passive index or portfolio
      • May need benchmark for entire portfolio and separate benchmarks for segments to evaluate individual managers
    • Benchmark Error

      • Can effect slope of SML
      • Can effect calculation of beta
      • Greater concern with global investing
      • Problem is one of measurement
  • Implications of the Benchmark Problems
    • Benchmark problems do not negate the value of the CAPM as a normative model of equilibrium pricing
    • There is a need to find a better proxy for the market portfolio or to adjust measured performance for benchmark errors
    • Multiple markets index (MMI) is major step toward a truly comprehensive world market portfolio
  • Required Characteristics of Benchmarks

    • Unambiguous
    • Investable
    • Measurable
    • Appropriate
    • Reflective of current investment opinions
    • Specified in advance
  • Selecting a Benchmark

    • A global level that contains the broadest mix of risky asset available from around the world
    • A fairly specific level consistent with the management style of an individual money manager

Software

Why I recommend Excel+VBA and Python?

  • Excel+VBA

    • simple and powerful
    • good performance for dataset with moderate size
    • every company has office suit installed on their desktops
  • Python: Life is short, you need Python!

    • best programming language for bigdata analytics
    • glue coding language
    • large and comprehensive standard library
    • smooth learning curve
    • highly readable and easy to code

Platform

  • Online Platforms
  • Professional Quantitative Trading Servaces

  • Build your own trading system

Tushare

Tushare是一个免费、开源的python财经数据接口包。主要实现对股票等金融数据从数据采集、清洗加工 到 数据存储的过程,能够为金融分析人员提供快速、整洁、和多样的便于分析的数据,为他们在数据获取方面极大地减轻工作量,使他们更加专注于策略和模型的研究与实现上。考虑到Python pandas包在金融量化分析中体现出的优势,Tushare返回的绝大部分的数据格式都是pandas DataFrame类型,非常便于用pandas/NumPy/Matplotlib进行数据分析和可视化。

VNPY

  • 丰富的Python交易和数据API接口,基本覆盖了国内外常规交易品种(证券、期货、期权、外汇、CFD):
    • CTP(vn.ctp):期货、期货期权
    • 飞创(vn.xspeed):期货、期货期权
    • 飞马(vn.femas):中金所的期货和期货期权
    • 金仕达期权(vn.ksotp):期货、期货期权、证券期权
    • 金仕达黄金(vn.ksgold):金交所贵金属
    • 飞鼠(vn.sgit):期货、金交所贵金属
    • QDP极速柜台(vn.qdp):期货、期货期权、金交所贵金属
    • OANDA(vn.oanda):外汇、CFD
    • Interactive Brokers(vn.ib):外盘股票、期货、期权、外汇等
    • 直达期货(vn.shzd):外盘期货
    • OKCoin(vn.okcoin):比特币、莱特币等
    • 通联数据(vn.datayes):历史行情数据、基本面数据
  • 事件驱动引擎(vn.event),用于实现Python在全局锁(GIL)限制下的高性能事件驱动编程
  • 开发示例(vn.demo),通过简洁明了的代码展示如何使用API和事件驱动引擎开发交易程序
  • 交易平台(vn.trader),整合了vn.py项目中所有的交易接口以及Interactive Brokers的三方接口(IbPy),围绕事件驱动引擎设计了针对策略算法和交易应用开发的上层API,使得交易员可以专注于解决交易业务需求而无需关注底层细节,平台中提供了一套完整的CTA策略模块(回测和实盘)作为开发参考
  • RPC模块(vn.rpc),提供跨进程服务调用的RPC模块,同时支持服务端向客户端的主动数据推送,用于实现vn.py框架下模块的多进程解耦

金融工程的应用:风险管理

Market Risk

Value-at-Risk (VaR)

  • VaR is the maximum loss over a target horizon such that there is a low, prespecified probability that actual loss will be larger.
  • Formula

or,

Components of a Multivariate Risk Modeling Systems


  • Risk system

    • portofolio position system
    • risk factor modeling system
    • aggregation system
  • Describe joint movements in the risk factors

    • specify an analytical distribution
    • take the joint distribution from empirical observations
  • Aggregation: VaR methods

    • delta-normal method
    • historical simulation method
    • Monte Carlo simulation method

Risk Mapping

Introduction

  • Have assumed so far that each position has its own risk factor, which we model directly

    • Distinguish between positions and risk factors
  • However, it is not always possible or desirable to model each position as having its own risk factor

  • Might wish to map our positions onto some smaller set of risk factors

    • Might wish to map positions to () risk factors

Reasons for mapping

  • Might not have enough data on our positions

    • E.g., might have small runs of Emerging Market data
    • Map to risk factors for which we do have data
  • Might wish to cut down on the dimensionality of our covariance matrices

    • This is important!
    • With positions, covariance matrix has terms
    • As rises, covariance matrix becomes more unwieldy
  • Need to keep dimensionality down to avoid computational problems too – rank problems, etc.

Stages of mapping

  • Construct a set of benchmark instruments or factors

    • Might include key bonds, equities, etc.
  • Collect data on their volatilities and correlations

  • Derive synthetic substitutes for our positions, in terms of these benchmarks

    • This substitution is the actual mapping
  • Construct VaR/CVaR of mapped porfolio

  • Take this as a measure of the VaR/CVaR of actual portfolio

Selecting Core Instruments

  • Usual approach to select key core instruments

    • Key equity indices, key zero bonds, key currencies, etc.
  • Want to have a rich enough set of these proxies, but don’t want so many that we run into covariance matrix problems

  • RiskMetrics core instruments

    • Equity positions represented by equivalent amounts in key equity indices
    • Fixed income positions by represented by combinations of cashflows of a limited number of maturities
    • FX positions represented by relevant amounts in `core' currenicies
    • Commodity positions represented by amounts of selected standardised futures positions

Mapping with Principal Components

  • Can use PCA to identify key factors

  • Small number of PCs will explain most movement in our data set

  • PCA can cut down dramatically on dimensionality of our problem, and cut down on number of covariance terms

    • E.g., with 50 original variables, have separate covariance terms
    • With 3 PCs, have only 3 separate covariance terms

Mapping Positions to Risk Factors

  • Most positions can be decomposed into primitive building blocks

  • Instead of trying to map each type of position, we can map in terms of portfolios of building blocks

  • Building blocks are

    • Basic FX
    • Basic equity
    • Basic fixed-income
    • Basic commodity

A General Example of Risk Mapping

  • Replace each if the positions with a exposure on the risk factors. Define as the exposure of instruments to risk factor
  • Aggregate the exposures across the positions in the portfolio,
  • Derive the distribution of the portfolio return from the exposures and movements in risk factors, , using one of the three VaR methods

Example: Mapping with Factor Models

  • Decompose stock return

    • a constant term (not important fot risk management purpose)
    • a component due to the market
    • a residual term
  • The portfolio return

    • Mean:
    • Variance:
    • For equally weighted portfolio:
    • The mapping: on stock on index
  • This approach is useful especially when there is no return history

Example: Mapping with Fixed-Income Portfolios

  • Risk-free bond portfolio

    • maturity mapping: replace the current value of each bond by a position on a risk factor with the same maturity

    • duration mapping: maps the bond on a zero-coupon risk factor with a maturity equal to the duration of the bond

    • cash flow mapping: maps the current value of each bond payment on a zero-coupon risk factor with maturity equal to the time to wait for each cash flow

Corporate bond portfolio

  • Decomposition:
  • the movement in the value of bond price :

  • the portfolio:
  • aggregation:

  • Variance:
  • on bond on on

Choice of Risk Factors

It should be driven by the nature of the portfolio:

  • portfolio of stocks that have many small positions well dispersed across sectors

  • portfolios with a small number of stocks concentrated in one sector

  • an equity market-neutral portfolio

Mapping Complex Positions

  • Complex positions are handled by apply financial engineering theory
  • Reverse-engineer complex positions into portfolios of simple positions
  • Map complex positions in terms of collections of synthetic simple positions
  • Some examples, using FE/FI theory:
    • Coupon-paying bonds: can regard as portfolios of zeros
    • FRAs: equivalent to spreads in zeros of different maturities
    • FRNs: equivalent to a zero with maturity equal to period to next coupon payment (because it reprices at par)
    • Vanilla IR swaps: equivalent to portfolio long a fixed-coupon bond and short a FRN
    • Structured notes: equivalent to combinations of IR swaps and conventional FRNs
    • FX forwards: equivalent to spread between foreign currency bond and domestic currency bond
    • Commodity, equity and FX swaps: combinations of spread between forward/futures and bond position

Dealing with Optionality

  • All these positions can be mapped with linear based mapping systems because of their being (close to) linear

  • These approaches not so good with optionality

    • Non-linearity of options positions can lead to major errors in mapping
  • With non-linearity, need to resort to more sophisticated methods, e.g., delta-gamma and duration-convexity

Credit Risk

Measuring Default Risk from Market Prices

Spreads and Default Risk: Single Period

Suppose a bond has a single payment $100 in one period, the market-determined yield can be derived from its price

We apply risk-neutral pricing:

Spreads and Default Risk: Multiple Periods

We compound interest rates and default rates over each period.Let be the average annual default rate.

If we use the cumulative default probability

A very rough approximation:

Risk Premium

In the previous analysis we assume risk neutrality. As a result, is a risk neutral measure, which is not necessarily equal to the objective, physical probability of default.

Assuming and be the physical probability of default and the discount rate. We have the following

The risk premium () must be tied to some meaure of bond riskiness as well as investor risk aversion. In addition, this premium may incorporate a **liquidity premium and tax effects.

The Merton Model

  • The Merton (1974) model views equity as akin to a call option on the assets of the firm, with an exercise price given by the face value of debt

  • Consider a firm with total value that has one bond due in one period with face value

    • equity can be viewed as a call option on the firm value with strike price equal to the face value of debt

    • the current stock price embodies a forecast of default probability in the same way that an option embodies a forecast of being exercised
    • corporate debt can be viewed as risk-free debt minus a put option on the firm value

Pricing Equity and Debt

Firm value follows the geometric Brownian motion

The value of firm can be decompose in to the value of equity () and the value of debt (). The corporate bond price is obtained as

The equity value is

Stock Valuation

where

Firm Volatility

Bond Valuation

Risk-Neutral Dynamics of Default

Pricing Credit Risk

Credit Option Valuation

Applying the Merton Model

  • the KMV approach: the company sells expected default frequencies (EDFs) for global firms

  • Advantages

    • it relies on the price of equities, which are more actively traded than bonds
    • correlations between equity prices can generate correlations between bonds
    • it generates movements in EDFs that seems to lead changes in credit ratings
  • Disadvantages

    • it can not be used to price sovereign credit risk
    • it relies on a static model of the firm's capital and risk structure
    • management could undertake new projects that increases not only the value if equity but also its volatility
    • the model fails to explain the magnitude of credit spreads we observe on credit-sensitive bonds

金融工程的应用:实物期权

An Alternative to the NPV Rule for Capital Investments


  • Define stochastic processes for the key underlying variables and use risk-neutral valuation

  • This approach (known as the real options approach) is likely to do a better job at valuing growth options, abandonment options, etc than NPV

The Problem with using NPV to Value Options


  • Consider the example from Chapter 13: risk-free rate =4%; strike price = $21
  • Suppose that the expected return required by investors in the real world on the stock is 16%. What discount rate should we use to value an option with strike price $21?

Correct Discount Rates are Counter-Intuitive


  • Correct discount rate for a call option is 42.6%

    • , , , if required expected return is
  • Correct discount rate for a put option is –52.5%

General Approach to Valuation

  • Assuming

    • The market price of risk for a variable is

    • Suppose that a real asset depends on several variables . Let and be the expected growth rate and volatility of so that

  • We can value any asset dependent on a variable by

    • Reducing the expected growth rate of by where is the market price of -risk and is the volatility of
    • Assuming that all investors are risk-neutral

Example (36.1)


The cost of renting commercial real estate in a certain city is quoted as the amount that would be paid per square foot per year in a new 5-year rental agreement. The current cost is $30 per square foot. The expected growth rate of the cost is 12% per annum, the volatility of the cost is 20% per annum, and its market price of risk is 0.3. A company has the opportunity to pay $1 million now for the option to rent 100,000 square feet at $35 per square foot for a 5-year period starting in 2 years. The risk-free rate is 5% per annum (assumed constant).

How to evaluate the option?

Example (36.1)


Define as the quoted cost per square foot of office space in 2 years. Assume that rent is paid annually in advance. The payoff from the option is

where is an annuity factor given by

The expected payoff in a risk-neutral world is therefore

According to the Black-Scholes formula, the value of the option is

where

and

The expected growth rate in the cost of commercial real estate in a risk-neutral world is , where is the real-world growth rate, is the volatility, and is the market price of risk. In this case, , , and , so that the expected risk-neutral growth rate is 0.06, or 6%, per year. It follows that . Substituting this in the expression above gives the expected payoff in a risk-neutral world as $1.5015 million. Discounting at the risk-free rate the value of the option is million.

This shows that it is worth paying $1 million for the option.

Extension to Many Underlying Variables

  • When there are several underlying variables qi we reduce the growth rate of each one by its market price of risk times its volatility and then behave as though the world is risk-neutral

  • Note that the variables do not have to be prices of traded securities

Estimating the Market Price of Risk


  • Contimuous CAPM:

  • According to the previous slides:

  • The market price of risk:

Types of Options


  • Abandonment

  • Expansion

  • Contraction

  • Option to defer

  • Option to extend life

Example (page 795)


  • A company has to decide whether to invest $15 million to obtain 6 million units of a commodity at the - rate of 2 million units per year for three years.
  • The fixed operating costs are $6 million per year and the variable costs are $17 per unit.
  • The spot price of the commodity is $20 per unit and 1, 2, and 3-year futures prices are $22, $23, and $24, respectively.
  • The risk-free rate is 10% per annum for all maturities.

The Process for the Commodity Price


  • We assume that this is

where and

  • We build a tree as in Chapter 32 (Interest Rate Tree) and Chapter 35 (Energy and Commodity Derivatives)

Estimating the Market Price of Risk Using CAPM (equation 36.2, page 792)

Node A B C D E F G H I
0.1667 0.1217 0.1667 0.2217 0.8867 0.1217 0.1667 0.2217 0.0867
0.6666 0.6566 0.6666 0.6566 0.0266 0.6566 0.6666 0.6566 0.0266
0.1667 0.2217 0.1667 0.1217 0.0867 0.2217 0.1667 0.1217 0.8867

Valuation of Base Project; Fig 36.2

Node A B C D E F G H I
0.1667 0.1217 0.1667 0.2217 0.8867 0.1217 0.1667 0.2217 0.0867
0.6666 0.6566 0.6666 0.6566 0.0266 0.6566 0.6666 0.6566 0.0266
0.1667 0.2217 0.1667 0.1217 0.0867 0.2217 0.1667 0.1217 0.8867

Valuation of Option to Abandon; Fig 36.3(No Salvage Value; No Further Payments)

Node A B C D E F G H I
0.1667 0.1217 0.1667 0.2217 0.8867 0.1217 0.1667 0.2217 0.0867
0.6666 0.6566 0.6666 0.6566 0.0266 0.6566 0.6666 0.6566 0.0266
0.1667 0.2217 0.1667 0.1217 0.0867 0.2217 0.1667 0.1217 0.8867

Value of Expansion Option; Fig 36.4 (Company Can Increase Scale of Project by 20% for $2 million)

Node A B C D E F G H I
0.1667 0.1217 0.1667 0.2217 0.8867 0.1217 0.1667 0.2217 0.0867
0.6666 0.6566 0.6666 0.6566 0.0266 0.6566 0.6666 0.6566 0.0266
0.1667 0.2217 0.1667 0.1217 0.0867 0.2217 0.1667 0.1217 0.8867

Appendix: Interest Rate Tree

Interest Rate Trees vs Stock Price Trees

  • The variable at each node in an interest rate tree is the -period rate

  • Interest rate trees work similarly to stock price trees except that the discount rate used varies from node to node

Two-Step Tree Example

Payoff after 2 years is , ; ; ; Time step=1yr

B:

A:

Alternative Branching Processes in a Trinomial Tree

Procedure for Building Tree

  • [1] Assume and
  • [2] Draw a trinomial tree for to match the mean and standard deviation of the process for
  • [3] Determine one step at a time so that the tree matches the initial term structure

Example

Suppose that , , and . The zero-rate curve is given below.

Maturity Zero Rate
0.5 3.430
1.0 3.824
1.5 4.183
2.0 4.512
2.5 4.812
3.0 5.086

Building the First Tree for the rate

  • Set vertical spacing:

  • Change branching when nodes from middle where is smallest integer greater than

  • Choose probabilities on branches so that mean change in is and S.D. of change is

The First Tree

Shifting Notes

  • Work forward through tree

  • Remember the value of a derivative providing a $1 payoff at node at time

  • Shift nodes at time by so that the bond is correctly priced

The Final Tree

Formulas for 's and 's

To express the approach more formally, suppose that the have been determined for . The next step is to determine so that the tree correctly prices a zero-coupon bond maturing at . The interest rate at node is ,so that the price of a zero-coupon bond maturing at time is given by

where is the number of nodes on each side of the central node at time .

The solution to this equation is

Once has been determined, the for can be calculated using

where is the probability of moving from node to node and the summation is taken over all values of for which this is nonzero.