Pandas DataFrame切片问题

时间:2017-09-17 15:06:44

标签: python pandas

为了回溯测试财务数据,我写了一个算法, 我的代码如下:     将pandas导入为pd     导入numpy为np     导入日期时间     从datetime导入日期时间     来自datetime import timedelta     将matplotlib.pyplot导入为plt

start_date = '2016-01-01'
end_date = '2017-09-15'
symbols = ['PAEL']
def data_symbol():
    dates=pd.date_range(start_date,end_date) 
    df=pd.DataFrame(index=dates)
    for symbol in symbols:
        df_temp=pd.read_csv('/home/furqan/Desktop/python_data/{}.csv'.format(symbol),usecols=['Date','Close'],
                        parse_dates=True,index_col='Date',na_values=['nan'])
        df=df.join(df_temp)
        df=df.fillna(method='ffill')
        df=df.fillna(method='bfill')
        df.index.names = ['Date']
    return df

def bollinger_start(df,window,std_dev):
    rolling_mean = df['Close'].rolling(window).mean()
    rolling_std = df['Close'].rolling(window).std()

    df['Bollinger High'] = rolling_mean + (rolling_std * std_dev)
    df['Bollinger Low'] = rolling_mean - (rolling_std * std_dev)

    #df['Short'] = None
    #df['Long'] = None
    df['Position'] = None
    print(df.tail())

    for row in range(len(df)):

        if (df['Close'].iloc[row] > df['Bollinger High'].iloc[row]) and (df['Close'].iloc[row-1] < df['Bollinger High'].iloc[row-1]):
            df['Position'].iloc[row] = -1

        if (df['Close'].iloc[row] < df['Bollinger Low'].iloc[row]) and (df['Close'].iloc[row-1] > df['Bollinger Low'].iloc[row-1]):
            df['Position'].iloc[row] = 1

    df['Position'].fillna(method='ffill',inplace=True)

    df['Market Return'] = np.log(df['Close'] / df['Close'].shift(1))
    df['Strategy Return'] = df['Market Return'] * df['Position']
    print(df.tail())
    df[['Strategy Return', 'Market Return']].cumsum().plot()
    plt.show()

df = data_symbol()
bollinger_start(df,50,2)

和dataframe(df)如下:

            Close  Bollinger High  Bollinger Low Position
Date                                                     
2017-09-11  71.31      115.253111      59.547689     None
2017-09-12  73.15      114.761653      58.966347     None
2017-09-13  75.14      113.992835      58.615965     None
2017-09-14  74.08      113.116464      58.290736     None
2017-09-15  73.37      112.222221      57.970179     None

以上代码行给出如下错误:

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

我无法弄清楚如何解决此错误。

0 个答案:

没有答案