[Python] Could not retrieve data fram without index thus resulting in value error

Discussão em 'Python' iniciado por Stack, Junho 20, 2025.

  1. Stack

    Stack Membro Participativo

    I have this below code that calculates DEMA [Double Exponential Moving Average] based on the close price

    import backtrader as bt
    import pandas as pd

    class CalculateDema:

    def __init__(self, data, period):
    self.period = period
    self.data = data
    close = []
    for i in self.data:
    close.append(i)
    self.df = pd.DataFrame(close)
    #self.df.reset_index(drop=True)

    def calculate_ema(self, data, period):
    return data.ewm(span=period, adjust=False).mean()

    def calculate_dema(self):
    ema1 = self.calculate_ema(self.df, self.period)
    ema2 = self.calculate_ema(ema1, self.period)
    dema = (2 * ema1) - ema2
    dema_df = pd.DataFrame(dema)
    #dema_df = dema_df.reset_index(drop=True, inplace=True)
    #dema_df.set_index(drop=True)
    return dema


    Below is the code that gets the data returned to main funtion and tries to do a comparison

    dema = CalculateDema(data = self.dataclose, period = self.p.period)
    self.dema = dema.calculate_dema()


    Below is the output if i print self.dema[0]

    0 56258.620924
    1 56140.770683
    2 56064.450842
    3 56025.820675
    4 55990.549055
    ...
    1496 56300.308681
    1497 56291.186529
    1498 56289.345639
    1499 56289.648383
    1500 56278.184361
    Name: 0, Length: 1501, dtype: float64


    Below is the code that checks whether close price is greater than or equal to dema and performs some operation

    if (self.dataclose[0] >= self.dema[0] and self.dataclose[0] >= self.donchian.dcm[0]):
    do something


    and at this point I am getting the below error

    if (self.dataclose[0] >= self.dema[0] and self.dataclose[0] >= self.donchian.dcm[0]):
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "H:\My Drive\Python_\zero\Lib\site-packages\pandas\core\generic.py", line 1577, in __nonzero__
    raise ValueError(
    ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

    Continue reading...

Compartilhe esta Página