【发布时间】:2022-01-04 22:23:35
【问题描述】:
我有一个熊猫数据框,其中包含证券价格和几条不同移动平均长度的移动平均趋势线。数据框足够大,我想确定最有效的方法来捕获斜率变化的特定系列的索引(在这个例子中,我们只是说数据框中给定系列的正数到负数。)
我的 hack 看起来很“hacky”。我目前正在执行以下操作(注意,假设这是针对单个移动平均线系列):
filter = (df.diff()>0).diff().dropna(axis=0)
new_df = df[filter].dropna(axis=0)
下面的完整示例代码:
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
# Create a sample Dataframe
date_today = datetime.now()
days = pd.date_range(date_today, date_today + timedelta(7), freq='D')
close = pd.Series([1,2,3,4,2,1,4,3])
df = pd.DataFrame({"date":days, "prices":close})
df.set_index("date", inplace=True)
print("Original DF")
print(df)
# Long Explanation
updays = (df.diff()>0) # Show True for all updays false for all downdays
print("Updays df is")
print(updays)
reversal_df = (updays.diff()) # this will only show change days as True
reversal_df.dropna(axis=0, inplace=True) # Handle the first day
trade_df = df[reversal_df].dropna() # Select only the days where the trend reversed
print("These are the days where the trend reverses it self from negative to positive or vice versa ")
print(trade_df)
# Simplified below by combining the above into two lines
filter = (df.diff()>0).diff().dropna(axis=0)
new_df = df[filter].dropna(axis=0)
print("The final result is this: ")
print(new_df)
我们将不胜感激。请注意,我更感兴趣的是如何在如何最好地做到这一点以便我理解它以及如何使其足够快地进行计算之间平衡效率。
【问题讨论】:
-
您是否需要发现移动平均线的斜率何时改变符号或仅改变幅度?
-
@MarcelloChiuminatto 在这种情况下,我正在寻找他们,因为他们改变了标志。
标签: python pandas dataframe time-series