예제 #1
0
def rsi(prices):
    df = pd.DataFrame()

    df['rsi_6'] = RSI(prices, timeperiod=6)
    df['rsi_12'] = RSI(prices, timeperiod=12)
    df['rsi_24'] = RSI(prices, timeperiod=24)

    #df['rsi_14'] = RSI(prices, timeperiod=14)

    return df
예제 #2
0
def ChartKBar_RSI_1(KBar,longPeriod=27,shortPeriod=9):
    # 計算RSI(長短線) 以及中介線 50
    KBar['RSI_long']=RSI(KBar,timeperiod=longPeriod)
    KBar['RSI_short']=RSI(KBar,timeperiod=shortPeriod)
    KBar['Middle']=np.array([50]*len(KBar['time']))
    # 將K線轉為DataFrame
    Kbar_df=KbarToDf(KBar)
    # 將副圖繪製出來
    addp=[]
    addp.append(mpf.make_addplot(Kbar_df['RSI_long'],panel='lower',color='red',secondary_y=False))
    addp.append(mpf.make_addplot(Kbar_df['RSI_short'],panel='lower',color='green',secondary_y=False))
    addp.append(mpf.make_addplot(Kbar_df['Middle'],panel='lower',color='black',secondary_y=False))
    # 開始繪圖
    ChartKBar(KBar,addp,False)
예제 #3
0
    def _xform_data(self, df):
        columns = []
        tables_ = data.get_tables(self.hypers.arbitrage)
        percent = self.hypers.pct_change
        for table in tables_:
            name, cols, ohlcv = table['name'], table['cols'], table.get(
                'ohlcv', {})
            columns += [self._diff(df[f'{name}_{k}'], percent) for k in cols]

            # Add extra indicator columns
            if ohlcv and self.hypers.indicators:
                ind = pd.DataFrame()
                # TA-Lib requires specifically-named columns (OHLCV)
                for k, v in ohlcv.items():
                    ind[k] = df[f"{name}_{v}"]
                columns += [
                    ## Original indicators from some boilerplate repo I started with
                    self._diff(SMA(ind, timeperiod=15), percent),
                    self._diff(SMA(ind, timeperiod=60), percent),
                    self._diff(RSI(ind, timeperiod=14), percent),
                    self._diff(ATR(ind, timeperiod=14), percent),

                    ## Indicators from the book "How to Day Trade For a Living". Not sure which are more solid...
                    ## Price, Volume, 9-EMA, 20-EMA, 50-SMA, 200-SMA, VWAP, prior-day-close
                    # self._diff(EMA(ind, timeperiod=9)),
                    # self._diff(EMA(ind, timeperiod=20)),
                    # self._diff(SMA(ind, timeperiod=50)),
                    # self._diff(SMA(ind, timeperiod=200)),
                ]

        states = np.nan_to_num(np.column_stack(columns))
        prices = df[data.target].values
        # Note: don't scale/normalize here, since we'll normalize w/ self.price/step_acc.cash after each action
        return states, prices
예제 #4
0
    def rsi(self, data, length, price_input='close'):
        rsi_values = {'success': True, 'result': {'data': None, 'current': None, 'state': None}}

        data_copy = data.copy()

        try:
            results = RSI(data_copy, timeperiod=length, prices=price_input)

            rsi_values['result']['data'] = results

            rsi_values['result']['current'] = results[-1]

            if rsi_values['result']['current'] > 50:
                rsi_state = 'positive'

            elif rsi_values['result']['current'] == 50:
                rsi_state = 'even'

            else:
                rsi_state = 'negative'

            rsi_values['result']['state'] = rsi_state

            if self.serialize_numpy == True:
                rsi_values['result']['data'] = rsi_values['result']['data'].tolist()

        except Exception as e:
            logger.exception('Exception while calculating RSI.')
            logger.exception(e)

            rsi_values['success'] = False

        finally:
            return rsi_values
예제 #5
0
def ChartKBar_RSI_2(KBar,RSIPeriod,upper,lower):
    # 計算RSI 以及 買超賣超線 
    KBar['RSI']=RSI(KBar,timeperiod=RSIPeriod)
    KBar['Ceil']=np.array([upper]*len(KBar['time']))
    KBar['Floor']=np.array([lower]*len(KBar['time']))
    # 將K線轉為DataFrame
    Kbar_df=KbarToDf(KBar)
    # 將副圖繪製出來
    addp=[]
    addp.append(mpf.make_addplot(Kbar_df['RSI'],panel='lower',color='black',secondary_y=False))
    addp.append(mpf.make_addplot(Kbar_df['Ceil'],panel='lower',color='red',secondary_y=False))
    addp.append(mpf.make_addplot(Kbar_df['Floor'],panel='lower',color='red',secondary_y=False))
    # 開始繪圖
    ChartKBar(KBar,addp,False)
예제 #6
0
    def calc_rsi(self, data, period_count, price_input='close'):
        rsi_values = {
            'Exception': False,
            'result': {
                'data': None,
                'current': None,
                'state': None
            }
        }

        try:
            results = RSI(data, timeperiod=period_count, prices=price_input)

            rsi_values['result']['data'] = results  #[-1]

            rsi_values['result']['current'] = results[-1]

            if rsi_values['result']['current'] > 50:
                rsi_state = 'positive'

            elif rsi_values['result']['current'] == 50:
                rsi_state = 'even'

            else:
                rsi_state = 'negative'

            rsi_values['result']['state'] = rsi_state

        except Exception as e:
            logger.exception('Exception while calculating RSI.')
            logger.exception(e)

            rsi_values['Exception'] = True

        finally:
            return rsi_values
예제 #7
0
파일: rsi.py 프로젝트: co2meal/haedong_test
    def __init__(self, candles: dict, indicator_info: dict):
        self.candles = candles
        self.LENGTH = indicator_info[LENGTH]

        self.RSI = RSI(candles, timeperiod=self.LENGTH)
예제 #8
0
import sys

# 登入帳號密碼(讀者須修正該帳號密碼為自己的,否則無法執行策略)
GOrder.Login('TestAccount', 'TestPasswd')
# 建立部位管理物件
OrderRecord = Record()
# 取得回測參數、移動停損點數
StartDate = sys.argv[1]
EndDate = sys.argv[2]
RSIPeriod = int(sys.argv[3])
Ceil = float(sys.argv[4])
Floor = float(sys.argv[5])
MoveStopLoss = float(sys.argv[6])
# 回測取報價物件
KBar = GOrder.GetTAKBar(StartDate, EndDate, 'TXF', 'Future', '0', '5')
KBar['RSI'] = RSI(KBar, timeperiod=RSIPeriod)
KBar['Ceil'] = np.array([Ceil] * len(KBar['time']))
KBar['Floor'] = np.array([Floor] * len(KBar['time']))
# 開始回測
for n in range(0, len(KBar['time']) - 1):
    # 先判斷long MA的上一筆值是否為空值 再接續判斷策略內容
    if not np.isnan(KBar['RSI'][n - 1]):
        # 如果無未平倉部位
        if OrderRecord.GetOpenInterest() == 0:
            # RSI 向下突破超買界線
            if KBar['RSI'][n - 1] <= KBar['Floor'][n] and KBar['RSI'][
                    n] > KBar['Floor'][n]:
                OrderRecord.Order('Buy', KBar['product'][n + 1],
                                  KBar['time'][n + 1], KBar['open'][n + 1], 1)
                OrderPrice = KBar['open'][n + 1]
                StopLossPoint = OrderPrice - MoveStopLoss
예제 #9
0
import sys

# 登入帳號密碼(讀者須修正該帳號密碼為自己的,否則無法執行策略)
GOrder.Login('TestAccount', 'TestPasswd')
# 建立部位管理物件
OrderRecord = Record()
# 取得回測參數、移動停損點數
StartDate = sys.argv[1]
EndDate = sys.argv[2]
LongRSIPeriod = int(sys.argv[3])
ShortRSIPeriod = int(sys.argv[4])
MoveStopLoss = float(sys.argv[5])
# 回測取報價物件
KBar = GOrder.GetTAKBar(StartDate, EndDate, '3008', 'Stock', '0', '10')
# 計算 RSI指標 以及定義中線
KBar['RSI_long'] = RSI(KBar, timeperiod=LongRSIPeriod)
KBar['RSI_short'] = RSI(KBar, timeperiod=ShortRSIPeriod)
KBar['Middle'] = np.array([50] * len(KBar['time']))
# 開始回測
for n in range(0, len(KBar['time']) - 1):
    # 先判斷long MA的上一筆值是否為空值 再接續判斷策略內容
    if not np.isnan(KBar['RSI_long'][n - 1]):
        # 如果無未平倉部位
        if OrderRecord.GetOpenInterest() == 0:
            # short RSI 大於 long RSI 並且 long RSI 大於 50
            if KBar['RSI_short'][n - 1] <= KBar['RSI_long'][
                    n - 1] and KBar['RSI_short'][n] > KBar['RSI_long'][
                        n] and KBar['RSI_long'][n] > KBar['Middle'][n]:
                OrderRecord.Order('Buy', KBar['product'][n + 1],
                                  KBar['time'][n + 1], KBar['open'][n + 1], 1)
                OrderPrice = KBar['open'][n + 1]