Date Open High Low Close Volume
2023-12-28 326.6 331.0 324.0 329.8 16123212
2023-12-27 327.05 329.9 321.65 324.85 10349372
2023-12-26 328.55 331.4 325.0 325.4 11314266
2023-12-22 331.0 332.0 323.55 326.65 15179674
2023-12-21 318.0 330.7 312.7 328.55 26393082
2023-12-20 336.7 346.9 318.0 320.15 40678163
2023-12-19 338.5 338.5 330.45 335.9 11713755
2023-12-18 339.0 340.3 334.4 337.05 15561817
2023-12-15 337.4 338.5 331.8 333.2 17080409
2023-12-14 340.9 341.9 335.0 335.4 16560229
2023-12-13 332.1 340.5 329.75 338.15 33632037
2023-12-12 335.0 335.0 327.6 330.8 22627713
2023-12-11 325.4 335.3 322.35 333.65 40351523
2023-12-08 331.95 335.95 318.1 323.55 74992149
2023-12-07 295.0 332.15 292.15 325.8 152381610
将上述数据作为 df 放入数据帧中,并希望创建另一列作为 4Bars 。
def find4Bars(data) :
\# this data variable should have following 3 Rows along with Current Rows
(at anypoint, only 4 rows to be passed into this function)
\# Doing Calculation with the 4 records and returning value to a variable ( calValue )
return calValue
df\['Bars'\] = df.apply(find4Bars.iloc\[CurrentRows:CurrentRows+3, axis=1)
注意:由于日期索引无法迭代,因此无法使用 iloc 函数。 不想为索引创建另一个流水号并在日期重新创建索引。
import yfinance as yf
data = yf.download('AAPL', period='50d', interval='1d', progress=False)[::-1]
使用上面的代码,可以下载数据进行试用。
感谢您的帮助
your text
您可以使用
df.rolling
每次提供 4 行 window
:
def find4Bars(data) :
calValue = data.sum()
return calValue
data.Close.rolling(window=4).apply(find4Bars, raw=True)
前 3 行将有
np.nan
值,为了避免这种情况,您可以将 min_periods
设置为 1
:
data.Close.rolling(window=4, min_periods=1).apply(find4Bars, raw=True)
注意:计算基于当前行和前3行,如果您想使用当前行和之后的3行,可以使用
shift
,如本答案所示:
data.Close.rolling(window=4, min_periods=1).apply(find4Bars, raw=True).shift(-3)
有关更多信息,请查看 df.rolling、Rolling.apply、shift 文档。