迭代股票价格python的行和列

问题描述 投票:0回答:1

我有一个代码如下

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
python python-3.x
1个回答
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()

© www.soinside.com 2019 - 2024. All rights reserved.