问题
i get error while running this code what to do? i get error ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
unrealized = [0, 0.50, 0.90, 0.20, 3, 6, 7, 2]
def stoploss():
df = pd.DataFrame({"price": unrealized})
df['high'] = df.cummax()
if df['high'] <= 0.10:
df['trailingstop'] = -0.50
df['signalstop'] = df['price'] < df['trailingstop']
if df['high'] >= 0.10:
df['trailingstop'] = df['high'] - 0.10
df['signalstop'] = df['price'] < df['trailingstop']
return df['signalstop'].iloc[-1]
print(stoploss())
回答1:
Well, it is because the truth value of a series is ambiguous. But what does that mean? Just check the output of df['high']<=0.1 and you'll see a series of True/False values depending on if the condition is met or not. And you are asking the truth value of this series by using the if statement. And what should that be? That is exactly what the error is telling you. "Should I use any or all or what should I do with this series?"
But I assume you want to do something else: You want to set these two extra columns depending on the value in the high column. Use the .loc with a condition to set a value for all items matching the condition as described here: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html
So the code might look like this (if I guessed your intention correctly):
df['high'] = df.cummax()
df.loc[df['high']<=0.1,'trailingstop'] = -0.50
df.loc[df['high']<=0.1,'signalstop'] = df['price'] < df['trailingstop']
df.loc[df['high']>=0.1,'trailingstop'] = df['high']-0.10
df.loc[df['high']>=0.1,'signalstop'] = df['price'] < df['trailingstop']
回答2:
The problem is in the lines
if df['high'] <= 0.10:
and
if df['high'] >= 0.10:
Because you are comparing a whole series against a number
Not entirely sure what your goal is, but here is some working code:
unrealized = [0, 0.50, 0.90, 0.20, 3, 6, 7, 2]
def stoploss():
df = pd.DataFrame({"price": unrealized})
df['high'] = df.cummax()
df['trailingstop'] = 0 # just to create the series in the DF
df['trailingstop'][df['high'] <= 0.10] = -0.50
df['trailingstop'][df['high'] >= 0.10] = df['high'] - 0.10
print(df['trailingstop'])
df['signalstop'] = df['price'] < df['trailingstop']
print(df['signalstop'])
return df['signalstop'].iloc[-1]
print(stoploss())
Result:
0 -0.5
1 0.4
2 0.8
3 0.8
4 2.9
5 5.9
6 6.9
7 6.9
Name: trailingstop, dtype: float64
0 False
1 False
2 False
3 True
4 False
5 False
6 False
7 True
Name: signalstop, dtype: bool
True
来源:https://stackoverflow.com/questions/64810966/i-get-valueerror-the-truth-value-of-a-series-is-ambiguous-use-a-empty-a-bool