Logarithmic returns in pandas dataframe

后端 未结 5 1203
悲&欢浪女
悲&欢浪女 2020-12-07 15:45

Python pandas has a pct_change function which I use to calculate the returns for stock prices in a dataframe:

ndf[\'Return\']= ndf[\'TypicalPrice\'].pct_chan         


        
5条回答
  •  [愿得一人]
    2020-12-07 16:22

    @poulter7: I cannot comment on the other answers, so I post it as new answer: be careful with

    np.log(df.price).diff() 
    

    as this will fail for indices which can become negative as well as risk factors e.g. negative interest rates. In these cases

    np.log(df.price/df.price.shift(1)).dropna()
    

    is preferred and based on my experience generally the safer approach. It also evaluates the logarithm only once.

    Whether you use +1 or -1 depends on the ordering of your time series. Use -1 for descending and +1 for ascending dates - in both cases the shift provides the preceding date's value.

提交回复
热议问题