期權定價

VBA中的複數

  • December 2, 2020

嘿,我嘗試在 VBA 中為選項定價。為此,我需要定義特徵函式並對複數進行一些操作。例如我有這個程式碼:

Function cf(u, T, r, q, sigma)
i = WorksheetFunction.Complex(0, 1)
b = r - q - 0.5 * sigma ^ 2
cf = WorksheetFunction.ImExp(T * (i * u * b - 0.5 * u ^ 2 * sigma ^ 2)
End Function

但它不起作用。我知道 WorksheetFunction.Complex(0, 1) 返回字元串,我想知道如何執行此操作以使此程式碼正常工作。也許有一些更好的圖書館?

Excel VBA 中的複數,是隔間程式的巔峰之作。去過也做過!

您引用的函式確實是返回string類型。但是您應該能夠編寫這些功能,例如

Option Explicit
Public Function cf(u As Double, ttm As Double, rf As Double, q As Double, s As Double) As String
   Dim b As Double
   b = rf - q - 0.5 * s ^ 2
   If u = 0 Then
       cf = "1.0"
   Else
       With Application.WorksheetFunction
           cf = .ImExp(.Complex(-0.5 * u ^ 2 * s ^ 2 * ttm, ttm * u * b))
       End With
   End If
End Function

這個函式現在將返回一個字元串類型,但 Excel 仍然可以使用它:

Sub ATest()
   Dim z1 As String, z2 As String, z3 As String
   Dim x1 As Double, x2 As Double
  ' some parameters
   Const ttm As Double = 1#
   Const rf As Double = 0.05
   Const q As Double = 0#
   Const sigma As Double = 0.2
   Const eps As Double = 0.0001
   
   z1 = cf(-eps, ttm, rf, q, sigma)
   z2 = cf(0, ttm, rf, q, sigma)
   z3 = cf(eps, ttm, rf, q, sigma)
   With Application.WorksheetFunction
       x1 = .ImReal(.ImDiv( _
                   .ImSub(z3, z1), _
                   .Complex(0, 2 * eps))) ' first moment estimator
       x2 = .ImReal(.ImDiv( _
                       .ImSum(.ImSub(z1, z2), .ImSub(z3, z2)), _
                       .Complex(-eps * eps, 0))) ' second moment estimator
   End With
   Debug.Print "drift:", Round(CDbl(x1), 6), (rf - 0.5 * sigma ^ 2) * ttm
   Debug.Print "variance:", Round(CDbl(x2) - CDbl(x1) ^ 2, 6), sigma ^ 2 * ttm
End Sub

將導致

drift:         0,03          0,03 
variance:      0,04          0,04 

即回報預期。

如果您想要另一種實現,pfadintegral提供了一個(我從未檢查過它)。當然,另一種方法是在 VBA 中編寫自己的庫(正如​​我所說,去過那裡,做到了!),但我認為這可能不值得考慮,因為有很多角落情況需要考慮,例如分支切割、數字下溢等…

HTH?

引用自:https://quant.stackexchange.com/questions/59704