-1

我已经计算了 BTC 的 RSI,效果很好。我想在我的数据框中添加一个新列 [Position],它指示我当前的位置是多头还是空头。现在我正在尝试做一个循环,如果我在做多或做空 BTC,它应该给我输出。思路如下:如果 RSI 处于超买状态 (>70) 并再次跌破 70,则输出头寸应为空头。如果 Rsi 处于超卖状态 (<30) 并开始升至 30 以上,则信号应为多头。如果 RSI 正在上升并且最后一个信号很长,我希望介于两者之间的所有值也很长,直到出现短信号(反之亦然)。

此外,在 2016 年 3 月 13 日计算的第一个 RSI (时间序列的开始)是 40.41 并且正在上升,这就是为什么如果在生成短信号之前的第一个值设置为 Long 会很棒,我没有整合在我的代码中,有人知道如何实现吗?

我的代码如下所示:

import pandas as pd
import numpy as np
import datetime
import matplotlib.pyplot as plt

from pandas_datareader import data as pdr

btc = pdr.get_data_yahoo('BTC-USD', 
                          start=datetime.datetime(2016, 2, 28), 
                          end=datetime.datetime(2020, 2, 27))

btc.tail()

btc = btc.reset_index()

def computeRSI (data, time_window):
    diff = data.diff(1).dropna()        # diff in one field(one day)

    #this preservers dimensions off diff values
    up_chg = 0 * diff
    down_chg = 0 * diff

    # up change is equal to the positive difference, otherwise equal to zero
    up_chg[diff > 0] = diff[ diff>0 ]

    # down change is equal to negative deifference, otherwise equal to zero
    down_chg[diff < 0] = diff[ diff < 0 ]

    # calculate EMAs
    up_chg_avg   = up_chg.ewm(com=time_window-1 , min_periods=time_window).mean()
    down_chg_avg = down_chg.ewm(com=time_window-1 , min_periods=time_window).mean()

    rs = abs(up_chg_avg/down_chg_avg)
    rsi = 100 - 100/(1+rs)
    return rsi

btc['RSI'] = computeRSI(btc['Close'], 14)

# get rid of the first 14 NA values
rsibtc = btc[-1448:]

rsibtc.head()

Position = []

for i in range(0,rsibtc.shape[0]):
    if rsibtc['RSI'].iloc[i] < 70 and rsibtc['RSI'].iloc[i-1] >70
        Position.append('Short')
    elif rsibtc['RSI'].iloc[i] >30 and rsibtc['RSI'].iloc[i-1]<30
        Position.append('Long')
    else Position.append(Position.iloc[i-1])

rsibtc['Position'] = Position
rsibtc.tail()

循环给了我一个语法错误......有人可以告诉我如何让这个循环运行吗?

非常感谢您的支持!我感谢你们的每一个想法!

一切顺利,保持保存!

4

1 回答 1

-1

马蒂亚斯,

看起来循环中的if语句for是导致语法错误的语句。它们的格式不正确。if 谓词后应该有一个冒号。所以我为你重写了它:

for i in range(0,rsibtc.shape[0]):
    if rsibtc['RSI'].iloc[i] < 70 and rsibtc['RSI'].iloc[i-1] > 70:
        Position.append('Short')
    elif rsibtc['RSI'].iloc[i] > 30 and rsibtc['RSI'].iloc[i-1] < 30:
        Position.append('Long')
    else:
        Position.append(Position.iloc[i-1])
于 2020-04-08T11:58:48.583 回答