Pd['Column1] > Pd['Column2'] Key Error: 0

Pd['Column1] > Pd['Column2'] Key Error: 0

我正在尝试编写一个循环遍历 pandas 数据帧并比较 column1 > column2 的函数,如果是则将 1 附加到列表,然后返回。

正在从yahoo finance 导入财务数据,计算2 Std 并分配给column upper 和lower,以及moving average。

    import pandas as pd 
    import pandas_datareader as web
    import matplotlib.pyplot as plt
    %matplotlib inline
    from datetime import datetime
    import numpy as np

    end = datetime(2021, 1, 16)
    start = datetime(2020 , 1, 16)

    symbols = ['ETH-USD']
    stock_df = web.get_data_yahoo(symbols, start, end)
    period = 20
    # Simple Moving Average
    stock_df['SMA'] = stock_df['Close'].rolling(window=period).mean()
    # Standard deviation
    stock_df['STD'] = stock_df['Close'].rolling(window=period).std() 
    # Upper Bollinger Band
    stock_df['Upper'] = stock_df['SMA'] + (stock_df['STD'] * 2)
    # Lower Bollinger Band
    stock_df['Lower'] = stock_df['SMA'] - (stock_df['STD'] * 2)
    # List of columns
    column_list = ['Close', 'SMA', 'Upper', 'Lower']
    stock_df[column_list].plot(figsize=(12.2,6.4)) #Plot the data
    plt.title('ETH-USD')
    plt.ylabel('USD Price ($)')
    plt.show();

    #Create a new data frame, Period for calculation, removes NAN's
    bolldf = stock_df[period-1:]
    #Show the new data frame
    bolldf

函数,遍历列行并比较,如果满足条件,将 df['Close'][0] 附加到 buy/sell 信号。


    def signal(df):
         buy_signal = []
         sell_signal = [] 

         for i in range(len(df['Close'])):
            if df['Close'][i] > df['Upper'][i]:
               buy_signal.append(1)
         return buy_signal

    buy_signal = signal(bolldf)

    buy_signal

关于错误的信息:

按键错误:0

在处理上述异常的过程中,又发生了异常: ---> 12 buy_signal = 大于(stock_df)

按键错误:0

在处理上述异常的过程中,又发生了异常: 11 ---> 12 buy_signal = 大于(stock_df) 13

----> 8 如果 bolldf['Close'][i] > bolldf['Open'][i]:

按键错误:0

当我尝试在列 df['Upper'] > df['Lower] 或 df['SMA'] < df['Lower'] 上使用此功能时,它会起作用正如预期的那样,只有在使用原始数据中的列时它才不起作用。

任何帮助都会很棒。谢谢。

既然是多索引,那么列也必须指定为多索引格式。可以查看bolldf.columns列的内容,修改如下即可得到

bolldf.columns
MultiIndex([('Adj Close', 'ETH-USD'),
            (    'Close', 'ETH-USD'),
            (     'High', 'ETH-USD'),
            (      'Low', 'ETH-USD'),
            (     'Open', 'ETH-USD'),
            (   'Volume', 'ETH-USD'),
            (      'SMA',        ''),
            (      'STD',        ''),
            (    'Upper',        ''),
            (    'Lower',        '')],
           names=['Attributes', 'Symbols'])

def signal(df):
    buy_signal = []
    sell_signal = []    
    for i in range(len(df[('Close','ETH-USD')])):
        if df[('Close','ETH-USD')][i] > df[('Upper','')][i]:
            buy_signal.append(1)
    return buy_signal

buy_signal = signal(bolldf)