遍历股价python的行和列

时间:2018-08-31 15:30:31

标签: python python-3.x

我下面有一个代码

result, diff = [], []

for index, row in final.iterrows():
    for column in final.columns:
        if ((final['close'] - final['open']) > 20):
            diff = final['close'] - final['open']
            result = 1
        elif ((final['close'] - final['open']) < -20):
            diff = final['close'] - final['open']
            result = -1
        elif (-20 < (final['close'] - final['open']) < 20 ):
            diff = final['close'] - final['open']
            result = 0
        else:
            continue

目的是对于每个时间戳,检查收盘价-开盘价是否大于20点,然后为其分配买入价。如果小于-20,则分配一个卖出价格;如果介于两者之间,则分配一个0。

我收到此错误

The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
[Finished in 35.418s

1 个答案:

答案 0 :(得分:0)

pandas有经验的人会给出更好的答案,但是由于没人在这里回答我的问题。通常,您不想直接使用pandas.Dataframes进行迭代,因为这样做会达到目的。 pandas解决方案看起来更像:

import pandas as pd

data = {
    'symbol': ['WZO', 'FDL', 'KXW', 'GYU', 'MIR', 'YAC', 'CDE', 'DSD', 'PAM', 'BQE'],
    'open': [356, 467, 462, 289, 507, 654, 568, 646, 440, 625],
    'close': [399, 497, 434, 345, 503, 665, 559, 702, 488, 608]
}
df = pd.DataFrame.from_dict(data)
df['diff'] = df['close'] - df['open']
df.loc[(df['diff'] < 20) & (df['diff'] > -20), 'result'] = 0
df.loc[df['diff'] >= 20, 'result'] = 1
df.loc[df['diff'] <= -20, 'result'] = -1

df现在包含:

  symbol  open  close  diff  result
0    WZO   356    399    43     1.0
1    FDL   467    497    30     1.0
2    KXW   462    434   -28    -1.0
3    GYU   289    345    56     1.0
4    MIR   507    503    -4     0.0
5    YAC   654    665    11     0.0
6    CDE   568    559    -9     0.0
7    DSD   646    702    56     1.0
8    PAM   440    488    48     1.0
9    BQE   625    608   -17     0.0

关于您的代码,我将从上面重复我的评论:您正在row进行迭代,但是随后在您的条件下使用整个DataFrame final。我认为您打算在那里row。您无需遍历按索引获取值的列。当final['close'] - final['open']恰好为20时,您的条件会丢失。result, diff = [], []在顶部,但随后在循环中被分配为整数。也许您想要result.append()