【问题标题】:Iterator operand 0 dtype could not be cast from dtype('<M8[us]') to dtype('<M8[D]') according to the rule 'safe'根据规则“安全”,迭代器操作数 0 dtype 无法从 dtype('<M8[us]') 转换为 dtype('<M8[D]')
【发布时间】:2020-11-23 05:19:59
【问题描述】:

我正在尝试通过编写代码来形成 Black-Scholes 模型,但发生了错误。

from scipy import stats
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

def time_to_maturity(t0, T, y=252):
    t0 = pd.to_datetime(t0)
    T = pd.to_datetime(T)
    return ( np.busday_count(t0, T) / y )

time_to_maturity('2018-08-01', '2018-12-14')


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-20-c71b621d9d71> in <module>
     10     return ( np.busday_count(t0, T) / y )
     11 
---> 12 time_to_maturity('2018-08-01', '2018-12-14')

<ipython-input-20-c71b621d9d71> in time_to_maturity(t0, T, y)
      8     t0 = pd.to_datetime(t0)
      9     T = pd.to_datetime(T)
---> 10     return ( np.busday_count(t0, T) / y )
     11 
     12 time_to_maturity('2018-08-01', '2018-12-14')

<__array_function__ internals> in busday_count(*args, **kwargs)

**TypeError: Iterator operand 0 dtype could not be cast from dtype('<M8[us]') to dtype('<M8[D]') according to the rule 'safe'**

我不明白问题出在哪里。我该如何解决这个问题?

【问题讨论】:

  • 我认为问题与“日期时间”格式有关...

标签: python pandas numpy matplotlib


【解决方案1】:

查了一下,发现np.busday_count()的参数需要是datetime64格式。所以我用np.datetime64()来转换。

from scipy import stats
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

def time_to_maturity(t0, T, y=252):
    t0 = np.datetime64(t0)
    T = np.datetime64(T)
    return ( np.busday_count(t0, T) / y )

time_to_maturity('2018-08-01', '2018-12-14')
0.38492063492063494

【讨论】:

  • 是因为np和pd的日期时间格式不同吗?
  • 在 pandas 中它是时间戳格式,所以我检查并发现需要 'datetime64' 格式。来自here
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-11
  • 1970-01-01
  • 2019-02-26
  • 2018-08-15
  • 1970-01-01
相关资源
最近更新 更多