Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫中每行的滚动计算_Python_Pandas - Fatal编程技术网

Python 熊猫中每行的滚动计算

Python 熊猫中每行的滚动计算,python,pandas,Python,Pandas,我尝试对数据帧的每一行执行以下测试和计算: 将过去10年的每日std作为长期波动率(L_vol) 将上个月的每日性病记录作为vol_hat查找 如果上个月的每日std在上五分位或下五分位,则将指示器(状态或st)值变为1,否则为0 将上述项目放入此公式中,以调整回报率: 缩放比例=拉伸最小值(1-st)* 我可以在每行上执行所有这些操作的唯一方法是通过以下循环 # creat a function to see if we are in extreme state volatility

我尝试对数据帧的每一行执行以下测试和计算:

  • 将过去10年的每日std作为长期波动率(L_vol)
  • 将上个月的每日性病记录作为vol_hat查找
  • 如果上个月的每日std在上五分位或下五分位,则将指示器(状态或st)值变为1,否则为0
  • 将上述项目放入此公式中,以调整回报率: 缩放比例=拉伸最小值(1-st)*
  • 我可以在每行上执行所有这些操作的唯一方法是通过以下循环

        # creat a function to see if we are in extreme state volatility
        def state(series):
           result=0
           last_vol = series[-21:].std()
           rolling_vol = series.rolling(21).std()
           if (last_vol <= rolling_vol.quantile(0.2)) or (last_vol >= rolling_vol.quantile(0.8)):
                result = 1
           return result
    
        # create 4 columns based on data from each day's observation
        df_spy['state'] = 0
        df_spy['L_vol'] = 0
        df_spy['sc_ret'] = 0
        df_spy['vol_hat'] =0
        for i in range(2500,len(spy)):
            ret = df_spy['spy'].iloc[i]
            serie = df_spy['spy'].iloc[:i]
            vol_hat = serie[-21:].std()
            df_spy['state'].iloc[i] = state(serie)
            df_spy['vol_hat'].iloc[i] = vol_hat
            df_spy['L_vol'].iloc[i] = df_spy['spy'].iloc[:i][-2500:].std()
            st = df_spy['state'].iloc[i]
            lv = df_spy['L_vol'].iloc[i]
            df_spy['sc_ret'].iloc[i] = (st*ret*min(lv/(vol_hat),2)) + (1-st)*ret
    
    df_spy
    
    Date    
    1980-01-03  -0.005106
    1980-01-04  0.012355
    1980-01-07  0.002723
    1980-01-08  0.020036
    1980-01-09  0.000918
    ... ...
    2020-10-26  -0.018590
    2020-10-27  -0.003026
    2020-10-28  -0.035288
    2020-10-29  0.011947
    2020-10-30  -0.012130
    10297 rows × 1 columns