The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

运行以下代码:

condition1 = df['MACD'] < 0 and df['MACD'].shift(3) > 0
condition2 = df['DIF'] < 0 and df['DIF'].shift(3) > df['DEA']
condition3 = df['volume'] > df['volume_ma']*n
df.loc[condition1 & condition2 & condition3, 'signal_short'] = 1

出现报错:

multiprocessing.pool.RemoteTraceback:
"""
Traceback (most recent call last):
  File "C:\Users\kawujeilu\AppData\Local\Continuum\anaconda3\lib\multiprocessing\pool.py", line 121, in worker
    result = (True, func(*args, **kwds))
  File "C:\Users\kawujeilu\AppData\Local\Continuum\anaconda3\lib\multiprocessing\pool.py", line 44, in mapstar
    return list(map(*args))
  File "D:\林杰\交易\刑不行\coin_quant_class_2019_0623副本\my\optimize_youhua_macd.py", line 77, in backtest
    df = signal_macd4(self.all_data.copy(), para)
  File "D:\林杰\交易\刑不行\coin_quant_class_2019_0623副本\my\xbxSignals3.py", line 239, in signal_macd4
    condition1 = df['MACD'] < 0 and df['MACD'].shift(3) > 0
  File "C:\Users\kawujeilu\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\generic.py", line 1478, in __nonzero__
    .format(self.__class__.__name__))
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
"""

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "optimize_youhua_macd.py", line 212, in 
    rtn_list = pool.map(yh.backtest, para_list)         # 将para_list中数据依次传入
  File "C:\Users\kawujeilu\AppData\Local\Continuum\anaconda3\lib\multiprocessing\pool.py", line 268, in map
    return self._map_async(func, iterable, mapstar, chunksize).get()
  File "C:\Users\kawujeilu\AppData\Local\Continuum\anaconda3\lib\multiprocessing\pool.py", line 657, in get
    raise self._value
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

报错指出是这一行的问题:condition1 = df['MACD'] < 0 and df['MACD'].shift(3) > 0

原因是由于在python中 or 和 and 的声明需要 truth-values, 即真实的True或者False

但是df['MACD'] < 0 and df['MACD'].shift(3) > 0返回并不是True或False

将代码更改成

condition1 = df['MACD'] < 0 & df['MACD'].shift(3) > 0

也依然无效。最终用最笨的方法,多写了几行

condition1 = df['MACD'] < 0 
condition2 = df['MACD'].shift(3) > 0
condition3 = df['DIF'] < 0 
condition4 = df['DIF'].shift(3) > df['DEA']
condition5 = df['volume'] > df['volume_ma']*n
df.loc[condition1 & condition2 & condition3 & condition4 & condition5, 'signal_short'] = 1

问题解决

你可能感兴趣的:(python,pandas)