动态计算groupby之后两个日期之间的移动平均值-Python

问题描述

我有2年的每日股票收益率,我想计算每个股票的6个月历史移动平均收益率。我的数据有3列:日期,股票行情,返回。

例如,如果当前日期为2019-01-31,我想计算2018-07-31和2019-01-31之间的平均回报(不包括开始日期)。

我分两步完成了此操作,但是运行起来很慢,而且我每天只有100个股票:

  1. 获取6个月前的日期
<CarouselView IndicatorView="indicatorView"> // set indicatorView for CarouselView 
  <CarouselView.ItemTemplate>
    <DataTemplate>
      ...
    </DataTemplate>
  </CarouselView.ItemTemplate>
</CarouselView>

<IndicatorView
  x:Name="indicatorView"
  IsVisible="{Binding CarouselVisible}"
  VerticalOptions="End"
  IndicatoRSShape="Circle"
  IndicatorSize="8"
  IndicatorColor="#666666"
  Margin="0,7"
  SelectedindicatorColor="#cccccc"
  HorizontalOptions="Center"
/>
  1. 代码进行分组,然后将我的移动平均线函数应用于每个代码
df['date'] = pd.to_datetime(df['date'])
df['six_months_ago']= df['date'].apply(lambda x: x.date() + relativedelta(months=-6))
df['six_months_ago'] = pd.to_datetime(df['six_months_ago'])

# filter out dates that have less than 6 months of data
df = df[df['six_months_ago'] >= df['date'].min()]

是否有更有效/更快的方法?我相信滚动功能在这里不起作用,因为我的窗口大小不是恒定的。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)