熊猫DataFrame行项目IF比较未返回正确结果

时间:2019-03-08 06:28:58

标签: python pandas dataframe

我从quandl检索数据并将其加载到熊猫DF对象。

然后,我根据“最后价格”计算SMA值(SMA21,SMA55)。 将这些SMA值作为列添加到我的DF对象中。

我遍历DF以捕获购买信号。

我知道某些日期的购买条件成立,但是我的代码没有打印任何内容。我希望至少打印出购买条件。

如下所示,您可以看到以下情况:

kitem['SMA21'] >= kitem['Last'] 

我的代码:

import requests 
import pandas as pd
import json

class URL_Params:

    def __init__ (self, endPoint, symboll, startDate, endDate, apiKey):
        self.endPoint = endPoint
        self.symboll = symboll
        self.startDate = startDate
        self.endDate = endDate
        self.apiKey = apiKey

    def createURL (self):
        return self.endPoint + self.symboll + '?start_date=' + self.startDate + '&end_date=' + self.endDate + '&api_key=' + self.apiKey

    def add_url(self, _url):
        self.url_list

my_portfolio = {'BTC':1.0, 'XRP':0, 'DSH':0, 'XMR':0, 'TotalBTCValue':1.0}

_endPoint = 'https://www.quandl.com/api/v3/datasets/BITFINEX/'
_symbolls = ['BTCEUR','XRPBTC','DSHBTC','IOTBTC','XMRBTC']
_startDate = '2017-01-01'
_endDate = '2019-03-01'
_apiKey = '' #needs to be set for quandl

my_data = {}
my_conns = {}
my_col_names =  ['Date', 'High', 'Low', 'Mid', 'Last', 'Bid', 'Ask', 'Volume']
orderbook = []



#create connection and load data for each pair/market.
#load them in a dict for later use
for idx_symbol in _symbolls:
    my_url_params = URL_Params(_endPoint,idx_symbol,_startDate,_endDate,_apiKey)
    response = requests.get(my_url_params.createURL())
    my_data[idx_symbol] = json.loads(response.text)

#Prepare Data
my_raw_data_df_xrpbtc = pd.DataFrame(my_data['XRPBTC']['dataset']['data'], columns= my_data['XRPBTC']['dataset']['column_names'])

#Set Index to Date Column and Sort
my_raw_data_df_xrpbtc['Date'] = pd.to_datetime(my_raw_data_df_xrpbtc['Date'])
my_raw_data_df_xrpbtc.index = my_raw_data_df_xrpbtc['Date']
my_raw_data_df_xrpbtc = my_raw_data_df_xrpbtc.sort_index()

#Drop unrelated columns
my_raw_data_df_xrpbtc.drop(['Date'], axis=1, inplace=True)
my_raw_data_df_xrpbtc.drop(['Ask'], axis=1, inplace=True)
my_raw_data_df_xrpbtc.drop(['Bid'], axis=1, inplace=True)
my_raw_data_df_xrpbtc.drop(['Low'], axis=1, inplace=True)
my_raw_data_df_xrpbtc.drop(['High'], axis=1, inplace=True)
my_raw_data_df_xrpbtc.drop(['Mid'], axis=1, inplace=True)

#Calculate SMA values to create buy-sell signal
my_raw_data_df_xrpbtc['SMA21'] = my_raw_data_df_xrpbtc['Last'].rolling(21).mean()
my_raw_data_df_xrpbtc['SMA55'] = my_raw_data_df_xrpbtc['Last'].rolling(55).mean()
my_raw_data_df_xrpbtc['SMA200'] = my_raw_data_df_xrpbtc['Last'].rolling(200).mean()

#Check for each day if buy signal holds BUY if sell signal holds SELL
for idx,kitem in my_raw_data_df_xrpbtc.iterrows():

    if (kitem['SMA21'] >= kitem['Last']) is True: #buy signal
        print("buy0")

        if my_portfolio['BTC'] > 0 is True:
            print("buy1")

    if (kitem['Last'] * my_portfolio['XRP']) >= (my_portfolio['BTC'] * 1.05) is True: #sell signal
        print("sell0")

        if my_portfolio['XRP'] > 0 is True:
            print("sell1")

我知道有很多行为true,但是我的代码从未输入此代码路径,因此它不会打印出我期望的内容。

任何人都可以帮助/评论可能出什么问题吗?

1 个答案:

答案 0 :(得分:1)

原因是您的比较是错误的。 kitem['SMA21'] >= kitem['Last']的结果将是numpy.bool_。当您使用is将其与True进行比较时,由于它不是同一对象,因此将失败。

如果您将比较更改为==,它将按预期工作:

if (kitem['SMA21'] >= kitem['Last']) == True: