我正在用python做我的第一个项目。我有一个名为df的熊猫数据框,其中有两列“ close”和“ volume”。我想基于前两列来计算/获取OBV列。公式如下:
如果收盘价高于先前收盘价,则: 当前OBC =以前的OBC +当前数量
如果收盘价低于先前收盘价,则: 当前OBV =先前的OBV-当前体积
如果收盘价等于之前的收盘价,则: 当前OBV =先前的OBV(不变)
收盘价OBC 30 2500南 32 3000 5500 25 2700 2800 35 4000 6800 20 1000 5800
我正在使用以下代码:
for i in df.close[1:]:
if i > df.close.shift(-1):
df["OBC"] = df.volume + df.OBC.shift(-1)
elif i < df.close.shift(-1):
df["OBC"] = df.OBC.shift(-1) - df.volume
else:
df["OBC"] = df.OBC
,我得到这个错误: ValueError:系列的真值不明确。使用a.empty,a.bool(),a.item(),a.any()或a.all()。
我已经看过这个问题,但是没有得到任何帮助。 Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
除此错误外,我认为代码在计算正确的OBV时可能会遇到麻烦。任何帮助都将具有巨大的价值。
答案 0 :(得分:2)
我不知道为什么会出现错误,但这是获取OBV的解决方案:
np.where(df['close'] > df['close'].shift(1), df['volume'],
np.where(df['close'] < df['close'].shift(1), -df['volume'], 0)).cumsum()
它也更快,如果您要进行很多次迭代,那就太好了!
答案 1 :(得分:1)
我基于 Olli 的回答,但我认为这是一个更简洁的解决方案:
library(rlang)
library(tidyverse)
a <- c(1:8)
b <- c(23,34,45,43,32,45,68,78)
c <- c(0.34,0.56,0.97,0.33,-0.23,-0.36,-0.11,0.17)
df <- data.frame(a,b,c)
tf <- function(df,MYcol) {
print(paste0("The name of the input column is ",MYcol)) # does not work
print(paste0("The name of the input column is ",{{MYcol}})) # does not work
y <- {{MYcol}} # This gives the values in column b as it shoulkd
}
z <- tf(df,b) # Gives undesired values - I want the string "b"
z