我在语法上遇到麻烦。我想在LastPrice将>到较低区间时买入,在LastPrice == sma水平时卖出,如果这是真的,我想将结果放入一列中:“买入”,它不是像这样放置“卖”
我的代码:
df['LastPrice'].dropna(inplace=True)
sma = df['LastPrice'].rolling(window=20).mean()
rstd = df['LastPrice'].rolling(window=20).std()
df['upper_band'] = sma + 2 * rstd
df['lower_band'] = sma - 2 * rstd
df['laseñalota'] = np.where((df['LastPrice'] > df['lower_band'],"Buy") & (df['LastPrice'] == sma), "Sell")
错误是:
operands could not be broadcast together with shapes (2,) (4508,)
答案 0 :(得分:1)
df['laseñalota'] = np.where(df['LastPrice'] > df['lower_band'], 'Buy',
np.where(df['LastPrice'] <= sma, 'Sell', 'Do Nothing'))
根据@ user3483203的建议,如果您有更多条件并希望在代码的另一行中更准确地反映它,也可以使用np.select
。例如,请参见以下代码:
condlist = [df['LastPrice'] > df['lower_band'], df['LastPrice'] <= sma]
choicelist = ['Buy', 'Sell']
df['new_laseñalota'] = np.select(condlist, choicelist)