How to calculate the weekly mean of a dataframe index between specific dates?

Viewed 109

I'm trying to calculate the weekly average of movement of open and close Netflix stock prices. The weekly average needs to be returned for a period between start and end. The movement index is part of the dataframe I am operating, called nflx_Frame.

            open   close   movement  py_date
2020-03-06  367.70  368.97  1.27    2020-03-06
2020-03-05  381.00  372.78  -8.22   2020-03-05
2020-03-04  377.77  383.79  6.02    2020-03-04
2020-03-03  381.03  368.77  -12.26  2020-03-03
2020-03-02  373.11  381.05  7.94    2020-03-02
... ... ... ... ...
2019-10-18  289.36  275.30  -14.06  2019-10-18
2019-10-17  304.49  293.35  -11.14  2019-10-17
2019-10-16  283.12  286.28  3.16    2019-10-16
2019-10-15  283.82  284.25  0.43    2019-10-15
2019-10-14  283.93  285.53  1.60    2019-10-14

Here is my code:

start = create_py_date_from_str('2020-02-06') #inital date
end = create_py_date_from_str('2020-03-06')

def week_avg(df, start):
    return df['movement'].resample('W').mean().between(start, end, inclusive = True)

week_avg(nflx_Frame, start)
nflx_Frame

But it returns this: TypeError: '>=' not supported between instances of 'float' and 'datetime.datetime'. I would appreciate any help with this.

UPDATE

I have fixed the issue. I've changed it to:

def week_avg(df, time):
period = df[df['py_date'].between(time, end, inclusive = True)]
cut_off = datetime.strptime('2020-01-01','%Y-%m-%d')
if time < cut_off:
    return('ERROR; dates out of range')
elif time > today:
    return('ERROR; dates out of range')
else:
    return period['movement'].resample('W').mean( '

And it works like magic now.

0 Answers
Related