title: Rolling a custom function over pandas series in python
body: <p>I have a pandas series </p>
  
  <pre><code>Date
  2016-11-01    100000.000000
  2016-11-02    100500.648302
  2016-11-03    100481.450478
  2016-11-04     99550.193742
  2016-11-07    101913.648567
  </code></pre>
  
  <p>I am trying to calculate a rolling sharpe ratio on this series. The formula for the sharpe ratio is </p>
  
  <pre><code>sharpe = np.sqrt(252)*(average_daily_returns/volatility)
  </code></pre>
  
  <p>where we can calculate daily returns as</p>
  
  <pre><code>daily_returns = (series/series.shift(1))-1
  daily_returns = daily_returns[1:]
  </code></pre>
  
  <p>then average _daily_returns becomes </p>
  
  <pre><code>average_daily_returns = daily_returns.mean()
  </code></pre>
  
  <p>and volatility becomes </p>
  
  <pre><code>volatility = daily_returns.std()
  </code></pre>
  
  <p>I am trying to roll the sharpe ratio over the series. So I want to calculate the sharpe ratio for day 1 then day 1 and day 2 then day 1 and day 2 and day 3 then day 1 and day 2 and ... and day n where n is the last date in the series.</p>
  
  <p>I have created the following function: </p>
  
  <pre><code>def sharpe(s): 
      daily_returns = (s/s.shift(1))-1
      daily_returns = daily_returns[1:]
      average_daily_returns = daily_returns.mean()
      volatility = daily_returns.std()
      sharpe = np.sqrt(252)*(average_daily_returns/volatility)
  </code></pre>
  
  <p>This above function will calculate the sharpe ratio for each series passed in. I want to roll this function over the series. So, roll this function on (2016-11-01) then on (2016-11-01 and 2016-11-02) then on (2016-11-01 and 2016-11-02 and 2016-01-03) ...</p>
  
  <p>I have looked at pandas.rolling_apply and the doccumentation (<a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.rolling_apply.html" rel="nofollow noreferrer">http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.rolling_apply.html</a>) but I can not get this to work with my function. It seems that the rolling_apply is only working when I do a function such as a sum, mean, or simple calculation like that. I have tried many variations of this but nothing has worked so far. For instance using </p>
  
  <pre><code>(pv.rolling(2)).apply(#I am not sure how I can fit the sharpe ratio function in here)
  </code></pre>