Kim Robenson
Kim Robenson

Reputation: 15

Python: Pandas function KeyError (algo-trading)

My probem is about how can I apply a function in my code I've tried until now to solve it but i always get errors.

def ichimoku_kinko_hyo(Data):
  # Tenkan-sen (Conversion Line): (9-period high + 9-period low)/2))
  nine_period_high = Data['High'].rolling(window= 9).max()
  nine_period_low = Data['Low'].rolling(window= 9).min()
  Data['tenkan_sen'] = (nine_period_high + nine_period_low) /2
  tenkan_sen= Data['tenkan_sen']
  
  # Kijun-sen (Base Line): (26-period high + 26-period low)/2))
  period26_high = Data['High'].rolling(window=26).max()
  period26_low = Data['Low'].rolling(window=26).min()
  Data['kijun_sen'] = (period26_high + period26_low) / 2
  kijun_sen= Data['kijun_sen']
  # Senkou Span A (Leading Span A): (Conversion Line + Base Line)/2))
  Data['senkou_span_a'] = ((Data['tenkan_sen'] + Data['kijun_sen']) / 2).shift(26)
  senkou_span_a= Data['senkou_span_a']

  # Senkou Span B (Leading Span B): (52-period high + 52-period low)/2))
  period52_high = Data['High'].rolling(window=52).max()
  period52_low = Data['Low'].rolling(window=52).min()
  Data['senkou_span_b'] = ((period52_high + period52_low) / 2).shift(26)
  senkou_span_b= Data['senkou_span_b']
  # The most current closing price plotted 26 time periods behind (optional)
  Data['chikou_span'] = Data['Close'].shift(-26)
  chikou_span= Data['chikou_span']

  return Data

def signal(Data):
 for i in range(len(Data)):
   if Data.iloc[i]['tenkan_sen'] > Data.iloc[i]['kijun_sen'] and Data.iloc[i - 1]['tenkan_sen'] < Data.iloc[i - 1]['kijun_sen'] and Data.iloc[i]['Close'] > Data[i]['senkou_span_a'] and Data.iloc[i]['Close'] > Data.iloc[i]['senkou_span_b'] and Data.iloc[i - 26]['chikou_span'] > Data.iloc[i - 26]['Close']:
    Data.iloc[i]['buy'] = 1 
   else:
    Data.iloc[i]['buy'] = 0

signal(data)

And here's the head of my 'data' or DataFrame

Date        Open        High        Low         Close       Adj Close   Volume              
2021-02-22  1935.557861 1936.453735 1580.626587 1781.992920 1781.992920 42409646036
2021-02-23  1781.409058 1781.409058 1378.840942 1570.203979 1570.203979 52029864713
2021-02-24  1571.476440 1710.983765 1511.018921 1626.575684 1626.575684 31329000537
2021-02-25  1625.393921 1670.224121 1465.058960 1475.703735 1475.703735 24481681873
2021-02-26  1478.653320 1559.028931 1407.979248 1446.033691 1446.033691 31435997881

This is the error i'm getting while running this code:

/usr/local/lib/python3.7/dist-packages/pandas/core/series.py:1056: SettingWithCopyWarning:


A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

/usr/local/lib/python3.7/dist-packages/pandas/core/indexing.py:1724: SettingWithCopyWarning:


A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3360             try:
-> 3361                 return self._engine.get_loc(casted_key)
   3362             except KeyError as err:

How can I apply this code to my Data? It doesn't matter if there's NAN's missing values.

Upvotes: 1

Views: 223

Answers (2)

r-beginners
r-beginners

Reputation: 35230

As for debugging the error.

  1. Checked the output of error rows.
  2. Since NA is an issue, we replaced NA with 0 for all columns.
  3. Since the conditional judgment of the signal is an issue, we disassembled and checked one condition at a time.
  4. We confirmed that the row specification for the third judgment was missing.
   def signal(Data):
        Data = ichimoku_kinko_hyo(Data)
        #print(Data.iloc[69])
        Data.fillna(0, inplace=True)
        #print(Data.info())
        Data['buy'] = 0
        for i in range(len(Data)):
            print(Data.iloc[i])
            print(Data.iloc[i]['tenkan_sen'] > Data.iloc[i]['kijun_sen'])
            print(Data.iloc[i - 1]['tenkan_sen'] < Data.iloc[i - 1]['kijun_sen'])
            print(Data.iloc[i]['Close'] > Data.iloc[i]['senkou_span_a']) # updated
            print(Data.iloc[i]['Close'] > Data.iloc[i]['senkou_span_b'])
            print(Data.iloc[i - 26]['chikou_span'] > Data.iloc[i - 26]['Close'])
            if Data.iloc[i]['tenkan_sen'] > Data.iloc[i]['kijun_sen'] and Data.iloc[i - 1]['tenkan_sen'] < Data.iloc[i - 1]['kijun_sen'] and Data.iloc[i]['Close'] > Data.loc[i]['senkou_span_a'] and Data.iloc[i]['Close'] > Data.iloc[i]['senkou_span_b'] and Data.iloc[i - 26]['chikou_span'] > Data.iloc[i - 26]['Close']:
                 Data.iloc[i]['buy'] = 1 
            else:
                Data.iloc[i]['buy'] = 0
        return Data

Upvotes: 1

Davr
Davr

Reputation: 31

I recommend taking a look at this video which has an implementation of the ichimoku cloud you are trying to make. I watched it a while ago and it made sense to me. Here is the source code if you don't wanna bother watching it.

Upvotes: 1

Related Questions