Python 根据规则';无法将迭代器操作数0数据类型从数据类型(';<;M8[us]';)转换为数据类型(';<;M8[D]';);安全';

Python 根据规则';无法将迭代器操作数0数据类型从数据类型(';<;M8[us]';)转换为数据类型(';<;M8[D]';);安全';,python,pandas,numpy,matplotlib,Python,Pandas,Numpy,Matplotlib,我试图通过编写代码来建立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

我试图通过编写代码来建立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'**
来自scipy导入统计信息
将numpy作为np导入
作为pd进口熊猫
将matplotlib.pyplot作为plt导入
%matplotlib内联
定义到期时间(t0,T,y=252):
t0=pd.to_日期时间(t0)
T=pd.to_日期时间(T)
返回(np.每日计数(t0,T)/y)
到期时间(“2018-08-01”、“2018-12-14”)
---------------------------------------------------------------------------
TypeError回溯(最近一次调用上次)
在里面
10返回(np.busday_计数(t0,T)/y)
11
--->12到期时间(“2018-08-01”、“2018-12-14”)
及时到期(t0,T,y)
8 t0=pd.to_日期时间(t0)
9 T=pd.to_日期时间(T)
--->10返回(np.busday_计数(t0,T)/y)
11
12到期时间(“2018-08-01”、“2018-12-14”)
公共汽车日计数(*args,**kwargs)

**TypeError:迭代器操作数0 dtype无法从dtype强制转换(“检查时,我发现
np.busday\u 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

我认为问题与“datetime”格式有关……这是因为np和pd的datetime格式不同吗?在pandas中,它是时间戳格式,因此我检查并发现需要“datetime64”格式。从