大熊猫的逻辑运算问题

时间:2020-04-16 15:36:23

标签: python python-3.x pandas

我有以下代码:

import pandas as pd
from pandas import datetime
from pandas import DataFrame as df
from pandas_datareader import data as web
import datetime
import numpy as np

stock = '^GSPC'
start = datetime.date(2018,1,1)
end = datetime.date.today()

data = web.DataReader(stock, 'yahoo',start, end)

这将生成以下内容:

                   High          Low  ...      Volume    Adj Close
Date                                  ...                         
2018-01-02  2695.889893  2682.360107  ...  3367250000  2695.810059
2018-01-03  2714.370117  2697.770020  ...  3538660000  2713.060059
2018-01-04  2729.290039  2719.070068  ...  3695260000  2723.989990
2018-01-05  2743.449951  2727.919922  ...  3236620000  2743.149902
2018-01-08  2748.510010  2737.600098  ...  3242650000  2747.709961
                ...          ...  ...         ...          ...
2020-04-08  2760.750000  2663.300049  ...  5856370000  2749.979980
2020-04-09  2818.570068  2762.360107  ...  7880140000  2789.820068
2020-04-13  2782.459961  2721.169922  ...  5274310000  2761.629883
2020-04-14  2851.850098  2805.100098  ...  5567400000  2846.060059
2020-04-15  2801.879883  2761.540039  ...  5203390000  2783.360107

[575 rows x 6 columns]

我们具有以下布尔逻辑:

(data['Close'].shift(2) < data['Open'].shift(1)) & (data['Close'].shift(1) > data['Open'].shift(2))

逻辑如下: 昨天的收盘价>今天的收盘价and今天的收盘价>昨天的收盘价。

一张描述我要做什么的图片,像这样:

但是当我运行布尔值时,它给了我:

   2020-04-03     True

那是不正确的,它应该看起来像图片。我确定布尔逻辑存在问题。对于您所提供的逻辑方面的帮助,我将不胜感激。


我想要一系列这样的输出:

2020-04-03     True
2020-04-06    False
2020-04-07    False
2020-04-08    False
2020-04-09    False
2020-04-13    False
2020-04-14    False
2020-04-15    False
dtype: bool

1 个答案:

答案 0 :(得分:1)

只需将您的条件更改为(data['Close'].shift(2) > data['Open'].shift(1)) & (data['Close'].shift(1) > data['Open'].shift(2))。 这里是一个示例:

data['Closeshift2'] = data['Close'].shift(2)
data['OpenShift1'] = data['Open'].shift(1)
data['CloseShift1'] = data['Close'].shift(1)
data['OpenShift2'] = data['Open'].shift(2)
data['Bool']  = (data['Closeshift2'] > data['OpenShift1']) & (data['CloseShift1'] > data['OpenShift2'])
data[-11:-8]

结果为:

            High        Low         Open        Close       Volume      Adj Close   Closeshift2 OpenShift1  CloseShift1 OpenShift2  Bool
Date                                            
2020-04-01  2522.750000 2447.489990 2498.080078 2470.500000 5947900000  2470.500000 2626.649902 2614.689941 2584.590088 2558.979980 True
2020-04-02  2533.219971 2455.790039 2458.540039 2526.899902 6454990000  2526.899902 2584.590088 2498.080078 2470.500000 2614.689941 False
2020-04-03  2538.179932 2459.959961 2514.919922 2488.649902 6087190000  2488.649902 2470.500000 2458.540039 2526.899902 2498.080078 True

这是您在图片中显示的结果