我想知道为什么下面的代码不起作用?事实上,我希望获得 SP500 的滚动年度风险度量。首先,我从雅虎财经导入数据。我选择了收盘价并取了每个月的最后收盘价。然后我想要返回每个日期的 36 个关闭月份。与风险指标相同。
import pandas as pd
import numpy as np
import yfinance as yf
SP500=yf.download("SPY", start = "2020-01-01", end = "2020-12-01")
close = SP500.loc[:, "Close"].copy()
month_ret = close.resample("M", kind = "period").last().pct_change().dropna()
month_ret["Return"] = month_ret.rolling(36).mean()*12
month_ret["Risk"] = month_ret.rolling(36).std()*np.sqrt(12)
month_ret.tail()
I've got the following message:
ValueError Traceback (most recent call last)
~\Anaconda3\lib\site-packages\pandas\core\window.py in _prep_values(self, values)
231 try:
--> 232 values = ensure_float64(values)
233 except (ValueError, TypeError):
pandas\_libs\algos_common_helper.pxi in pandas._libs.algos.ensure_float64()
ValueError: setting an array element with a sequence.
During handling of the above exception, another exception occurred:
TypeError Traceback (most recent call last)
~\Anaconda3\lib\site-packages\pandas\core\window.py in _apply(self, func, name, window, center, check_minp, **kwargs)
911 try:
--> 912 values = self._prep_values(b.values)
913
~\Anaconda3\lib\site-packages\pandas\core\window.py in _prep_values(self, values)
234 raise TypeError(
--> 235 "cannot handle this type -> {0}" "".format(values.dtype)
236 )
TypeError: cannot handle this type -> object
During handling of the above exception, another exception occurred:
DataError Traceback (most recent call last)
<ipython-input-18-6480c4316ca2> in <module>
----> 1 month_ret["Risk"] = month_ret.rolling(36).std()*np.sqrt(12)
~\Anaconda3\lib\site-packages\pandas\core\window.py in std(self, ddof, *args, **kwargs)
1886 def std(self, ddof=1, *args, **kwargs):
1887 nv.validate_rolling_func("std", args, kwargs)
-> 1888 return super().std(ddof=ddof, **kwargs)
1889
1890 @Substitution(name="rolling")
~\Anaconda3\lib\site-packages\pandas\core\window.py in std(self, ddof, *args, **kwargs)
1292
1293 return self._apply(
-> 1294 f, "std", check_minp=_require_min_periods(1), ddof=ddof, **kwargs
1295 )
1296
~\Anaconda3\lib\site-packages\pandas\core\window.py in _apply(self, func, name, window, center, check_minp, **kwargs)
918 continue
919 else:
--> 920 raise DataError("No numeric types to aggregate")
921
922 if values.size == 0:
DataError: No numeric types to aggregate