Q:

calculate Geometric mean return for specific rows

I have a dataframe like this.
       Date       price     mid      std         top             btm
     ..............
    1999-07-21  8.6912  8.504580    0.084923    9.674425    8.334735
    1999-07-22  8.6978  8.508515    0.092034    8.692583    8.324447
    1999-07-23  8.8127  8.524605    0.118186    10.760976   8.288234
    1999-07-24  8.8779  8.688810    0.091124    8.871057    8.506563
     ..............

I want to create a new col called 'diff'.
If in a row ,'price' >'top' then I want to fill 'diff' of this row with the Geometric mean return of price in this row and price in the n-5 previous row.(The 5-day Geometric mean).
For example, In row 1999-07-22,the price is greater than top, so I wanto fill 'diff' in this row with  Geometric mean of 07-22 and 07-17(notice the date may not be consecutive since holidays are excluded ). Only a small part of the rows meet the demand. So most of values in 'diff' will be missing values.
Could you please tell me how I can do this in python?

A:

Use Series.diff with Series.where for set NaNs:
df['diff'] = df['price'].diff().where(df['price'] > df['top'])
print (df)
             price       mid       std        top       btm    diff
Date                                                               
1999-07-21  8.6912  8.504580  0.084923   9.674425  8.334735     NaN
1999-07-22  8.6978  8.508515  0.092034   8.692583  8.324447  0.0066
1999-07-23  8.8127  8.524605  0.118186  10.760976  8.288234     NaN
1999-07-24  8.8779  8.688810  0.091124   8.871057  8.506563  0.0652

EDIT:
I believe you need:
df['Date'] = pd.to_datetime(df['Date'])
df = df.set_index('Date')

from scipy.stats.mstats import gmean

df['gmean'] = (df['price'].rolling('5d')
                          .apply(gmean, raw=True)
                          .where(df['price'] > df['top']))
print (df)
             price       mid       std        top       btm     gmean
Date                                                                 
1999-07-21  8.6912  8.504580  0.084923   9.674425  8.334735       NaN
1999-07-22  8.6978  8.508515  0.092034   8.692583  8.324447  8.694499
1999-07-23  8.8127  8.524605  0.118186  10.760976  8.288234       NaN
1999-07-24  8.8779  8.688810  0.091124   8.871057  8.506563  8.769546

