3

I want to calculate the rolling_std for daily returns, using all records previous to the current row. How do i set the window to use the rolling count of the rows? For example: on 04-04. I want to use all rows to calculate, on 04-01 I want to use all rows with date less than 04-01.

Date        Daily       Std
4/4/2016    -0.003087335    ?
4/1/2016    0.006480923 ?
3/31/2016   -0.001553158    ?
3/30/2016   0.004351748 ?
3/29/2016   0.009234222 ?
1
  • 1
    you probably want expanding() rather than rolling() and also need to sort to get things in ascending date order
    – JohnE
    Apr 6, 2016 at 20:14

1 Answer 1

6

With pandas 0.18, use the Rolling object. This is a 2-day rolling std:

df.rolling(2).std()

With prior version, the call would be:

df.rolling_std(2)

If the goal is to get the function applied from the beginning of the DataFrame down to the current line, then the object to use is Expanding:

df.expanding().std()
3
  • 1
    I want the number of days of rolling to be dynamic based on the number of previous records. So on 4-4 should have 5 rows, on 4-1 should use 4 rows, on 3-31 should use 3 rows.
    – Poly-AAAA
    Apr 6, 2016 at 20:13
  • 1
    also need to sort b/c dates are currently reversed compared to what OP is asking for. expanding only goes in one direction, I believe.
    – JohnE
    Apr 6, 2016 at 20:21
  • Buzz light year to the rescue, didn't realize there was such a simple built in functionality, thank you.
    – Poly-AAAA
    Apr 6, 2016 at 20:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.