首页 > 解决方案 > 为什么我不能使用 month_ret.rolling(36).std()*np.sqrt(12) ?(蟒蛇金融)

问题描述

我想知道为什么下面的代码不起作用?事实上,我希望获得 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

标签: pythonstdfinanceyfinance

解决方案


产生错误的原因有两个,二是return列中没有指定风险值的计算,导致计算中包含了NaN值的错误。由于我不熟悉投资,以下代码是否符合您的问题的意图?

import pandas as pd
import numpy as np
import yfinance as yf

SP500=yf.download("SPY", start = "2015-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.fillna(0, inplace=True)
month_ret["Risk"] = month_ret['Return'].rolling(36).std()*np.sqrt(12)

month_ret.tail(37)
Close   Return  Risk
Date            
2017-11     0.030566    0.000000    NaN
2017-12     0.006981    0.092355    0.053321
2018-01     0.056359    0.121018    0.086672
2018-02     -0.036360   0.090163    0.099274
2018-03     -0.031290   0.086426    0.108837
2018-04     0.005168    0.084871    0.116688
2018-05     0.024309    0.088689    0.124241
2018-06     0.001255    0.097458    0.132499
2018-07     0.037047    0.102278    0.140553
2018-08     0.031920    0.133234    0.154062
2018-09     0.001412    0.143890    0.167868
2018-10     -0.069104   0.092502    0.170876
2018-11     0.018549    0.097467    0.173960
2018-12     -0.093343   0.074052    0.174226
2019-01     0.080066    0.117336    0.178965
2019-02     0.032416    0.128416    0.184521
2019-03     0.013636    0.112365    0.186919
2019-04     0.040852    0.124669    0.190188
2019-05     -0.063771   0.097741    0.189812
2019-06     0.064410    0.119783    0.191078
2019-07     0.015119    0.112665    0.190892
2019-08     -0.016743   0.106685    0.189555
2019-09     0.014772    0.113265    0.188173
2019-10     0.022105    0.126412    0.187371
2019-11     0.036198    0.126199    0.185726
2019-12     0.024021    0.129441    0.183558
2020-01     -0.000404   0.123342    0.179933
2020-02     -0.079166   0.083856    0.173722
2020-03     -0.129987   0.041556    0.168637
2020-04     0.126984    0.080575    0.161391
2020-05     0.047645    0.091753    0.153379
2020-06     0.013275    0.095681    0.144406
2020-07     0.058892    0.108460    0.134495
2020-08     0.069797    0.130753    0.124329
2020-09     -0.041281   0.111955    0.110565
2020-10     -0.024934   0.095790    0.093477
2020-11     0.108777    0.121860    0.071686

推荐阅读