金融計算程式運用(二)

課程資訊

教科書
Daniel J. Duffy, Financial Instrument Pricing Using C++ (2nd Edition), Wiley Finance

補充教材

  • QuantLib C++ 1.43 原始碼與官方文件
  • 教師自編 Modern C++ 補充教材
  • QuantLib 金融工程實務案例
  • 金融商品評價與風險管理程式範例

一、課程介紹

本學期課程以 Modern C++ 與金融工程(Computational Finance) 為核心, 從現代 C++ 程式語言出發,逐步進入數值方法、金融商品評價,以及金融軟體系統設計。

本課程並不是單純學習 C++ 語法,也不是單純學習金融數學。

我們真正要處理的核心問題是:

如何將一個金融模型,轉換成可靠、可維護、可擴充,而且具有效率的 C++ 金融工程程式?

因此,本學期將同時處理四個彼此連結的層次:

\[ \text{Financial Model} \]

\[ \downarrow \]

\[ \text{Numerical Algorithm} \]

\[ \downarrow \]

\[ \text{Modern C++ Software Design} \]

\[ \downarrow \]

\[ \text{QuantLib Implementation} \]

亦即:

金融模型 → 數值方法 → C++ 程式設計 → QuantLib 金融工程實務

本課程希望建立的是一條完整的金融計算程式學習路徑,而不是彼此獨立的程式語法與金融公式。


二、課程目標

完成本課程後,希望同學能夠:

  1. 掌握 Modern C++(C++11/14/17) 的核心程式設計技巧。
  2. 理解 C++ 的物件導向、泛型與函數式程式設計方法。
  3. 掌握 Smart Pointer、RAII、Move Semantics 等現代資源管理技術。
  4. 熟悉 Template、Tuple、Type Traits、Lambda 與 STL Algorithms。
  5. 將金融模型轉換成可以實際執行的數值演算法。
  6. 理解 Lattice、Monte Carlo 與其他金融計算方法。
  7. 理解金融軟體中的 abstraction、modularity 與 Design Pattern。
  8. 閱讀並理解 QuantLib 的核心程式架構。
  9. 使用 QuantLib 建立基本的金融商品評價與風險計算程式。
  10. 期末完成一個小型金融商品評價或風險管理系統。

三、本學期的核心思維

本學期不把 C++ 僅僅視為:

「一個執行速度比較快的程式語言」

C++ 在金融工程中的價值還包括:

  • deterministic destruction
  • RAII(Resource Acquisition Is Initialization)
  • value semantics
  • move semantics
  • zero-cost abstractions
  • templates
  • generic programming
  • compile-time type checking
  • STL algorithms
  • static polymorphism
  • dynamic polymorphism
  • predictable resource management

因此,我們會特別討論:

如何依照問題的特性,選擇適合的 programming paradigm。

Modern C++ 並不是只有 Object-Oriented Programming。

C++ 是一個 Multiparadigm Programming Language,可以同時支援:

  • Procedural Programming
  • Object-Oriented Programming
  • Generic Programming
  • Functional Programming

在實際金融工程系統中,通常必須將這些方法適當組合,而不是完全依賴 class hierarchy。


四、課程模組

第一單元:Modern C++ 基礎與資源管理

主要內容

  • C++ 作為 Multiparadigm Programming Language
  • RAII
  • Smart Pointer
    • std::unique_ptr
    • std::shared_ptr
    • std::weak_ptr
  • Ownership
  • Object Lifetime
  • Move Semantics
  • Rvalue References
  • Value Categories
  • auto
  • nullptr
  • Range-based for
  • Scoped Enumeration
  • std::variant

核心問題

如何避免:

  • memory leak
  • dangling pointer
  • double delete
  • unclear ownership
  • unnecessary copy

對應教科書

  • Chapter 1 — A Tour of C++ and Environs
  • Chapter 2 — New and Improved C++ Fundamentals

QuantLib 連結

觀察 QuantLib 中:

  • object ownership
  • shared objects
  • pricing engine
  • instrument lifecycle

第二單元:函數、Lambda 與 Functional Programming

主要內容

  • Function as an abstraction
  • Functional Programming 基礎
  • Callable Objects
  • Function Objects
  • std::function
  • Lambda Expressions
  • Lambda Capture
  • Function Closure
  • Partial Function Application
  • std::bind
  • Generic Lambda

核心問題

傳統 C++ 常利用:

inheritance
virtual functions
function pointers

來達成軟體彈性。

Modern C++ 則可以進一步利用:

std::function
lambda
template

建立更容易組合、低耦合的軟體架構。

對應教科書

  • Chapter 3 — Modelling Functions in C++
  • Chapter 6 — Generic Lambdas

QuantLib 連結

討論:

  • Strategy Pattern
  • Callback
  • Pricing Algorithm
  • Model / Engine Separation

第三單元:模板與泛型程式設計

主要內容

  • Function Template
  • Class Template
  • Template Specialization
  • Variadic Template
  • decltype
  • std::declval
  • SFINAE
  • std::enable_if
  • Type Traits
  • Generic Lambda
  • Compile-Time Type Information

核心觀念

Generic Programming 的目的並不只是減少重複程式碼。

它也提供:

  • 編譯期型別資訊
  • static polymorphism
  • 更強的 type safety
  • compiler optimization 的可能性
  • reusable numerical algorithms

但 template 並不自動代表程式一定比較快。

仍然必須考量:

  • algorithm
  • compiler optimization
  • data layout
  • memory access
  • code bloat
  • compilation time

對應教科書

  • Chapter 4 — Advanced C++ Template Programming
  • Chapter 6 — Type Traits, Advanced Lambdas and Multiparadigm Design in C++

第四單元:Tuple、STL 與金融資料結構

主要內容

  • std::pair
  • std::tuple
  • Multiple Return Values
  • Structured Data
  • STL Containers
  • STL Iterators
  • STL Algorithms
  • Functional-style Data Processing

金融應用

例如,一個 Option Pricing Function 可以同時計算:

Price
Delta
Gamma

在 C++ 中可利用 std::tuple 將這些結果整合:

using ComputedData =
    std::tuple<double, double, double>;

而不必為 Price、Delta 與 Gamma 建立彼此獨立的資料交換方式。

對應教科書

  • Chapter 5 — Tuples in C++ and their Applications
  • Chapter 17 — STL Algorithms in Detail
  • Chapter 18 — STL Algorithms Part II

五、金融模型與數值方法

5.1 Black–Scholes 與 Greeks

Black–Scholes 將作為本學期的重要示範模型。

除了金融公式本身之外,我們會進一步研究:

  • Model Input
  • Pricing Function
  • Greeks
  • Data Structure
  • Software Architecture
  • Algorithm Interface

因此,我們不只問:

Black–Scholes 的公式是什麼?

還要進一步思考:

Black–Scholes Pricing Engine 應該如何設計?

例如:

Market / Option Data
        ↓
Pricing Algorithm
        ↓
Price + Greeks

5.2 Lattice Models

主要內容:

  • Binomial Tree
  • Trinomial Tree
  • European Option
  • American Option
  • Early Exercise
  • Greeks
  • Convergence

對應教科書

  • Chapter 11 — Lattice Models Fundamental Data Structures and Algorithms
  • Chapter 12 — Lattice Models Applications to Computational Finance

5.3 Random Number Generation

主要內容:

  • Pseudo-Random Number
  • Uniform Distribution
  • Normal Distribution
  • Box–Muller Method
  • Random Number Engine
  • Distribution
  • Seed
  • Reproducibility

對應教科書

  • Chapter 26 — Random Number Generation and Distributions

5.4 Monte Carlo Simulation

Monte Carlo Simulation 為本學期重要的金融數值方法之一。

主要內容:

  • GBM Asset Price Process
  • Path Generation
  • European Option
  • Asian Option
  • Barrier Option
  • Number of Simulations
  • Statistical Error
  • Convergence
  • Performance

對應教科書

  • Chapter 31 — Monte Carlo Simulation, Part I
  • Chapter 32 — Monte Carlo Simulation, Part II

六、C++ Concurrency 與 Monte Carlo 加速

現代 CPU 普遍採用 multicore architecture。

因此,在金融計算中除了演算法正確性之外,也需要進一步考慮平行運算。

主要內容:

  • std::thread
  • Task Decomposition
  • std::async
  • std::future
  • Data Parallelism
  • Task Parallelism

並以 Monte Carlo Simulation 作為重要案例。

核心問題

我們真正要思考的並不是:

如何建立很多 threads?

而是:

一個金融計算問題中,哪些工作可以安全且有效率地 parallelize?

對應教科書

  • Chapter 28 — C++ Concurrency, Part I: Threads
  • Chapter 29 — C++ Concurrency, Part II: Tasks
  • Chapter 32 — Monte Carlo Simulation, Part II

七、金融軟體設計

本課程另一個重要目標,是理解:

數學公式正確,不代表金融軟體就是好的。

金融軟體還必須考量:

  • correctness
  • maintainability
  • extensibility
  • testability
  • reliability
  • performance
  • separation of concerns
  • coupling
  • abstraction

因此我們會討論:

  • Single Responsibility Principle
  • Liskov Substitution Principle
  • Composition
  • Inheritance
  • Dynamic Polymorphism
  • Static Polymorphism
  • Policy-Based Design
  • Multiparadigm Design

對應教科書

  • Chapter 7 — Multiparadigm Design in C++
  • Chapter 9 — An Introduction to Unified Software Design

八、Design Patterns 與 Modern C++

傳統 Gang of Four Design Patterns 主要建立於:

  • class hierarchy
  • inheritance
  • virtual function
  • subtype polymorphism

Modern C++ 提供更多設計工具,例如:

  • template
  • lambda
  • std::function
  • smart pointer
  • generic programming

因此我們會比較傳統與 Modern C++ 的設計方法。

Traditional Object-Oriented Design

        Base Class
          /   \
         /     \
Derived A     Derived B

Modern C++ Design

Interface / Function Signature
              ↓
       Callable Object
              ↓
          Algorithm

並討論下列 Design Patterns:

  • Strategy
  • Factory
  • Observer
  • Bridge
  • Singleton
  • Decorator

我們也會思考:

哪些 Design Pattern 仍然適合直接使用?

以及:

哪些 Design Pattern 可以利用 Modern C++ 重新設計?


九、QuantLib

課程後半段將逐步把前面學習的 C++ 與金融模型帶入 QuantLib。

QuantLib 不只是金融公式的集合。

它同時是一個大型的:

Financial Engineering Software Framework

我們會逐步研究其主要概念,例如:

Instrument
    ↓
PricingEngine
    ↓
Model
    ↓
Market Data

以及:

  • Instrument
  • PricingEngine
  • CashFlow
  • Coupon
  • Bond
  • YieldTermStructure
  • Handle
  • Quote
  • Observer / Observable
  • LazyObject
  • Calendar
  • DayCounter

學習 QuantLib 的重點不只是:

QuantLib::Bond

或:

QuantLib::VanillaOption

怎麼呼叫。

更重要的是理解:

QuantLib 為什麼要這樣設計?


十、QuantLib 金融應用

10.1 固定收益

主要內容:

  • Bond
  • Cash Flow
  • Discount Factor
  • Yield to Maturity
  • Duration
  • Convexity
  • DV01
  • Yield Curve

將前面所學的:

Financial Model
        +
Numerical Method
        +
C++ Architecture

與 QuantLib 的實際實作進行比較。


10.2 選擇權

主要內容:

  • VanillaOption
  • Black–Scholes Model
  • Binomial Engine
  • Monte Carlo Engine
  • Asian Option
  • Barrier Option

核心問題仍然是:

QuantLib 如何把金融模型、數值演算法與軟體架構結合?


十一、課程進度(18 週)

週次 主題 主要閱讀 程式實作
1 課程介紹、Modern C++ 與金融工程 Ch.1 C++ 環境確認、Black–Scholes 初步案例
2 Smart Pointer、RAII、Ownership Ch.2 unique_ptr / shared_ptr
3 Move Semantics 與 Modern C++ Fundamentals Ch.2 Copy vs Move 實驗
4 std::function、Lambda 與 Callable Objects Ch.3 Pricing Function
5 Template 與 decltype Ch.4 Generic Numerical Function
6 Tuple 與 Multiple Return Values Ch.5 Price / Delta / Gamma
7 Type Traits 與 Generic Lambda Ch.6 Compile-Time Type Analysis
8 Multiparadigm Design Ch.7 Strategy Pattern Modernization
9 STL Algorithms 與金融資料 Ch.17–18 STL Financial Data Processing
10 Lattice Models Ch.11–12 Binomial Option Pricing
11 Random Number Generation Ch.26 Normal Random Number Generator
12 Monte Carlo I Ch.31 GBM + European Option
13 Monte Carlo II Ch.31–32 Asian / Barrier Option
14 C++ Concurrency Ch.28–29 thread / async / future
15 QuantLib 基礎架構 補充講義 Instrument / PricingEngine
16 QuantLib 固定收益 補充講義 Bond / Yield / Duration / DV01
17 QuantLib Option 與 Design Pattern 補充講義 VanillaOption / PricingEngine
18 綜合案例與期末專題 綜合 Pricing / Risk System

十二、期末專題

期末專題的目標不是完成一套大型金融系統,而是實際整合:

Financial Model
        ↓
Numerical Method
        ↓
Modern C++
        ↓
Software Architecture
        ↓
Pricing / Risk Result

以下為可能的專題方向。


Project A:Bond Analytics

實作:

  • Bond Price
  • Yield to Maturity
  • Duration
  • Convexity
  • DV01

最後將自行開發的結果與 QuantLib 比較。


Project B:Option Pricing Engine

實作:

  • Black–Scholes
  • Binomial Tree
  • Monte Carlo

並比較不同方法的:

  • accuracy
  • convergence
  • performance

Project C:Monte Carlo Pricing Engine

支援:

  • European Option
  • Asian Option
  • Barrier Option

並利用:

std::thread
std::async
std::future

進行 parallelization。

比較:

  • Single-thread
  • Multi-thread
  • Task-based

三種方法的執行效率。


Project D:QuantLib Extension

選擇一個 QuantLib 模組:

Instrument
PricingEngine
CashFlow
TermStructure
Option
Bond

分析:

  1. 類別架構
  2. Design Pattern
  3. Object Lifecycle
  4. Pricing Flow
  5. Market Data Flow

並嘗試進行小型功能擴充。


十三、本學期課程重點

本學期可以歸納為五個核心主題。

1. Modern C++

不只是學習 C++ 語法,而是理解:

RAII
Smart Pointer
Move Semantics
Lambda
Template
Type Traits
STL

以及這些語言工具背後的設計思想。


2. Computational Finance

理解:

Financial Model
        ↓
Numerical Algorithm
        ↓
Computer Implementation

金融計算不是只有公式。

我們還必須理解:

  • 如何表示金融資料
  • 如何設計 numerical algorithm
  • 如何處理 numerical error
  • 如何測試計算結果
  • 如何改善計算效率

3. Software Design

除了:

「算得出答案」

還要求程式具備:

Correctness
Maintainability
Extensibility
Reliability
Performance

4. QuantLib

不只學習:

QuantLib::Bond
QuantLib::VanillaOption
QuantLib::PricingEngine

如何使用。

更重要的是理解:

QuantLib 如何把金融理論轉換成大型 C++ 金融工程架構?


5. 從數學到金融系統

最終希望建立完整的思考方式:

金融理論
   ↓
數學模型
   ↓
數值方法
   ↓
C++ Algorithm
   ↓
Software Architecture
   ↓
QuantLib
   ↓
Pricing / Risk Management System

十四、學習方法

C++ 是一門需要實際撰寫程式才能真正掌握的語言。

因此,本學期的學習方式將以:

Concept → Code → Experiment → Financial Application

為主要流程。

每一個重要觀念都希望經過:

  1. 理論說明
  2. C++ 程式碼
  3. 編譯與執行
  4. 結果驗證
  5. 金融案例
  6. QuantLib 對照

同學不應只閱讀程式碼,而應實際:

Compile
Run
Modify
Test
Debug
Measure
Compare

才能真正理解 Modern C++ 與金融計算程式。


十五、這門課最重要的一句話

這學期我們不是單純學 C++,也不是單純學金融數學;我們要學的是如何使用 Modern C++,把金融模型真正做成可以工作的金融工程軟體。

因此,本學期真正希望培養的並不是:

「記住多少 C++ 語法」

而是:

面對一個金融問題時,知道如何把 Financial Model、Numerical Method、C++ 與 Software Design 組合成一個可靠的解決方案。