Пример #1
0
def app():

    st.write("""
    # S&P 500 Stock Analyzer
    Shown below are the **Fundamentals**, **News Sentiment**, **Bollinger Bands** and **Comprehensive Report (Compared with SPY as a whole as benchmark)** of your selected stock!
       
    """)
    st.markdown("***")
    st.sidebar.header('User Input Parameters')

    symbol, start, end = user_input_features()
    start = pd.to_datetime(start)
    end = pd.to_datetime(end)
    #symbol1 = get_symbol(symbol.upper())

    #st.subheader(symbol1)

    stock = finvizfinance(symbol.lower())
    stock_chart = stock.ticker_charts()
    st.image(stock_chart)

    # Read data
    data = yf.download(symbol, start, end, threads=False)

    # ## SMA and EMA
    #Simple Moving Average
    data['SMA'] = talib.SMA(data['Adj Close'], timeperiod=20)

    # Exponential Moving Average
    data['EMA'] = talib.EMA(data['Adj Close'], timeperiod=20)

    # Plot
    st.subheader(f"""
              Simple Moving Average vs. Exponential Moving Average\n {symbol}
              """)
    st.line_chart(data[['Adj Close', 'SMA', 'EMA']])

    # Bollinger Bands
    data['upper_band'], data['middle_band'], data['lower_band'] = talib.BBANDS(
        data['Adj Close'], timeperiod=20)

    # Plot
    st.subheader(f"""
              Bollinger Bands\n {symbol}
              """)
    st.line_chart(
        data[['Adj Close', 'upper_band', 'middle_band', 'lower_band']])

    # ## MACD (Moving Average Convergence Divergence)
    # MACD
    data['macd'], data['macdsignal'], data['macdhist'] = talib.MACD(
        data['Adj Close'], fastperiod=12, slowperiod=26, signalperiod=9)

    # Plot
    st.subheader(f"""
              Moving Average Convergence Divergence\n {symbol}
              """)
    st.line_chart(data[['macd', 'macdsignal']])

    # ## RSI (Relative Strength Index)
    # RSI
    data['RSI'] = talib.RSI(data['Adj Close'], timeperiod=14)

    # Plot
    st.subheader(f"""
              Relative Strength Index\n {symbol}
              """)
    st.line_chart(data['RSI'])

    st.markdown("***")

    st.subheader("Fundamentals: ")
    st.dataframe(get_fundamentals(symbol))
    st.markdown("***")

    # ## Latest News
    st.subheader("Latest News: ")
    st.table(get_news(symbol).head(5))
    st.markdown("***")

    # ## Recent Insider Trades
    st.subheader("Recent Insider Trades: ")
    st.table(get_insider(symbol).head(5))
    st.markdown("***")

    st.write("Generating comprehensive stock report...")
    st.write("**please wait for some time... **")
    st.write(
        "This section will compare the historical performance of your selected stock with SPDR S&P 500 Trust ETF (Ticker: SPY) as benchmark."
    )
    stock_report(symbol)
    # ## Stock report

    st.subheader(f"""**{symbol} Stock Report**""")

    #st.header(symbol + " Stock Report")

    HtmlFile = open("report.html", 'r', encoding='utf-8')
    source_code = HtmlFile.read()
    #print(source_code)
    components.html(source_code, height=9000)

    st.write(
        "Disclaimer: The data are collected from Google, Yahoo Finance and Finviz"
    )
Пример #2
0
    def ZIGZAG(self,
               df,
               minbars=12,
               bb_period=20,
               bb_dev=2.0,
               nan_value=0.0,
               dropna=True,
               level=logging.WARN):
        """Builds a ZIGZAG indicator based on Bollinger Bands overbought and oversell signals

    Keyword arguments:
      df -- Datafeed to apply indicator
      minbars -- Min. number of bars per flip to avoid discarding (default 12)
      bb_period -- Bollinger bands period (default 20)
      bb_dev -- Bollinger bands deviation (default 2.0)
      nan_value -- Values for zigzag indicator during search phase (default 0.0)
      dropna -- Flag to delete NaN values, else fill them with nan_value
      level -- logging level (default WARN)
    """
        class ActionCtrl():
            class ActionType(Enum):
                NoActions = 0
                SearchingHigh = 1
                SearchingLow = 2

            def __init__(self, high, low, idx, delta, level=logging.WARN):
                self.__logger = logging.getLogger(__name__)
                self.__logger.setLevel(level)
                self.curr = ActionCtrl.ActionType.NoActions
                self.last_high = high
                self.last_high_idx = idx
                self.beforelast_high = high
                self.beforelast_high_idx = idx
                self.last_swing_high_idx = idx
                self.last_low = low
                self.last_low_idx = idx
                self.beforelast_low = low
                self.beforelast_low_idx = idx
                self.last_swing_low_idx = idx
                self.delta = delta
                self.events = ZIGZAG_Events()
                self.__logger.debug(
                    'New action at idx={}: last_high={}, last_low={}, min-delta={}'
                    .format(idx, self.last_high, self.last_low, self.delta))

            #---end action::__init__

            def __result(self):
                if self.curr == ActionCtrl.ActionType.SearchingHigh:
                    return 'high'
                elif self.curr == ActionCtrl.ActionType.SearchingLow:
                    return 'low'
                return 'no-action'

            #---end action::__result

            # this function updates MAX|MIN values with last recorded depending on the current action
            def zigzag(self, x, df):
                log = 'Procesing [{}]:'.format(x.name)
                self.events.clear()

                # check if HIGH must be updated
                max_value = x.HIGH
                if self.curr == ActionCtrl.ActionType.SearchingHigh and max_value > self.last_high:
                    #self.beforelast_high = self.last_high
                    #self.beforelast_high_idx = self.last_high_idx
                    self.last_high = max_value
                    self.last_high_idx = x.name
                    log += ' new HIGH={}'.format(max_value)
                    self.__logger.debug(log)
                    return self.__result()

                # check if LOW must be updated
                min_value = x.LOW
                if self.curr == ActionCtrl.ActionType.SearchingLow and min_value < self.last_low:
                    #self.beforelast_low = self.last_low
                    #self.beforelast_low_idx = self.last_low_idx
                    self.last_low = min_value
                    self.last_low_idx = x.name
                    log += ' new LOW={}'.format(min_value)
                    self.__logger.debug(log)
                    return self.__result()

                # check if search HIGH starts
                if self.curr != ActionCtrl.ActionType.SearchingHigh and max_value > x.BOLLINGER_HI:
                    _prev_action = self.curr
                    self.events.ZIGZAG_StartMaxSearch = True
                    self.curr = ActionCtrl.ActionType.SearchingHigh
                    # check delta condition
                    curr_delta = (x.name - self.last_high_idx)
                    if _prev_action == ActionCtrl.ActionType.NoActions:
                        # in first swing doesnt apply
                        curr_delta = self.delta + 1
                    if curr_delta < self.delta:
                        log += ' ERR_DELTA \/ ={}'.format(curr_delta)
                        df.at[self.last_high_idx, 'ZIGZAG'] = nan_value
                        df.at[self.last_high_idx, 'ACTION'] = 'high'
                        if max_value > self.last_high:
                            log += ' replace_HIGH @[{}]=>{}'.format(
                                self.last_high_idx, max_value)
                            self.last_high = max_value
                            self.last_high_idx = x.name
                        else:
                            log += ' keep_HIGH @[{}]=>{}'.format(
                                self.last_high_idx, self.last_high)
                        df.at[self.last_low_idx, 'ZIGZAG'] = nan_value
                        df.at[self.last_low_idx, 'ACTION'] = 'high'
                        log += ' remove LOW @[{}]'.format(self.last_low_idx)
                        self.last_low = self.beforelast_low
                        self.last_low_idx = self.beforelast_low_idx
                        self.__logger.info(log)
                    else:
                        # save last low
                        df.at[self.last_low_idx, 'ZIGZAG'] = self.last_low
                        self.beforelast_low = self.last_low
                        self.beforelast_low_idx = self.last_low_idx
                        # starts high recording
                        #self.beforelast_high = self.last_high
                        #self.beforelast_high_idx = self.last_high_idx
                        self.last_high = max_value
                        self.last_high_idx = x.name
                        log += ' save LOW @[{}]={}, new HIGH=>{}'.format(
                            self.last_low_idx, self.last_low, max_value)
                        self.__logger.debug(log)
                    return self.__result()

                # check if search LOW starts
                if self.curr != ActionCtrl.ActionType.SearchingLow and min_value < x.BOLLINGER_LO:
                    _prev_action = self.curr
                    self.events.ZIGZAG_StartMinSearch = True
                    self.curr = ActionCtrl.ActionType.SearchingLow
                    # check delta condition
                    curr_delta = (x.name - self.last_low_idx)
                    if _prev_action == ActionCtrl.ActionType.NoActions:
                        # in first swing doesnt apply
                        curr_delta = self.delta + 1
                    if curr_delta < self.delta:
                        log += ' ERR_DELTA /\ ={}'.format(curr_delta)
                        df.at[self.last_low_idx, 'ZIGZAG'] = nan_value
                        df.at[self.last_low_idx, 'ACTION'] = 'low'
                        if min_value < self.last_low:
                            log += ' replace_LOW @[{}]=>{}'.format(
                                self.last_low_idx, min_value)
                            self.last_low = min_value
                            self.last_low_idx = x.name
                        else:
                            log += ' keep_LOW @[{}]=>{}'.format(
                                self.last_low_idx, self.last_low)
                        df.at[self.last_high_idx, 'ZIGZAG'] = nan_value
                        df.at[self.last_high_idx, 'ACTION'] = 'low'
                        log += ' remove HIGH @[{}]'.format(self.last_high_idx)
                        self.last_high = self.beforelast_high
                        self.last_high_idx = self.beforelast_high_idx
                        self.__logger.info(log)
                    else:
                        # save last high
                        df.at[self.last_high_idx, 'ZIGZAG'] = self.last_high
                        self.beforelast_high = self.last_high
                        self.beforelast_high_idx = self.last_high_idx
                        # starts low recording
                        #self.beforelast_low = self.last_low
                        #self.beforelast_low_idx = self.last_low_idx
                        self.last_low = min_value
                        self.last_low_idx = x.name
                        log += ' save HIGH @[{}]={}, new LOW=>{}'.format(
                            self.last_high_idx, self.last_high, min_value)
                        self.__logger.debug(log)
                    return self.__result()

                if self.curr == ActionCtrl.ActionType.SearchingLow:
                    log += ' curr LOW @[{}]=>{}'.format(
                        self.last_low_idx, self.last_low)
                elif self.curr == ActionCtrl.ActionType.SearchingHigh:
                    log += ' curr HIGH @[{}]=>{}'.format(
                        self.last_high_idx, self.last_high)
                self.__logger.debug(log)
                return self.__result()

            #---end action::zigzag

            # registers previous zzpoints and their indexes at current row.Px and row.Px_idx
            def points(self, row, df, nan_value):
                log = 'row [{}] zigzag={}: '.format(row.name, row.ZIGZAG)

                # get last 5 zigzag points
                zzpoints = df.ZIGZAG[(df.index < row.name)
                                     & (df.ZIGZAG != nan_value) &
                                     (df.ACTION.str.contains('in-progress')
                                      == False)]
                # at least requires 6 points, else discard
                if zzpoints.shape[0] < 6:
                    log += 'exit-zzpoints-count={} '.format(zzpoints.shape[0])
                    self.__logger.debug(log)
                    return
                # update rows
                for i in range(1, 7):
                    df.at[row.name, 'P{}'.format(i)] = zzpoints.iloc[-i]
                    df.at[row.name, 'P{}_idx'.format(i)] = zzpoints.index[-i]
                log += 'Updated!! '
                self.__logger.debug(log)

            #---end action::points

        # clear events
        self.__events.clear()

        # copy dataframe and calculate bollinger bands if not yet present
        _df = df.copy()
        _df['BOLLINGER_HI'], _df['BOLLINGER_MA'], _df[
            'BOLLINGER_LO'] = talib.BBANDS(_df.CLOSE,
                                           timeperiod=bb_period,
                                           nbdevup=bb_dev,
                                           nbdevdn=bb_dev,
                                           matype=0)
        _df['BOLLINGER_WIDTH'] = _df['BOLLINGER_HI'] - _df['BOLLINGER_LO']
        boll_b = (_df.CLOSE - _df['BOLLINGER_LO']) / _df['BOLLINGER_WIDTH']
        boll_b[np.isnan(boll_b)] = 0.5
        boll_b[np.isinf(boll_b)] = 0.5
        _df['BOLLINGER_b'] = boll_b
        if dropna:
            _df.dropna(inplace=True)
            _df.reset_index(drop=True, inplace=True)
        else:
            _df.fillna(value=nan_value, inplace=True)

        # Initially no actions are in progress, record first high and low values creating an ActionCtrl object
        action = ActionCtrl(
            high=_df['HIGH'][0],  #max(_df['OPEN'][0], _df['CLOSE'][0]), 
            low=_df['LOW'][0],  #min(_df['OPEN'][0], _df['CLOSE'][0]), 
            idx=_df.iloc[0].name,
            delta=minbars,
            level=level)

        _df['ZIGZAG'] = nan_value
        _df['ACTION'] = 'no-action'
        _df['ACTION'] = _df.apply(lambda x: action.zigzag(x, _df), axis=1)

        # fills last element as pending
        if _df.ZIGZAG.iloc[-1] == nan_value:
            if _df.ACTION.iloc[-1] == 'high':
                _df.at[action.last_high_idx, 'ZIGZAG'] = action.last_high
                _df.at[action.last_high_idx, 'ACTION'] = 'high-in-progress'
            else:
                _df.at[action.last_low_idx, 'ZIGZAG'] = action.last_low
                _df.at[action.last_low_idx, 'ACTION'] = 'low-in-progress'

        # now adds point p1 to p6 backtrace of values and indexes:
        for i in range(1, 7):
            _df['P{}'.format(i)] = nan_value
            _df['P{}_idx'.format(i)] = 0

        _df.apply(lambda x: action.points(x, _df, nan_value), axis=1)
        self.__df = _df
        self.__action = action
        return self.__df, self.__action.events
Пример #3
0
def bbands(source, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0):
    return talib.BBANDS(source, timeperiod, nbdevup, nbdevdn, matype)
Пример #4
0
# ## SMA and EMA
#Simple Moving Average
data['SMA'] = ta.SMA(data['Adj Close'], timeperiod=20)

# Exponential Moving Average
data['EMA'] = ta.EMA(data['Adj Close'], timeperiod=20)

# Plot
data[['Adj Close', 'SMA', 'EMA']].plot(figsize=(10, 5))
plt.subplots()
plt.show()

# ## Bollinger Bands
# Bollinger Bands
data['upper_band'], data['middle_band'], data['lower_band'] = ta.BBANDS(
    data['Adj Close'], timeperiod=20)

# Plot
data[['Adj Close', 'upper_band', 'middle_band',
      'lower_band']].plot(figsize=(10, 5))
plt.show()

# ## MACD (Moving Average Convergence Divergence)
# MACD
data['macd'], data['macdsignal'], data['macdhist'] = ta.MACD(data['Adj Close'],
                                                             fastperiod=12,
                                                             slowperiod=26,
                                                             signalperiod=9)
data[['macd', 'macdsignal']].plot(figsize=(10, 5))

plt.show()
    def process_indextools(self):
        """======================更新辅助指标=================="""

        ###更新closes
        close = self.newBar['close']
        self.closes.append(close)
        if len(self.closes) < self.macd_len: return  #如果收盘价列表不够用于计算,则继续添加
        if len(self.fenxingTuples) <= 1: return  #如果两个分型都没有,则继续等待分型
        now_fenxing = self.fenxingTuples[-1]
        ###判断分型是否更新
        ###未更新
        if self.last_fenxing_datetime == now_fenxing[0]:

            self.macd_area_buffer.append(
                talib.MACD(np.array(self.closes))[-1][-1])  #buffer添加一个

        ###更新了
        else:
            ###替代前分型
            if self.last_fenxing_type == now_fenxing[2]:

                #macd处理
                self.macd_area_buffer.append(
                    talib.MACD(np.array(self.closes))[-1][-1])  #buffer添加一个
                self.macd_area_backup.extend(
                    self.macd_area_buffer)  #backup加入buffer
                macd_area = sum(self.macd_area_backup)  #计算
                #self.macd_areas[-1] = macd_area#替换最后一个红蓝柱面积
                self.macd_areas[-1] = (now_fenxing[0], macd_area)  #替换最后一个红蓝柱面积
                self.macd_area_buffer = []  #清空buffer

                #bolling处理
                ceil = talib.BBANDS(np.array(self.closes))[0][-2]
                floor = talib.BBANDS(np.array(self.closes))[-1][-2]
                self.powerful_area = ((now_fenxing[1] > ceil) |
                                      (now_fenxing[1] < floor))
                #self.bolling_fenxing[-1] = self.powerful_area
                self.bolling_fenxing[-1] = (now_fenxing[0], self.powerful_area)

                #判断变量
                self.last_fenxing_datetime = now_fenxing[0]

            ###增加新的分型
            else:

                #macd处理
                self.macd_area_backup = []  #清空backup
                self.macd_area_buffer.append(
                    talib.MACD(np.array(self.closes))[-1][-1])  #buffer添加一个
                self.macd_area_backup.extend(
                    self.macd_area_buffer)  #backup加入buffer
                macd_area = sum(self.macd_area_backup)
                #self.macd_areas.append(sum(self.macd_area_backup))#增加一个红蓝柱面积
                self.macd_areas.append((now_fenxing[0], macd_area))  #增加一个红蓝柱面积
                self.macd_area_buffer = []  #清空buffer

                #bolling处理
                ceil = talib.BBANDS(np.array(self.closes))[0][-2]
                floor = talib.BBANDS(np.array(self.closes))[-1][-2]
                self.powerful_area = ((now_fenxing[1] > ceil) |
                                      (now_fenxing[1] < floor))
                #self.bolling_fenxing.append(self.powerful_area)
                self.bolling_fenxing.append(
                    (now_fenxing[0], self.powerful_area))

                #判断变量
                self.last_fenxing_datetime = now_fenxing[0]
                self.last_fenxing_type = now_fenxing[2]
    def test_case(self):
        close, open, ma2 = [], [], []
        pre_ma2 = []
        true_test = []
        boll = {
                'upper': [],
                'middler': [],
                'lower': []
                }

        boll3 = {
                'upper': [],
                'middler': [],
                'lower': []
                }

        class DemoStrategy(Strategy):
            def on_init(self, ctx):
                """初始化数据""" 
                ctx.ma2 = MA(ctx.close, 2)
                ctx.boll = BOLL(ctx.close, 2)

            def on_bar(self, ctx):
                if ctx.curbar>=2:
                    ## @todo + - * /
                    true_test.append(ctx.ma2-0 == ctx.ma2[0])
                    
                pre_ma2.append(ctx.ma2[3])
                ma2.append(ctx.ma2[0])
                close.append(ctx.close[0])
                open.append(ctx.open[0])
                boll['upper'].append(ctx.boll['upper'][0])
                boll['middler'].append(ctx.boll['middler'][0])
                boll['lower'].append(ctx.boll['lower'][0])
                boll3['upper'].append(ctx.boll['upper'][3])
                boll3['middler'].append(ctx.boll['middler'][3])
                boll3['lower'].append(ctx.boll['lower'][3])


            def on_final(self, ctx):
                return

            def on_exit(self, ctx):
                return

        ## @todo 滚动的时候无法通过测试
        set_pcontracts([pcontract('BB.SHFE', '1.Minute')], 0)
        add_strategy([DemoStrategy('A1')])
        run()
        self.assertTrue(all(true_test), "指标转化错误!")
        logger.info('----------------- 指标转化测试成功 -------------------')

        # 分别测试单值和多值指标函数。
        source_ma2 = talib.SMA(np.asarray(close), 2)
        true_test, false_test = [], []
        for i in xrange(0, len(close)):
            if i >=  1:
                true_test.append(ma2[i] == source_ma2[i])
            else:
                false_test.append(ma2[i] == ma2[i])
        self.assertFalse(any(false_test), "单值指标正例测试失败!")
        self.assertTrue(all(true_test), "单值指标正例测试失败!")
        source_ma2 = talib.SMA(np.asarray(open), 2)
        true_test, false_test = [], []
        for i in xrange(0, len(open)):
            if i >=  1:
                true_test.append(ma2[i] == source_ma2[i])
            else:
                false_test.append(ma2[i] == ma2[i])
        self.assertFalse(any(false_test), "单值指标反例测试失败!")
        self.assertFalse(all(true_test), "单值指标反例测试失败!")
        logger.info('----------------- 单值指标测试成功 -------------------')

        true_test, false_test = [], []
        source_ma2 = talib.SMA(np.asarray(close), 2)
        for i in xrange(0, len(close)):
            if i >= 4:
                true_test.append(pre_ma2[i] == source_ma2[i-3])
            else:
                # 指标序列变量的默认值为nan
                false_test.append(pre_ma2[i] == pre_ma2[i])
        self.assertTrue(all(true_test), "单值指标回溯正例测试成功")
        self.assertFalse(any(false_test), "单值指标回溯正例测试成功")
        true_test, false_test = [], []
        source_ma2 = talib.SMA(np.asarray(open), 2)
        for i in xrange(0, len(close)):
            if i >= 4:
                true_test.append(pre_ma2[i] == source_ma2[i-3])
            else:
                # 指标序列变量的默认值为nan
                false_test.append(pre_ma2[i] == pre_ma2[i])
        self.assertFalse(all(true_test), "单值指标回溯反例测试成功")
        self.assertFalse(any(false_test), "单值指标回溯反例测试成功")
        logger.info('----------------- 单值指标回溯测试成功 -------------------')

        #
        u, m, l = talib.BBANDS(np.asarray(close), 2, 2, 2)
        true_test, false_test = [], []
        for i in xrange(0, len(close)):
            if i >=  1:
                true_test.append(boll['upper'][i] == u[i])
                true_test.append(boll['middler'][i] == m[i])
                true_test.append(boll['lower'][i] == l[i])
            else:
                false_test.append(boll['upper'][i] == boll['upper'][i])
                false_test.append(boll['middler'][i] == boll['middler'][i])
                false_test.append(boll['lower'][i] == boll['lower'][i])
        self.assertFalse(any(false_test), "多值指标正例测试失败!")
        self.assertTrue(all(true_test), "多值指标正例测试失败!")
        u, m, l = talib.BBANDS(np.asarray(open), 2, 2, 2)
        true_test, false_test = [], []
        for i in xrange(0, len(close)):
            if i >=  1:
                true_test.append(boll['upper'][i] == u[i])
                true_test.append(boll['middler'][i] == m[i])
                true_test.append(boll['lower'][i] == l[i])
            else:
                false_test.append(boll['upper'][i] == boll['upper'][i])
                false_test.append(boll['middler'][i] == boll['middler'][i])
                false_test.append(boll['lower'][i] == boll['lower'][i])
        self.assertFalse(any(false_test), "多值指标反例测试失败!")
        self.assertFalse(all(true_test), "多值指标反例测试失败!")
        logger.info('----------------- 多值指标测试成功 -------------------')


        true_test, false_test = [], []
        u, m, l = talib.BBANDS(np.asarray(close), 2, 2, 2)
        for i in xrange(0, len(close)):
            if i >= 4:
                true_test.append(boll3['upper'][i] == u[i-3])
            else:
                false_test.append(boll3['upper'][i] == boll3['upper'][i])
        self.assertTrue(all(true_test), "多值指标回溯正例测试成功")
        self.assertFalse(any(false_test), "多值指标回溯正例测试成功")
        true_test, false_test = [], []
        u, m, l = talib.BBANDS(np.asarray(open), 2, 2, 2)
        for i in xrange(0, len(close)):
            if i >= 4:
                true_test.append(boll3['upper'][i] == u[i-3])
            else:
                false_test.append(boll3['upper'][i] == boll3['upper'][i])
        self.assertFalse(all(true_test), "多值指标回溯反例测试成功")
        self.assertFalse(any(false_test), "多值指标回溯反例测试成功")
        logger.info('----------------- 多值指标回溯测试成功 -------------------')
Пример #7
0
def math_transform_process(event):
    print(event.widget.get())
    math_transform = event.widget.get()

    upperband, middleband, lowerband = ta.BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)
    fig, axes = plt.subplots(2, 1, sharex=True)
    ax1, ax2 = axes[0], axes[1]
    axes[0].plot(close, 'rd-', markersize=3)
    axes[0].plot(upperband, 'y-')
    axes[0].plot(middleband, 'b-')
    axes[0].plot(lowerband, 'y-')
    axes[0].set_title(math_transform, fontproperties="SimHei")


    if math_transform == '反余弦':
        real = ta.ACOS(close)
        axes[1].plot(real, 'r-')
    elif math_transform == '反正弦':
        real = ta.ASIN(close)
        axes[1].plot(real, 'r-')
    elif math_transform == '反正切':
        real = ta.ATAN(close)
        axes[1].plot(real, 'r-')
    elif math_transform == '向上取整':
        real = ta.CEIL(close)
        axes[1].plot(real, 'r-')
    elif math_transform == '余弦':
        real = ta.COS(close)
        axes[1].plot(real, 'r-')
    elif math_transform == '双曲余弦':
        real = ta.COSH(close)
        axes[1].plot(real, 'r-')
    elif math_transform == '指数':
        real = ta.EXP(close)
        axes[1].plot(real, 'r-')
    elif math_transform == '向下取整':
        real = ta.FLOOR(close)
        axes[1].plot(real, 'r-')
    elif math_transform == '自然对数':
        real = ta.LN(close)
        axes[1].plot(real, 'r-')
    elif math_transform == '常用对数':
        real = ta.LOG10(close)
        axes[1].plot(real, 'r-')
    elif math_transform == '正弦':
        real = ta.SIN(close)
        axes[1].plot(real, 'r-')
    elif math_transform == '双曲正弦':
        real = ta.SINH(close)
        axes[1].plot(real, 'r-')
    elif math_transform == '平方根':
        real = ta.SQRT(close)
        axes[1].plot(real, 'r-')
    elif math_transform == '正切':
        real = ta.TAN(close)
        axes[1].plot(real, 'r-')
    elif math_transform == '双曲正切':
        real = ta.TANH(close)
        axes[1].plot(real, 'r-')

    plt.show()
Пример #8
0
def shaping_ohlc(ohlc, columns, drop=False, bbtp=9, over_rate=0.00035):

    #columns dependency reverse resolution
    cdrr = {
        'O/O': ['O/O', 'ATR/O'],
        'H/O': ['H/O', 'H-L/O', 'ATR/O'],
        'L/O': ['L/O', 'H-L/O', 'ATR/O'],
        'C/O': ['C/O', 'MACDS/O', 'MACDM/O', 'MACDL/O'],
        'O/C': ['O/C'],
        'H/C': ['H/C', 'H-L/C'],
        'L/C': ['L/C', 'H-L/C'],
        'C/C': ['C/C'],
        'H-L/O': ['H-L/O'],
        'H-L/C': ['H-L/C'],
        'O-1/C': ['O-1/C'],
        'H-1/C': ['H-1/C'],
        'L-1/C': ['L-1/C'],
        'C-1/C': ['C-1/C'],
        'PositiveLine':
        ['PositiveLine', 'SignLine', '3SignLine', '6SignLine', '12SignLine'],
        'NegativeLine':
        ['NegativeLine', 'SignLine', '3SignLine', '6SignLine', '12SignLine'],
        'SignLine': ['SignLine'],
        '3SignLine': ['3SignLine'],
        '6SignLine': ['6SignLine'],
        '12SignLine': ['12SignLine'],
        'BB': ['BBUpper', 'BBMiddle', 'BBLower', 'BBOver', 'BBUnder'],
        'BBOver': ['BBOver'],
        'BBUnder': ['BBUnder'],
        'MACDS': ['MACDS'],
        'MACDM': ['MACDM'],
        'MACDL': ['MACDL'],
        'MACDS/O': ['MACDS/O'],
        'MACDM/O': ['MACDM/O'],
        'MACDL/O': ['MACDL/O'],
        'ATR': ['ATR'],
        'ATR/O': ['ATR/O'],
        'RSI': ['RSI'],
        'Time': ['Time'],
        'Over': ['Over', 'Target_Over'],
        '1moku-base': [
            '1moku-base', '1moku-precedent-span1', '1moku-signal1',
            '1moku-signal2', '1moku-signal3', '1moku-signal4', '1moku-signal5',
            '1moku-signal6'
        ],
        '1moku-conversion': [
            '1moku-conversion', '1moku-precedent-span1', '1moku-signal1',
            '1moku-signal2', '1moku-signal3', '1moku-signal4', '1moku-signal5',
            '1moku-signal6'
        ],
        '1moku-precedent-span1': [
            '1moku-precedent-span1', '1moku-signal3', '1moku-signal4',
            '1moku-signal5', '1moku-signal6'
        ],
        '1moku-precedent-span2': [
            '1moku-precedent-span2', '1moku-signal3', '1moku-signal4',
            '1moku-signal5', '1moku-signal6'
        ],
        '1moku-late-span': ['1moku-late-span'],
        '1moku-signal1': ['1moku-signal1'],
        '1moku-signal2': ['1moku-signal2'],
        '1moku-signal3': ['1moku-signal3'],
        '1moku-signal4': ['1moku-signal4'],
        '1moku-signal5': ['1moku-signal5'],
        '1moku-signal6': ['1moku-signal6'],
        'Target_Open': [
            'Target_Open', 'Target_O/O', 'Target_H/O', 'Target_L/O',
            'Target_C/O', 'Target_O/C'
        ],
        'Target_High': ['Target_High', 'Target_H/O', 'Target_H/C'],
        'Target_Low': ['Target_Low', 'Target_L/O', 'Target_L/C'],
        'Target_Close': [
            'Target_Close', 'Target_C/O', 'Target_O/C', 'Target_H/C',
            'Target_L/C', 'Target_C/C'
        ],
        'Target_O/O': ['Target_O/O'],
        'Target_H/O': ['Target_H/O'],
        'Target_L/O': ['Target_L/O'],
        'Target_C/O': ['Target_C/O'],
        'Target_O/C': ['Target_O/C'],
        'Target_H/C': ['Target_H/C'],
        'Target_L/C': ['Target_L/C'],
        'Target_C/C': ['Target_C/C'],
        'Target_Over': ['Target_Over'],
    }
    if check_cdrr('O/O', cdrr, columns):
        ohlc['O/O'] = ohlc['Open'] / ohlc['Open']

    if check_cdrr('H/O', cdrr, columns):
        ohlc['H/O'] = ohlc['High'] / ohlc['Open']

    if check_cdrr('L/O', cdrr, columns):
        ohlc['L/O'] = ohlc['Low'] / ohlc['Open']

    if check_cdrr('C/O', cdrr, columns):
        ohlc['C/O'] = ohlc['Close'] / ohlc['Open']

    if check_cdrr('O/C', cdrr, columns):
        ohlc['O/C'] = ohlc['Open'] / ohlc['Close']

    if check_cdrr('H/C', cdrr, columns):
        ohlc['H/C'] = ohlc['High'] / ohlc['Close']

    if check_cdrr('L/C', cdrr, columns):
        ohlc['L/C'] = ohlc['Low'] / ohlc['Close']

    if check_cdrr('C/C', cdrr, columns):
        ohlc['C/C'] = ohlc['Close'] / ohlc['Close']

    if check_cdrr('H-L/O', cdrr, columns):
        ohlc['H-L/O'] = ohlc['H/O'] - ohlc['L/O']

    if check_cdrr('H-L/C', cdrr, columns):
        ohlc['H-L/C'] = ohlc['H/C'] - ohlc['L/C']

    if check_cdrr('O-1/C', cdrr, columns):
        ohlc['O-1/C'] = ohlc['Open'].shift(1) / ohlc['Close']

    if check_cdrr('H-1/C', cdrr, columns):
        ohlc['H-1/C'] = ohlc['High'].shift(1) / ohlc['Close']

    if check_cdrr('L-1/C', cdrr, columns):
        ohlc['L-1/C'] = ohlc['Low'].shift(1) / ohlc['Close']

    if check_cdrr('C-1/C', cdrr, columns):
        ohlc['C-1/C'] = ohlc['Close'].shift(1) / ohlc['Close']

    if check_cdrr('PositiveLine', cdrr, columns):
        ohlc['PositiveLine'] = (ohlc['Open'] <= ohlc['Close']) * 1

    if check_cdrr('NegativeLine', cdrr, columns):
        ohlc['NegativeLine'] = (ohlc['Open'] > ohlc['Close']) * (-1)

    if check_cdrr('SignLine', cdrr, columns):
        ohlc['SignLine'] = ohlc['PositiveLine'] + ohlc['NegativeLine']

    if check_cdrr('3SignLine', cdrr, columns):
        ohlc['3SignLine'] = ohlc['SignLine'].rolling(3).sum()

    if check_cdrr('6SignLine', cdrr, columns):
        ohlc['6SignLine'] = ohlc['SignLine'].rolling(6).sum()

    if check_cdrr('12SignLine', cdrr, columns):
        ohlc['12SignLine'] = ohlc['SignLine'].rolling(12).sum()

    if check_cdrr('BB', cdrr, columns):
        upper, middle, lower = talib.BBANDS(ohlc['Close'],
                                            timeperiod=bbtp,
                                            nbdevup=2,
                                            nbdevdn=2,
                                            matype=0)
        ohlc['BBUpper'] = upper
        ohlc['BBMiddle'] = middle
        ohlc['BBLower'] = lower

    if check_cdrr('BBOver', cdrr, columns):
        ohlc['BBOver'] = ohlc['BBUpper'] < ohlc['Close']

    if check_cdrr('BBUnder', cdrr, columns):
        ohlc['BBUnder'] = ohlc['Close'] < ohlc['BBLower']

    if check_cdrr('MACDS', cdrr, columns):
        ohlc['MACDS'] = talib.MACD(ohlc['Close'],
                                   fastperiod=6,
                                   slowperiod=19,
                                   signalperiod=9)[0]

    if check_cdrr('MACDM', cdrr, columns):
        ohlc['MACDM'] = talib.MACD(ohlc['Close'],
                                   fastperiod=12,
                                   slowperiod=26,
                                   signalperiod=9)[0]

    if check_cdrr('MACDL', cdrr, columns):
        ohlc['MACDL'] = talib.MACD(ohlc['Close'],
                                   fastperiod=19,
                                   slowperiod=39,
                                   signalperiod=9)[0]

    if check_cdrr('MACDS/O', cdrr, columns):
        ohlc['MACDS/O'] = talib.MACD(ohlc['C/O'],
                                     fastperiod=6,
                                     slowperiod=19,
                                     signalperiod=9)[0]

    if check_cdrr('MACDM/O', cdrr, columns):
        ohlc['MACDM/O'] = talib.MACD(ohlc['C/O'],
                                     fastperiod=12,
                                     slowperiod=26,
                                     signalperiod=9)[0]

    if check_cdrr('MACDL/O', cdrr, columns):
        ohlc['MACDL/O'] = talib.MACD(ohlc['C/O'],
                                     fastperiod=19,
                                     slowperiod=39,
                                     signalperiod=9)[0]

    if check_cdrr('ATR', cdrr, columns):
        ohlc['ATR'] = talib.ATR(ohlc['High'],
                                ohlc['Low'],
                                ohlc['Close'],
                                timeperiod=14)

    if check_cdrr('ATR/O', cdrr, columns):
        ohlc['ATR/O'] = talib.ATR(ohlc['H/O'],
                                  ohlc['L/O'],
                                  ohlc['O/O'],
                                  timeperiod=14)

    if check_cdrr('RSI', cdrr, columns):
        ohlc['RSI'] = talib.RSI(ohlc['Close'], timeperiod=14)

    if check_cdrr('Time', cdrr, columns):
        #time relation
        tr = {
            '60': [60, 60],
            '300': [300, 12],
            '3600': [3600, 24],
        }
        period = str(int(ohlc['timestamp'].diff().mode()))
        ohlc['Time'] = ohlc['timestamp'] // tr[period][0] % tr[period][1]

    if check_cdrr('Over', cdrr, columns):
        ohlc['Over'] = ((ohlc['Open'] * (1 + over_rate) <= ohlc['High']) *
                        (ohlc['Open'] *
                         (1 - over_rate) >= ohlc['Low'])).astype(bool)

    if check_cdrr('1moku-base', cdrr, columns):
        ohlc['1moku-base'] = (ohlc['High'].rolling(26).max() +
                              ohlc['Low'].rolling(26).min()) / 2

    if check_cdrr('1moku-conversion', cdrr, columns):
        ohlc['1moku-conversion'] = (ohlc['High'].rolling(9).max() +
                                    ohlc['Low'].rolling(9).min()) / 2

    if check_cdrr('1moku-precedent-span1', cdrr, columns):
        ohlc['1moku-precedent-span1'] = (
            (ohlc['1moku-base'] + ohlc['1moku-conversion']) / 2).shift(26)

    if check_cdrr('1moku-precedent-span2', cdrr, columns):
        ohlc['1moku-precedent-span2'] = (
            (ohlc['High'].rolling(52).max() + ohlc['Low'].rolling(52).min()) /
            2).shift(26)

    if check_cdrr('1moku-late-span', cdrr, columns):
        ohlc['1moku-late-span'] = ohlc['Close'].shift(-26)

    if check_cdrr('1moku-signal1', cdrr, columns):
        ohlc['1moku-signal1'] = (
            (ohlc['1moku-conversion'] - ohlc['1moku-base'] > 0) * 1).diff(1)

    if check_cdrr('1moku-signal2', cdrr, columns):
        ohlc['1moku-signal2'] = (ohlc['1moku-conversion'] - ohlc['1moku-base']
                                 > 0) * 1

    if check_cdrr('1moku-signal3', cdrr, columns):
        ohlc['1moku-signal3'] = (
            ((ohlc['Close'] > ohlc['1moku-precedent-span1']) * 1) *
            ((ohlc['Close'] > ohlc['1moku-precedent-span2']) * 1)).diff(1)

    if check_cdrr('1moku-signal4', cdrr, columns):
        ohlc['1moku-signal4'] = (
            (ohlc['Close'] > ohlc['1moku-precedent-span1']) * 1) * (
                (ohlc['Close'] > ohlc['1moku-precedent-span2']) * 1)

    if check_cdrr('1moku-signal5', cdrr, columns):
        ohlc['1moku-signal5'] = (
            ((ohlc['Close'] < ohlc['1moku-precedent-span1']) * 1) *
            ((ohlc['Close'] < ohlc['1moku-precedent-span2']) * 1)).diff(1)

    if check_cdrr('1moku-signal6', cdrr, columns):
        ohlc['1moku-signal6'] = (
            (ohlc['Close'] < ohlc['1moku-precedent-span1']) * 1) * (
                (ohlc['Close'] < ohlc['1moku-precedent-span2']) * 1)

    if check_cdrr('Target_Open', cdrr, columns):
        ohlc['Target_Open'] = ohlc['Open'].shift(-1)

    if check_cdrr('Target_High', cdrr, columns):
        ohlc['Target_High'] = ohlc['High'].shift(-1)

    if check_cdrr('Target_Low', cdrr, columns):
        ohlc['Target_Low'] = ohlc['Low'].shift(-1)

    if check_cdrr('Target_Close', cdrr, columns):
        ohlc['Target_Close'] = ohlc['Close'].shift(-1)

    if check_cdrr('Target_O/O', cdrr, columns):
        ohlc['Target_O/O'] = ohlc['Target_Open'] / ohlc['Open']

    if check_cdrr('Target_H/O', cdrr, columns):
        ohlc['Target_H/O'] = ohlc['Target_High'] / ohlc['Open']

    if check_cdrr('Target_L/O', cdrr, columns):
        ohlc['Target_L/O'] = ohlc['Target_Low'] / ohlc['Open']

    if check_cdrr('Target_C/O', cdrr, columns):
        ohlc['Target_C/O'] = ohlc['Target_Close'] / ohlc['Open']

    if check_cdrr('Target_O/C', cdrr, columns):
        ohlc['Target_O/C'] = ohlc['Target_Open'] / ohlc['Close']

    if check_cdrr('Target_H/C', cdrr, columns):
        ohlc['Target_H/C'] = ohlc['Target_High'] / ohlc['Close']

    if check_cdrr('Target_L/C', cdrr, columns):
        ohlc['Target_L/C'] = ohlc['Target_Low'] / ohlc['Close']

    if check_cdrr('Target_C/C', cdrr, columns):
        ohlc['Target_C/C'] = ohlc['Target_Close'] / ohlc['Close']

    if check_cdrr('Target_Over', cdrr, columns):
        ohlc['Target_Over'] = ohlc['Over'].shift(-1).astype(bool)

    ohlc = ohlc[columns]

    if drop:
        ohlc = ohlc.dropna()

    return ohlc
Пример #9
0
def strategy_bandwidth(series, is_backtest=True):
    '''策略:布林通道宽度'''

    # 实时线
    close = np.cumsum(series).astype(float)
    # 布林线
    upperband, middleband, lowerband = ta.BBANDS(close,
                                                 timeperiod=5,
                                                 nbdevup=2,
                                                 nbdevdn=2,
                                                 matype=0)

    bandwidth = upperband - lowerband
    bandwidth_mean = np.nan_to_num(bandwidth).mean()

    current_signal = 0  # 当前信号:无

    # 计算趋势
    mean = ta.MA(close, timeperiod=5, matype=0)
    #mean = np.nan_to_num(mean) #Nan转换为0
    diff_mean = np.diff(mean)  # 注意:长度减1

    #trend = np.where(diff_mean > 0, 1, -1)
    trend = []
    for i in range(len(diff_mean)):
        if diff_mean[i] == 0:
            trend.append(trend[-1])
        else:
            trend.append([-1, 1][diff_mean[i] > 0])

    # 如果是回测
    if is_backtest:
        error_periods = 0  # 哨兵:之前错误期数
        earn = []  # 收益记录
        order = []  # 投注资金记录

        for i in range(2, len(series)):

            # 判断是否有信号,什么信号
            #if bandwidth[i-1] < bandwidth[i]: # 增:趋势区间
            if bandwidth[i - 1] > bandwidth_mean:  # 宽:趋势区间
                #current_signal = series[-1] # 与前一期相同
                current_signal = trend[i - 2]  # 与前一期趋势相同
            else:  # 窄:震荡区间
                current_signal = -series[i - 1]  # 与前一期相反(注意不一样!!)

            # 若无信号,跳过,不做任何操作
            #if current_signal == 0: continue

            if current_signal == 0:
                order.append(0)
                earn.append(0)
                continue

            # 看料
            buy = current_signal
            # 下单
            order.append(times[error_periods])

            # 判断对错,计算收益
            if buy == series[i]:
                error_periods = 0  # 错误期数置零
                earn.append(odds * order[-1])  # 赔率odds=1.96
            else:
                error_periods += 1  # 错误期数加一
                earn.append(0)

        print('投注记录:\n', order[-show_period:], '\n合计:',
              sum(order[-show_period:]))
        print('收益记录:\n', earn[-show_period:], '\n合计:',
              sum(earn[-show_period:]))
        print('收益率:', (sum(earn[-show_period:]) - sum(order[-show_period:])) /
              sum(order[-show_period:]))

        return order, earn, bandwidth, bandwidth_mean
    # 否则只显示最后一期
    else:
        # 应肖的需求,显示下期结果
        if bandwidth[-1] > mean:  # 宽:趋势区间
            current_signal = trend[-1]  # 与前一期(趋势)相同
        else:  # 窄:震荡区间
            current_signal = -series[-1]  # 与前一期相反
        print('=' * 30)
        print('通道宽度: ', end='')
        print_red_color_text(current_signal)
        print('=' * 30)

        return current_signal
Пример #10
0
def get_factors(index, 
                Open, 
                Close, 
                High, 
                Low, 
                Volume,
                rolling = 26,
                drop=False, 
                normalization=True):
    
    tmp = pd.DataFrame()
    tmp['tradeTime'] = index
    
    #累积/派发线(Accumulation / Distribution Line,该指标将每日的成交量通过价格加权累计,
    #用以计算成交量的动量。属于趋势型因子
    tmp['AD'] = talib.AD(High, Low, Close, Volume)

    # 佳庆指标(Chaikin Oscillator),该指标基于AD曲线的指数移动均线而计算得到。属于趋势型因子
    tmp['ADOSC'] = talib.ADOSC(High, Low, Close, Volume, fastperiod=3, slowperiod=10)

    # 平均动向指数,DMI因子的构成部分。属于趋势型因子
    tmp['ADX'] = talib.ADX(High, Low, Close,timeperiod=14)

    # 相对平均动向指数,DMI因子的构成部分。属于趋势型因子
    tmp['ADXR'] = talib.ADXR(High, Low, Close,timeperiod=14)

    # 绝对价格振荡指数
    tmp['APO'] = talib.APO(Close, fastperiod=12, slowperiod=26)

    # Aroon通过计算自价格达到近期最高值和最低值以来所经过的期间数,帮助投资者预测证券价格从趋势到区域区域或反转的变化,
    #Aroon指标分为Aroon、AroonUp和AroonDown3个具体指标。属于趋势型因子
    tmp['AROONDown'], tmp['AROONUp'] = talib.AROON(High, Low,timeperiod=14)
    tmp['AROONOSC'] = talib.AROONOSC(High, Low,timeperiod=14)

    # 均幅指标(Average TRUE Ranger),取一定时间周期内的股价波动幅度的移动平均值,
    #是显示市场变化率的指标,主要用于研判买卖时机。属于超买超卖型因子。
    tmp['ATR14']= talib.ATR(High, Low, Close, timeperiod=14)
    tmp['ATR6']= talib.ATR(High, Low, Close, timeperiod=6)

    # 布林带
    tmp['Boll_Up'],tmp['Boll_Mid'],tmp['Boll_Down']= talib.BBANDS(Close, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0)

    # 均势指标
    tmp['BOP'] = talib.BOP(Open, High, Low, Close)

    #5日顺势指标(Commodity Channel Index),专门测量股价是否已超出常态分布范围。属于超买超卖型因子。
    tmp['CCI5'] = talib.CCI(High, Low, Close, timeperiod=5)
    tmp['CCI10'] = talib.CCI(High, Low, Close, timeperiod=10)
    tmp['CCI20'] = talib.CCI(High, Low, Close, timeperiod=20)
    tmp['CCI88'] = talib.CCI(High, Low, Close, timeperiod=88)

    # 钱德动量摆动指标(Chande Momentum Osciliator),与其他动量指标摆动指标如相对强弱指标(RSI)和随机指标(KDJ)不同,
    # 钱德动量指标在计算公式的分子中采用上涨日和下跌日的数据。属于超买超卖型因子
    tmp['CMO_Close'] = talib.CMO(Close,timeperiod=14)
    tmp['CMO_Open'] = talib.CMO(Close,timeperiod=14)

    # DEMA双指数移动平均线
    tmp['DEMA6'] = talib.DEMA(Close, timeperiod=6)
    tmp['DEMA12'] = talib.DEMA(Close, timeperiod=12)
    tmp['DEMA26'] = talib.DEMA(Close, timeperiod=26)

    # DX 动向指数
    tmp['DX'] = talib.DX(High, Low, Close,timeperiod=14)

    # EMA 指数移动平均线
    tmp['EMA6'] = talib.EMA(Close, timeperiod=6)
    tmp['EMA12'] = talib.EMA(Close, timeperiod=12)
    tmp['EMA26'] = talib.EMA(Close, timeperiod=26)

    # KAMA 适应性移动平均线
    tmp['KAMA'] = talib.KAMA(Close, timeperiod=30)

    # MACD
    tmp['MACD_DIF'],tmp['MACD_DEA'],tmp['MACD_bar'] = talib.MACD(Close, fastperiod=12, slowperiod=24, signalperiod=9)

    # 中位数价格 不知道是什么意思
    tmp['MEDPRICE'] = talib.MEDPRICE(High, Low)

    # 负向指标 负向运动
    tmp['MiNUS_DI'] = talib.MINUS_DI(High, Low, Close,timeperiod=14)
    tmp['MiNUS_DM'] = talib.MINUS_DM(High, Low,timeperiod=14)

    # 动量指标(Momentom Index),动量指数以分析股价波动的速度为目的,研究股价在波动过程中各种加速,
    #减速,惯性作用以及股价由静到动或由动转静的现象。属于趋势型因子
    tmp['MOM'] = talib.MOM(Close, timeperiod=10)

    # 归一化平均值范围
    tmp['NATR'] = talib.NATR(High, Low, Close,timeperiod=14)

    # OBV 	能量潮指标(On Balance Volume,OBV),以股市的成交量变化来衡量股市的推动力,
    #从而研判股价的走势。属于成交量型因子
    tmp['OBV'] = talib.OBV(Close, Volume)

    # PLUS_DI 更向指示器
    tmp['PLUS_DI'] = talib.PLUS_DI(High, Low, Close,timeperiod=14)
    tmp['PLUS_DM'] = talib.PLUS_DM(High, Low, timeperiod=14)

    # PPO 价格振荡百分比
    tmp['PPO'] = talib.PPO(Close, fastperiod=6, slowperiod= 26, matype=0)

    # ROC 6日变动速率(Price Rate of Change),以当日的收盘价和N天前的收盘价比较,
    #通过计算股价某一段时间内收盘价变动的比例,应用价格的移动比较来测量价位动量。属于超买超卖型因子。
    tmp['ROC6'] = talib.ROC(Close, timeperiod=6)
    tmp['ROC20'] = talib.ROC(Close, timeperiod=20)
    #12日量变动速率指标(Volume Rate of Change),以今天的成交量和N天前的成交量比较,
    #通过计算某一段时间内成交量变动的幅度,应用成交量的移动比较来测量成交量运动趋向,
    #达到事先探测成交量供需的强弱,进而分析成交量的发展趋势及其将来是否有转势的意愿,
    #属于成交量的反趋向指标。属于成交量型因子
    tmp['VROC6'] = talib.ROC(Volume, timeperiod=6)
    tmp['VROC20'] = talib.ROC(Volume, timeperiod=20)

    # ROC 6日变动速率(Price Rate of Change),以当日的收盘价和N天前的收盘价比较,
    #通过计算股价某一段时间内收盘价变动的比例,应用价格的移动比较来测量价位动量。属于超买超卖型因子。
    tmp['ROCP6'] = talib.ROCP(Close, timeperiod=6)
    tmp['ROCP20'] = talib.ROCP(Close, timeperiod=20)
    #12日量变动速率指标(Volume Rate of Change),以今天的成交量和N天前的成交量比较,
    #通过计算某一段时间内成交量变动的幅度,应用成交量的移动比较来测量成交量运动趋向,
    #达到事先探测成交量供需的强弱,进而分析成交量的发展趋势及其将来是否有转势的意愿,
    #属于成交量的反趋向指标。属于成交量型因子
    tmp['VROCP6'] = talib.ROCP(Volume, timeperiod=6)
    tmp['VROCP20'] = talib.ROCP(Volume, timeperiod=20)

    # RSI
    tmp['RSI'] = talib.RSI(Close, timeperiod=14)

    # SAR 抛物线转向
    tmp['SAR'] = talib.SAR(High, Low, acceleration=0.02, maximum=0.2)

    # TEMA
    tmp['TEMA6'] = talib.TEMA(Close, timeperiod=6)
    tmp['TEMA12'] = talib.TEMA(Close, timeperiod=12)
    tmp['TEMA26'] = talib.TEMA(Close, timeperiod=26)

    # TRANGE 真实范围
    tmp['TRANGE'] = talib.TRANGE(High, Low, Close)

    # TYPPRICE 典型价格
    tmp['TYPPRICE'] = talib.TYPPRICE(High, Low, Close)

    # TSF 时间序列预测
    tmp['TSF'] = talib.TSF(Close, timeperiod=14)

    # ULTOSC 极限振子
    tmp['ULTOSC'] = talib.ULTOSC(High, Low, Close, timeperiod1=7, timeperiod2=14, timeperiod3=28)

    # 威廉指标
    tmp['WILLR'] = talib.WILLR(High, Low, Close, timeperiod=14)
    
    # 标准化
    if normalization:
        factors_list = tmp.columns.tolist()[1:]

        if rolling >= 26:
            for i in factors_list:
                tmp[i] = (tmp[i] - tmp[i].rolling(window=rolling, center=False).mean())                /tmp[i].rolling(window=rolling, center=False).std()
        elif rolling < 26 & rolling > 0:
            print ('Recommended rolling range greater than 26')
        elif rolling <=0:
            for i in factors_list:
                tmp[i] = (tmp[i] - tmp[i].mean())/tmp[i].std()
            
    if drop:
        tmp.dropna(inplace=True)
        
    tmp.set_index('tradeTime', inplace=True)
    
    return tmp
Пример #11
0
def ALL():
    def candles(window, period):
        period = str(period)
        window = WINDOW[0]
        url = 'https://api.hitbtc.com/api/2/public/candles/BTCUSD?period=' + window + '&limit=' + period
        r = requests.get(url)
        retorno = {}
        resposta = r.json()
        MEAN, TIMESTAMP = [], []
        for i in range(len(np.array(resposta))):
            MEAN.append((float(np.array(resposta)[i]['max']) +
                         float(np.array(resposta)[i]['min'])) / 2)
            TIMESTAMP.append(np.array(resposta)[i]['timestamp'])
        return list(MEAN), TIMESTAMP

    def vol(window, period):
        period = str(period)
        window = WINDOW[0]
        url = 'https://api.hitbtc.com/api/2/public/candles/BTCUSD?period=' + window + '&limit=' + period
        r = requests.get(url)
        retorno = {}
        resposta = r.json()
        VOL, TIMESTAMP = [], []
        for i in range(len(np.array(resposta))):
            VOL.append((float(np.array(resposta)[i]['volume'])))
            TIMESTAMP.append(np.array(resposta)[i]['timestamp'])
        return list(VOL), TIMESTAMP

    from scipy.signal import savgol_filter
    WINDOW = ['M1', 'M3', 'M5', 'M15', 'M30', 'H1', 'H4', 'D1', 'W1']

    window = 1000
    lista, timestamp = candles(WINDOW[0], window)
    w = 13
    #x = moving_average(lista, w)
    x = savgol_filter(lista, 63, 3)
    #x = savgol_filter(lista, 123, 3)
    d_window = 10
    dydx = x[1:] - x[:-1]

    val = []
    val.append(0)
    index = []
    l = 130
    j = 190
    for i in range(0, len(lista) - l, l):
        a = min(lista[i:i + j])
        if a != val[-1]:
            index.append(int(np.argwhere(np.array(lista) == a)[0]))
            val.append(a)
    val.pop(0)
    a = min(lista[-80:])
    val.append(a)
    index.append(int(np.argwhere(np.array(lista) == a)))
    y_s = val
    x_s = index

    val = []
    val.append(0)
    index = []
    for i in range(0, len(lista) - l, l):
        a = max(lista[i:i + j])
        if a != val[-1]:
            index.append(int(np.argwhere(np.array(lista) == a)[0]))
            val.append(a)
    val.pop(0)
    a = max(lista[-80:])
    val.append(a)
    index.append(int(np.argwhere(np.array(lista) == a)))
    '''
    indexMAX = []
    indexMIN = []
    for i in range(len(x)-1):
        if dydx[i]<0 and sum(dydx[i+1:i+50]>0)==49:
            indexMAX.append(i)
        if dydx[i]>0 and sum(dydx[i+1:i+50]<0)==49:
            indexMIN.append(i)
           
    #plt.scatter(  np.array(indexMIN)  , np.array(lista)[np.array(indexMIN)]   )   
    #plt.plot(x) 
    #plt.plot(lista[w:])  
    y_s = np.array(lista)[list(np.array(indexMIN)+int(w/2))]
    x_s = np.array(indexMIN)+w/2
    #A = (y_s[0]-y_s[1])/(x_s[0]-x_s[1]) 
    #B = y_s[0]-A*x_s[0]
    #X_s=np.array(range(-10,200))
    #Y_s = A*X+B
    y_r = np.array(lista)[list(np.array(indexMAX)+int(w/2))]
    x_r = np.array(indexMAX)+w/2
    
    A = (y_r[0]-y_r[1])/(x_r[0]-x_r[1]) 
    B = y_r[0]-A*x_r[0]
    X_r = np.array(range(-10,200))
    Y_r = A*X+B
    '''
    y_r = val
    x_r = index

    plt.figure(figsize=(10, 5))
    plt.plot(lista)

    c_gap = 1
    a_r = []
    a_s = []

    for i in range(0, len(y_r) - c_gap, c_gap):
        A = (y_r[i] - y_r[i + c_gap]) / (x_r[i] - x_r[i + c_gap] + 0.001)
        B = y_r[i] - A * x_r[i]
        a_r.append(A)
        X_r1 = np.array(range(int(x_r[i]), int(x_r[i + c_gap])))
        Y_r1 = A * X_r1 + B
        #Y_r1 = A*X+B
        plt.plot(X_r1, Y_r1, color='green')
        if i == list(range(0, len(y_r) - c_gap, c_gap))[-1]:
            X_r1 = np.array(range(int(x_r[i]), int(len(lista) + 60)))
            Y_r1 = A * X_r1 + B
            plt.plot(X_r1, Y_r1, color='green')
    c_gap = 1
    for i in range(0, len(y_r) - c_gap, c_gap):
        try:
            A = (y_s[i] - y_s[i + c_gap]) / (x_s[i] - x_s[i + c_gap])
            a_s.append(A)
            B = y_s[i] - A * x_s[i]
            X_s = np.array(range(int(x_s[i]), int(x_s[i + c_gap])))
            Y_s = A * X_s + B
            plt.plot(X_s, Y_s, color='red')
            if i == list(range(0, len(y_r) - c_gap, c_gap))[-1]:
                X_s = np.array(range(int(x_s[i]), int(len(lista) + 60)))
                Y_s = A * X_s + B
                plt.plot(X_s, Y_s, color='red')
        except:
            i = len(x_s) - 1 - c_gap
            A = (y_s[i] - y_s[i + c_gap]) / (x_s[i] - x_s[i + c_gap])
            a_s.append(A)
            B = y_s[i] - A * x_s[i]
            X_s = np.array(range(int(x_s[i]), int(len(lista) + 60)))
            Y_s = A * X_s + B
            plt.plot(X_s, Y_s, color='red')

    plt.plot(x)
    plt.grid()
    plt.savefig('dydx/Sup_Res' + str(time.time()).split('.')[0] + '.png')
    plt.title('Support/Resistence')
    plt.xlim(0, len(lista) + 60)
    plt.savefig('../INDICATORS/' + 'support_res' + str(time.time()) + '.png')
    plt.cla()
    plt.clf()

    #plt.plot(X_r,Y_r)
    #plt.plot(X_s,Y_s)
    #plt.plot(x)
    #plt.plot(lista)
    #plt.xlim(20,115)
    #plt.ylim(min(lista)-20,max(lista)+20)
    #plt.legend(['MA 10 periodos','preço'])
    #plt.figure(1)
    #plt.plot(a_s)
    #plt.plot(a_r)

    price = np.array(lista)
    price = (price - price.mean())
    price = price / max(price)
    dydx = savgol_filter(dydx, 63, 3)
    price = savgol_filter(price, 63, 3)

    plt.figure(66)
    plt.figure(figsize=(10, 4))
    #plt.figure(3,figsize=(6,2))
    plt.plot(dydx / max(abs(dydx)))
    plt.plot(price)
    plt.plot(np.zeros(len(dydx)))
    plt.legend(['dydx', 'price'], loc='best')
    plt.savefig('dydx/Derivate' + str(time.time()).split('.')[0] + '.png')
    plt.title('Derivate')
    plt.savefig('../INDICATORS/' + 'phase_in_t' + str(time.time()) + '.png')
    plt.cla()
    plt.clf()

    r = int(-1)
    s = int(-1)
    plt.figure(50)
    plt.figure(figsize=(10, 5))
    cem = y_r[r] - y_s[s]
    fibonacci = np.ones((400, 5)) * np.array(
        [0.236, 0.382, 0.50, 0.618, 0.786]) * cem + y_s[-1]
    x_f = list(range(x_s[s], x_s[s] + len(fibonacci), 1))
    #plt.plot(x)
    plt.plot(lista)
    plt.plot(x_f, fibonacci)
    plt.ylim(y_r[r] - 200, y_s[s] + 200)
    plt.legend(['price', '0.236', '0.382', '0.50', '0.618', '0.786'])
    plt.grid()
    plt.title('Fibonacci')
    plt.savefig('dydx/Fibonacci' + str(time.time()).split('.')[0] + '.png')
    plt.savefig('../INDICATORS/' + 'Fibonacci_' + str(time.time()) + '.png')

    import numpy
    import talib
    output = talib.SMA(np.array(lista))
    from talib import MA_Type
    upper, middle, lower = talib.BBANDS(np.array(lista), 44)
    #talib.MOM(lista, timeperiod=5)

    plt.figure(60)
    plt.figure(figsize=(10, 5))
    plt.plot(upper)
    plt.plot(lower)
    plt.plot(middle)
    plt.plot(np.array(lista))
    plt.grid()
    volume, timestamp = vol(WINDOW[0], window)
    plt.legend(['upper', 'lower', 'mid', 'price'])
    plt.title('Bollinger')
    plt.savefig('../INDICATORS/' + 'dydxBollinger' +
                str(time.time()).split('.')[0] + '.png')
    plt.cla()
    plt.clf()

    price = np.array(lista)
    std = np.ones(len(volume)) * np.array(volume).std()
    mean = np.ones(len(volume)) * np.array(volume).mean()

    plt.figure(70)
    plt.figure(figsize=(10, 5))
    plt.plot(volume)
    plt.plot(mean + 2 * std)
    plt.plot((price - (min(price))))
    plt.grid()
    plt.legend(['volume', 'mean+2sigma', 'price (normalized)'])
    plt.title('Anomaly')
    plt.savefig('dydx/anomaly' + str(time.time()).split('.')[0] + '.png')
    plt.savefig('../INDICATORS/' + 'dydx_' + str(time.time()) + '.png')
    plt.cla()
    plt.clf()

    plt.figure(777)
    #plt.figure(figsize= (5,5))
    dyd2x = dydx[1:] - dydx[:-1]
    state1 = (dydx / max(abs(dydx)))[1:]
    state2 = dyd2x
    lenght = 200
    state2 = state2[-lenght:]
    state1 = state1[-lenght:]
    plt.grid()
    t = np.linspace(0, 1, num=len(state1))
    dotcolors = [(0.0, 0.0, 0.0, a) for a in t]
    plt.scatter(state1, state2, c=dotcolors, s=30, edgecolors='None')
    plt.plot(state1, state2, linewidth=0.4, c='black')
    [min(state2), max(state2)]
    [min(state1), max(state2)]
    [0, 0]
    plt.plot([min(state1), max(state1)], [0, 0], color='black')
    plt.plot([0, 0], [min(state2), max(state2)], color='black')
    plt.title('Phase Diagram')
    plt.savefig('../INDICATORS/' + 'phase_mean' + str(time.time()) + '.png')

    plt.xlabel("y'(x)")
    plt.ylabel("y''(x)")
    plt.cla()
    plt.clf()

    plt.figure(999)
    price = np.array(lista)
    price = (price - price.mean())
    price = price / max(price)
    price = savgol_filter(price, 63, 3)
    #plt.figure(figsize= (5,5))
    dyd2x = dydx[1:] - dydx[:-1]
    state1 = (dydx / max(abs(dydx)))[1:]
    state2 = price
    lenght = 300
    state2 = state2[-lenght:]
    state1 = state1[-lenght:]
    plt.grid()
    t = np.linspace(0, 1, num=len(state1))
    dotcolors = [(0.0, 0.0, 0.0, a) for a in t]
    plt.scatter(state2, state1, c=dotcolors, s=30, edgecolors='None')
    plt.plot(state2, state1, linewidth=0.4, c='black')
    plt.title("Phase Diagram price y'(x)")
    plt.xlabel("x")
    plt.ylabel("y'(x)")
    plt.savefig('../INDICATORS/' + 'phase' + str(time.time()) + '.png')

    [min(state2), max(state2)]
    [min(state1), max(state2)]
    [0, 0]
    plt.plot([0, 0], [min(state1), max(state1)], color='black')
    plt.plot([min(state2), max(state2)], [0, 0], color='black')
    plt.cla()
    plt.clf()
Пример #12
0
def _extract_feature(candle, params):
    o = candle.open
    h = candle.high
    l = candle.low
    c = candle.close
    v = candle.volume

    # OHLCV
    features = pd.DataFrame()
    features['open'] = o
    features['high'] = h
    features['low'] = l
    features['close'] = c
    features['volume'] = v

    # RSI
    features['rsi_s'] = ta.RSI(c, timeperiod=params['rsi_timeperiod_s'])
    features['rsi_m'] = ta.RSI(c, timeperiod=params['rsi_timeperiod_m'])
    features['rsi_l'] = ta.RSI(c, timeperiod=params['rsi_timeperiod_l'])

    # STOCHF
    fastk, fastd = ta.STOCHF(h,
                             l,
                             c,
                             fastk_period=params['stockf_fastk_period_s'],
                             fastd_period=params['stockf_fastd_period_s'],
                             fastd_matype=ta.MA_Type.T3)
    change_stockf = calc_change(fastk, fastd)
    change_stockf.index = fastk.index
    features['fastk_s'] = fastk
    features['fastd_s'] = fastd
    features['fast_change_s'] = change_stockf
    fastk, fastd = ta.STOCHF(h,
                             l,
                             c,
                             fastk_period=params['stockf_fastk_period_m'],
                             fastd_period=params['stockf_fastd_period_m'],
                             fastd_matype=ta.MA_Type.T3)
    change_stockf = calc_change(fastk, fastd)
    change_stockf.index = fastk.index
    features['fastk_m'] = fastk
    features['fastd_m'] = fastd
    features['fast_change_m'] = change_stockf
    fastk, fastd = ta.STOCHF(h,
                             l,
                             c,
                             fastk_period=params['stockf_fastk_period_l'],
                             fastd_period=params['stockf_fastd_period_l'],
                             fastd_matype=ta.MA_Type.T3)
    change_stockf = calc_change(fastk, fastd)
    change_stockf.index = fastk.index
    features['fastk_l'] = fastk
    features['fastd_l'] = fastd
    features['fast_change_l'] = change_stockf

    # WILLR
    features['willr_s'] = ta.WILLR(h,
                                   l,
                                   c,
                                   timeperiod=params['willr_timeperiod_s'])
    features['willr_m'] = ta.WILLR(h,
                                   l,
                                   c,
                                   timeperiod=params['willr_timeperiod_m'])
    features['willr_l'] = ta.WILLR(h,
                                   l,
                                   c,
                                   timeperiod=params['willr_timeperiod_l'])

    # MACD
    macd, macdsignal, macdhist = ta.MACDEXT(
        c,
        fastperiod=params['macd_fastperiod_s'],
        slowperiod=params['macd_slowperiod_s'],
        signalperiod=params['macd_signalperiod_s'],
        fastmatype=ta.MA_Type.T3,
        slowmatype=ta.MA_Type.T3,
        signalmatype=ta.MA_Type.T3)
    change_macd = calc_change(macd, macdsignal)
    change_macd.index = macd.index
    features['macd_s'] = macd
    features['macdsignal_s'] = macdsignal
    features['macdhist_s'] = macdhist
    features['change_macd_s'] = change_macd
    macd, macdsignal, macdhist = ta.MACDEXT(
        c,
        fastperiod=params['macd_fastperiod_m'],
        slowperiod=params['macd_slowperiod_m'],
        signalperiod=params['macd_signalperiod_m'],
        fastmatype=ta.MA_Type.T3,
        slowmatype=ta.MA_Type.T3,
        signalmatype=ta.MA_Type.T3)
    change_macd = calc_change(macd, macdsignal)
    change_macd.index = macd.index
    features['macd_m'] = macd
    features['macdsignal_m'] = macdsignal
    features['macdhist_m'] = macdhist
    features['change_macd_m'] = change_macd

    # ROCP
    rocp = ta.ROCP(c, timeperiod=params['rocp_timeperiod_s'])
    change_rocp = calc_change(
        rocp, pd.Series(np.zeros(len(candle)), index=candle.index))
    change_rocp.index = rocp.index
    features['rocp_s'] = rocp
    features['change_rocp_s'] = change_rocp
    rocp = ta.ROCP(c, timeperiod=params['rocp_timeperiod_m'])
    change_rocp = calc_change(
        rocp, pd.Series(np.zeros(len(candle)), index=candle.index))
    change_rocp.index = rocp.index
    features['rocp_m'] = rocp
    features['change_rocp_m'] = change_rocp
    rocp = ta.ROCP(c, timeperiod=params['rocp_timeperiod_l'])
    change_rocp = calc_change(
        rocp, pd.Series(np.zeros(len(candle)), index=candle.index))
    change_rocp.index = rocp.index
    features['rocp_l'] = rocp
    features['change_rocp_l'] = change_rocp

    # ボリンジャーバンド
    bb_upper, bb_middle, bb_lower = ta.BBANDS(
        c,
        timeperiod=params['bbands_timeperiod_s'],
        nbdevup=params['bbands_nbdevup_s'],
        nbdevdn=params['bbands_nbdevdn_s'],
        matype=ta.MA_Type.T3)
    bb_trend1 = pd.Series(np.zeros(len(candle)), index=candle.index)
    bb_trend1[c > bb_upper] = 1
    bb_trend1[c < bb_lower] = -1
    bb_trend2 = pd.Series(np.zeros(len(candle)), index=candle.index)
    bb_trend2[c > bb_middle] = 1
    bb_trend2[c < bb_middle] = -1
    features['bb_upper_s'] = bb_upper
    features['bb_middle_s'] = bb_middle
    features['bb_lower_s'] = bb_lower
    features['bb_trend1_s'] = bb_trend1
    features['bb_trend2_s'] = bb_trend2
    bb_upper, bb_middle, bb_lower = ta.BBANDS(
        c,
        timeperiod=params['bbands_timeperiod_m'],
        nbdevup=params['bbands_nbdevup_m'],
        nbdevdn=params['bbands_nbdevdn_m'],
        matype=ta.MA_Type.T3)
    bb_trend1 = pd.Series(np.zeros(len(candle)), index=candle.index)
    bb_trend1[c > bb_upper] = 1
    bb_trend1[c < bb_lower] = -1
    bb_trend2 = pd.Series(np.zeros(len(candle)), index=candle.index)
    bb_trend2[c > bb_middle] = 1
    bb_trend2[c < bb_middle] = -1
    features['bb_upper_m'] = bb_upper
    features['bb_middle_m'] = bb_middle
    features['bb_lower_m'] = bb_lower
    features['bb_trend1_m'] = bb_trend1
    features['bb_trend2_m'] = bb_trend2
    bb_upper, bb_middle, bb_lower = ta.BBANDS(
        c,
        timeperiod=params['bbands_timeperiod_l'],
        nbdevup=params['bbands_nbdevup_l'],
        nbdevdn=params['bbands_nbdevdn_l'],
        matype=ta.MA_Type.T3)
    bb_trend1 = pd.Series(np.zeros(len(candle)), index=candle.index)
    bb_trend1[c > bb_upper] = 1
    bb_trend1[c < bb_lower] = -1
    bb_trend2 = pd.Series(np.zeros(len(candle)), index=candle.index)
    bb_trend2[c > bb_middle] = 1
    bb_trend2[c < bb_middle] = -1
    features['bb_upper_l'] = bb_upper
    features['bb_middle_l'] = bb_middle
    features['bb_lower_l'] = bb_lower
    features['bb_trend1_l'] = bb_trend1
    features['bb_trend2_l'] = bb_trend2

    # 出来高
    features['obv'] = ta.OBV(c, v)
    features['ad'] = ta.AD(h, l, c, v)
    features['adosc_s'] = ta.ADOSC(h,
                                   l,
                                   c,
                                   v,
                                   fastperiod=params['fastperiod_adosc_s'],
                                   slowperiod=params['slowperiod_adosc_s'])

    # ローソク足
    features['CDL2CROWS'] = ta.CDL2CROWS(o, h, l, c)
    features['CDL3BLACKCROWS'] = ta.CDL3BLACKCROWS(o, h, l, c)
    features['CDL3INSIDE'] = ta.CDL3INSIDE(o, h, l, c)
    features['CDL3LINESTRIKE'] = ta.CDL3LINESTRIKE(o, h, l, c)
    features['CDL3OUTSIDE'] = ta.CDL3OUTSIDE(o, h, l, c)
    features['CDL3STARSINSOUTH'] = ta.CDL3STARSINSOUTH(o, h, l, c)
    features['CDL3WHITESOLDIERS'] = ta.CDL3WHITESOLDIERS(o, h, l, c)
    features['CDLABANDONEDBABY'] = ta.CDLABANDONEDBABY(o,
                                                       h,
                                                       l,
                                                       c,
                                                       penetration=0)
    features['CDLADVANCEBLOCK'] = ta.CDLADVANCEBLOCK(o, h, l, c)
    features['CDLBELTHOLD'] = ta.CDLBELTHOLD(o, h, l, c)
    features['CDLBREAKAWAY'] = ta.CDLBREAKAWAY(o, h, l, c)
    features['CDLCLOSINGMARUBOZU'] = ta.CDLCLOSINGMARUBOZU(o, h, l, c)
    features['CDLCONCEALBABYSWALL'] = ta.CDLCONCEALBABYSWALL(o, h, l, c)
    features['CDLCOUNTERATTACK'] = ta.CDLCOUNTERATTACK(o, h, l, c)
    features['CDLDARKCLOUDCOVER'] = ta.CDLDARKCLOUDCOVER(o,
                                                         h,
                                                         l,
                                                         c,
                                                         penetration=0)
    features['CDLDOJI'] = ta.CDLDOJI(o, h, l, c)
    features['CDLDOJISTAR'] = ta.CDLDOJISTAR(o, h, l, c)
    features['CDLDRAGONFLYDOJI'] = ta.CDLDRAGONFLYDOJI(o, h, l, c)
    features['CDLENGULFING'] = ta.CDLENGULFING(o, h, l, c)
    features['CDLEVENINGDOJISTAR'] = ta.CDLEVENINGDOJISTAR(o,
                                                           h,
                                                           l,
                                                           c,
                                                           penetration=0)
    features['CDLEVENINGSTAR'] = ta.CDLEVENINGSTAR(o, h, l, c, penetration=0)
    features['CDLGAPSIDESIDEWHITE'] = ta.CDLGAPSIDESIDEWHITE(o, h, l, c)
    features['CDLGRAVESTONEDOJI'] = ta.CDLGRAVESTONEDOJI(o, h, l, c)
    features['CDLHAMMER'] = ta.CDLHAMMER(o, h, l, c)
    features['CDLHANGINGMAN'] = ta.CDLHANGINGMAN(o, h, l, c)
    features['CDLHARAMI'] = ta.CDLHARAMI(o, h, l, c)
    features['CDLHARAMICROSS'] = ta.CDLHARAMICROSS(o, h, l, c)
    features['CDLHIGHWAVE'] = ta.CDLHIGHWAVE(o, h, l, c)
    features['CDLHIKKAKE'] = ta.CDLHIKKAKE(o, h, l, c)
    features['CDLHIKKAKEMOD'] = ta.CDLHIKKAKEMOD(o, h, l, c)
    features['CDLHOMINGPIGEON'] = ta.CDLHOMINGPIGEON(o, h, l, c)
    features['CDLIDENTICAL3CROWS'] = ta.CDLIDENTICAL3CROWS(o, h, l, c)
    features['CDLINNECK'] = ta.CDLINNECK(o, h, l, c)
    features['CDLINVERTEDHAMMER'] = ta.CDLINVERTEDHAMMER(o, h, l, c)
    features['CDLKICKING'] = ta.CDLKICKING(o, h, l, c)
    features['CDLKICKINGBYLENGTH'] = ta.CDLKICKINGBYLENGTH(o, h, l, c)
    features['CDLLADDERBOTTOM'] = ta.CDLLADDERBOTTOM(o, h, l, c)
    features['CDLLONGLEGGEDDOJI'] = ta.CDLLONGLEGGEDDOJI(o, h, l, c)
    features['CDLMARUBOZU'] = ta.CDLMARUBOZU(o, h, l, c)
    features['CDLMATCHINGLOW'] = ta.CDLMATCHINGLOW(o, h, l, c)
    features['CDLMATHOLD'] = ta.CDLMATHOLD(o, h, l, c, penetration=0)
    features['CDLMORNINGDOJISTAR'] = ta.CDLMORNINGDOJISTAR(o,
                                                           h,
                                                           l,
                                                           c,
                                                           penetration=0)
    features['CDLMORNINGSTAR'] = ta.CDLMORNINGSTAR(o, h, l, c, penetration=0)
    features['CDLONNECK'] = ta.CDLONNECK(o, h, l, c)
    features['CDLPIERCING'] = ta.CDLPIERCING(o, h, l, c)
    features['CDLRICKSHAWMAN'] = ta.CDLRICKSHAWMAN(o, h, l, c)
    features['CDLRISEFALL3METHODS'] = ta.CDLRISEFALL3METHODS(o, h, l, c)
    features['CDLSEPARATINGLINES'] = ta.CDLSEPARATINGLINES(o, h, l, c)
    features['CDLSHOOTINGSTAR'] = ta.CDLSHOOTINGSTAR(o, h, l, c)
    features['CDLSHORTLINE'] = ta.CDLSHORTLINE(o, h, l, c)
    features['CDLSPINNINGTOP'] = ta.CDLSPINNINGTOP(o, h, l, c)
    features['CDLSTALLEDPATTERN'] = ta.CDLSTALLEDPATTERN(o, h, l, c)
    features['CDLSTICKSANDWICH'] = ta.CDLSTICKSANDWICH(o, h, l, c)
    features['CDLTAKURI'] = ta.CDLTAKURI(o, h, l, c)
    features['CDLTASUKIGAP'] = ta.CDLTASUKIGAP(o, h, l, c)
    features['CDLTHRUSTING'] = ta.CDLTHRUSTING(o, h, l, c)
    features['CDLTRISTAR'] = ta.CDLTRISTAR(o, h, l, c)
    features['CDLUNIQUE3RIVER'] = ta.CDLUNIQUE3RIVER(o, h, l, c)
    features['CDLUPSIDEGAP2CROWS'] = ta.CDLUPSIDEGAP2CROWS(o, h, l, c)
    features['CDLXSIDEGAP3METHODS'] = ta.CDLXSIDEGAP3METHODS(o, h, l, c)

    window = 5
    features_ext = features
    for w in range(window):
        tmp = features.shift(periods=60 * (w + 1), freq='S')
        tmp.columns = [c + '_' + str(w + 1) + 'w' for c in features.columns]
        features_ext = pd.concat([features_ext, tmp], axis=1)
    return features_ext
Пример #13
0
def trades():
    print(datetime.datetime.now())
    cancel_order()
    #获取持仓
    holding_result = futureAPI.get_specific_position(future_id)
    # print(holding_result)
    #获取多仓可平仓数量,空仓可平仓数量
    long_amount = holding_result['holding'][0]['long_avail_qty']
    short_amount = holding_result['holding'][0]['short_avail_qty']
    #获取多仓数量、空仓数量
    long_qty = float(holding_result['holding'][0]['long_qty'])
    short_qty = float(holding_result['holding'][0]['short_qty'])
    #获取多仓收益率、空仓收益率
    long_ratio = float(holding_result['holding'][0]['long_pnl_ratio'])
    short_ratio = float(holding_result['holding'][0]['short_pnl_ratio'])
    #获取多仓收益、空仓收益
    long_pnl = float(holding_result['holding'][0]['long_pnl'])
    short_pnl = float(holding_result['holding'][0]['short_pnl'])

    print('多仓数量:', long_qty, '可平:', long_amount, '空仓数量:', short_qty, '可平:',
          short_amount)
    print('多仓收益:', long_pnl, '多仓收益率:', long_ratio)
    print('空仓收益:', short_pnl, '空仓收益率:', short_ratio)
    k_result = futureAPI.get_kline('BTC-USDT-200515', '')
    df = pd.DataFrame(
        k_result,
        columns=['time', 'open', 'high', 'low', 'close', 'volume', 'vc'])
    upper_band, middle_band, lower_band = talib.BBANDS(
        df['close'].apply(float).values, timeperiod=20, nbdevup=2, nbdevdn=2)
    pre_close_price = float(df['close'].values[-1])
    print(pre_close_price, upper_band[-1], lower_band[-1])

    #止盈止损部分
    #多仓平多止盈
    if float(long_amount) > 0 and long_ratio > 0.06:
        price_depth = futureAPI.get_depth('BTC-USDT-200515', '2', '')
        sell_price = price_depth['asks'][1][0]
        order_result = futureAPI.take_order(instrument_id=future_id,
                                            type='3',
                                            order_type='0',
                                            price=sell_price,
                                            size=long_amount,
                                            match_price='0')
        print('多仓平多止盈')
    #空仓平空止盈
    if float(short_amount) > 0 and short_ratio > 0.06:
        price_depth = futureAPI.get_depth('BTC-USDT-200515', '2', '')
        buy_price = price_depth['bids'][1][0]
        order_result = futureAPI.take_order(instrument_id=future_id,
                                            type='4',
                                            order_type='0',
                                            price=buy_price,
                                            size=short_amount,
                                            match_price='0')
        print('空仓平空止盈')
    #多仓平多止损
    if float(long_amount) > 0 and long_ratio < -0.03:
        price_depth = futureAPI.get_depth('BTC-USDT-200515', '2', '')
        sell_price = price_depth['asks'][1][0]
        order_result = futureAPI.take_order(instrument_id=future_id,
                                            type='3',
                                            order_type='0',
                                            price=sell_price,
                                            size=long_amount,
                                            match_price='0')
        print('多仓平多止损')
    #空仓平空止损
    if float(short_amount) > 0 and short_ratio < -0.03:
        price_depth = futureAPI.get_depth('BTC-USDT-200515', '2', '')
        buy_price = price_depth['bids'][1][0]
        order_result = futureAPI.take_order(instrument_id=future_id,
                                            type='4',
                                            order_type='0',
                                            price=buy_price,
                                            size=short_amount,
                                            match_price='0')
        print('空仓平空止损')

    #交易部分
    #交易数量
    amount = 15
    #获取仓位信息
    holding_result = futureAPI.get_specific_position(future_id)
    #获取多仓可平仓数量,空仓可平仓数量
    long_amount = holding_result['holding'][0]['long_avail_qty']
    short_amount = holding_result['holding'][0]['short_avail_qty']

    if pre_close_price > upper_band[-1]:
        print('超出上轨')
        if float(long_amount) > 0 and float(short_amount) > 0:
            price_depth = futureAPI.get_depth('BTC-USDT-200515', '2', '')
            buy_price = price_depth['bids'][1][0]
            order_result = futureAPI.take_order(instrument_id=future_id,
                                                type='4',
                                                order_type='0',
                                                price=buy_price,
                                                size=short_amount,
                                                match_price='0')
            print('有空有多,平空持多,持有多仓:', long_amount)
        if float(short_amount) > 0 and float(long_amount) == 0:
            price_depth = futureAPI.get_depth('BTC-USDT-200515', '2', '')
            #平空
            buy_price = price_depth['bids'][1][0]
            order_result = futureAPI.take_order(instrument_id=future_id,
                                                type='4',
                                                order_type='0',
                                                price=buy_price,
                                                size=short_amount,
                                                match_price='0')
            #开多
            order_result = futureAPI.take_order(instrument_id=future_id,
                                                type='1',
                                                order_type='0',
                                                price=buy_price,
                                                size=str(amount),
                                                match_price='0')
            print('有空无多,平空开多')
        if float(short_amount) == 0 and float(long_amount) > 0:
            print('无空有多,持有多仓:', long_amount)
        if float(short_amount) == 0 and float(long_amount) == 0:
            price_depth = futureAPI.get_depth('BTC-USDT-200515', '2', '')
            buy_price = price_depth['bids'][1][0]
            order_result = futureAPI.take_order(instrument_id=future_id,
                                                type='1',
                                                order_type='0',
                                                price=buy_price,
                                                size=str(amount),
                                                match_price='0')
            print('无空无多,买入开多')
    if pre_close_price < lower_band[-1]:
        print('低于下轨')
        if float(long_amount) > 0 and float(short_amount) > 0:
            #平多
            price_depth = futureAPI.get_depth('BTC-USDT-200515', '2', '')
            sell_price = price_depth['asks'][1][0]
            order_result = futureAPI.take_order(instrument_id=future_id,
                                                type='3',
                                                order_type='0',
                                                price=sell_price,
                                                size=long_amount,
                                                match_price='0')
            print('有多有空,平多持空,持有空仓:', short_amount)
        if float(long_amount) > 0 and float(short_amount) == 0:
            #平多
            price_depth = futureAPI.get_depth('BTC-USDT-200515', '2', '')
            sell_price = price_depth['asks'][1][0]
            order_result = futureAPI.take_order(instrument_id=future_id,
                                                type='3',
                                                order_type='0',
                                                price=sell_price,
                                                size=long_amount,
                                                match_price='0')
            #开空
            order_result = futureAPI.take_order(instrument_id=future_id,
                                                type='2',
                                                order_type='0',
                                                price=sell_price,
                                                size=str(amount),
                                                match_price='0')
            print('有多无空,平多开空')
        if float(long_amount) == 0 and float(short_amount) > 0:
            print('无多有空,持有空仓:', short_amount)
        if float(long_amount) == 0 and float(short_amount) == 0:
            price_depth = futureAPI.get_depth('BTC-USDT-200515', '2', '')
            sell_price = price_depth['asks'][1][0]
            order_result = futureAPI.take_order(instrument_id=future_id,
                                                type='2',
                                                order_type='0',
                                                price=sell_price,
                                                size=str(amount),
                                                match_price='0')
            print('无多无空,卖出开空')
    else:
        print('区间内运行')
    time.sleep(60)
Пример #14
0
def procBar(bar1, bar2, pos, trade):
    global pairSeries
    global tsPairratio
    global tsZscore
    global tsDates
    global indSmaZscore
    global intDatapoints
    global sentEntryOrder
    global sentExitOrder
    global intSMALength
    global dblUpperThreshold
    global dblLowerThreshold
    global instPair1Factor
    global instPair2Factor
    global dblQty
    global dblQty2
    global crossAbove
    global crossBelow

    if bar1['Close'] > 0 and bar2['Close'] > 0:
        xd = bar1['Close'] * instPair1Factor
        yd = bar2['Close'] * instPair2Factor
        sym1 = bar1['Symbol']
        sym2 = bar2['Symbol']
        logging.info("s106:procBar:" + sym1 + "," + sym2)
        if not pairSeries.has_key(sym1):
            pairSeries[sym1] = list()
        if not pairSeries.has_key(sym2):
            pairSeries[sym2] = list()
        if not tsPairratio.has_key(sym1 + sym2):
            tsPairratio[sym1 + sym2] = list()
        if not tsPairratio.has_key(sym2 + sym1):
            tsPairratio[sym2 + sym1] = list()
        if not tsZscore.has_key(sym1 + sym2):
            tsZscore[sym1 + sym2] = list()
        if not tsZscore.has_key(sym2 + sym1):
            tsZscore[sym2 + sym1] = list()
        if not tsDates.has_key(sym1):
            tsDates[sym1] = list()
        if not tsDates.has_key(sym2):
            tsDates[sym2] = list()
        if not tsDates.has_key(sym1 + sym2):
            tsDates[sym1 + sym2] = list()
        if not tsDates.has_key(sym2 + sym1):
            tsDates[sym2 + sym1] = list()
        if not crossAbove.has_key(sym1 + sym2):
            crossAbove[sym1 + sym2] = False
        if not crossBelow.has_key(sym1 + sym2):
            crossBelow[sym1 + sym2] = False
        if not sentEntryOrder.has_key(sym1 + sym2):
            sentEntryOrder[sym1 + sym2] = False
        if not sentExitOrder.has_key(sym1 + sym2):
            sentExitOrder[sym1 + sym2] = False

        if bar1['Date'] not in tsDates[sym1]:
            pairSeries[sym1].append(bar1['Close'])
            tsDates[sym1].append(bar1['Date'])

        if bar2['Date'] not in tsDates[sym2]:
            pairSeries[sym2].append(bar2['Close'])
            tsDates[sym2].append(bar2['Date'])

        dblRatioData = bar1['Close'] / bar2['Close']
        tsPairratio[sym1 + sym2].append(dblRatioData)

        dblRatioData2 = bar2['Close'] / bar1['Close']
        tsPairratio[sym2 + sym1].append(dblRatioData2)

        if len(tsPairratio[sym1 + sym2]) < intDatapoints or len(
                tsPairratio[sym2 + sym1]) < intDatapoints:
            return []

        iStart = len(tsPairratio[sym1 + sym2]) - intDatapoints
        iEnd = len(tsPairratio[sym1 + sym2]) - 1
        dblAverage = np.mean(tsPairratio[sym1 + sym2][iStart:iEnd])
        dblRatioStdDev = np.std(tsPairratio[sym1 + sym2][iStart:iEnd])
        dblResidualsData = (dblRatioData - dblAverage)
        dblZscoreData = (dblRatioData - dblAverage) / dblRatioStdDev
        tsZscore[sym1 + sym2].append(dblZscoreData)
        tsDates[sym1 + sym2].append(bar1['Date'])

        iStart2 = len(tsPairratio[sym2 + sym1]) - intDatapoints
        iEnd2 = len(tsPairratio[sym2 + sym1]) - 1
        dblAverage2 = np.mean(tsPairratio[sym2 + sym1][iStart2:iEnd2])
        dblRatioStdDev2 = np.std(tsPairratio[sym2 + sym1][iStart2:iEnd2])
        dblResidualsData2 = (dblRatioData2 - dblAverage2)
        dblZscoreData2 = (dblRatioData2 - dblAverage2) / dblRatioStdDev2
        tsZscore[sym2 + sym1].append(dblZscoreData2)
        tsDates[sym2 + sym1].append(bar2['Date'])

        signals = pd.DataFrame()
        signals['Date'] = tsDates[sym1 + sym2]
        signals['tsZscore'] = tsZscore[sym1 + sym2]
        signals['tsZscore2'] = tsZscore[sym2 + sym1]
        #signals['indSmaZscore']=pd.rolling_mean(signals['tsZscore'], intSMALength, min_periods=1)
        #signals['indSmaZscore2']=pd.rolling_mean(signals['tsZscore2'], intSMALength, min_periods=1)

        (signals['indBbu'], signals['indBbm'], signals['indBbl']) = ta.BBANDS(
            np.array(signals['tsZscore']),
            timeperiod=intSMALength,
            # number of non-biased standard deviations from the mean
            nbdevup=dblBBUOrder,
            nbdevdn=dblBBLOrder,
            # Moving average type: simple moving average here
            matype=0)

        (signals['indBbu2'], signals['indBbm2'],
         signals['indBbl2']) = ta.BBANDS(
             np.array(signals['tsZscore2']),
             timeperiod=intSMALength,
             # number of non-biased standard deviations from the mean
             nbdevup=dblBBUOrder,
             nbdevdn=dblBBLOrder,
             # Moving average type: simple moving average here
             matype=0)

        signals['indSmaZscore'] = ta.SMA(np.array(signals['tsZscore']),
                                         intSMALength)
        signals['indSmaZscore2'] = ta.SMA(np.array(signals['tsZscore2']),
                                          intSMALength)
        signals = signals.set_index('Date')

        #				tsPricePair1.Add(bar1['Date']Time, bar1['Close']);
        #			tsPricePair2.Add(bar2['Date']Time, bar2['Close']);
        #				double dblBeta = tsPricePair1.GetCovariance( tsPricePair2 ) /tsPricePair1.GetVariance(Bars.Ago(intDatapoints).DateTime,	Bars.Ago(1).DateTime);

        #print 'ZScore:' + str(dblZscoreData) + ' Upper: ' +  str(dblUpperThreshold) +  + ' Lower: ' +  str(dblLowerThreshold)

        if len(signals['tsZscore']) < 5 or len(
                signals['indSmaZscore']) < 5 or len(
                    signals['indSmaZscore2']) < 5:
            return []

        #updateCointData();

        if trade:
            #print strOrderComment
            (crossBelow[sym1 + sym2],
             crossAbove[sym1 + sym2]) = crossCheck(signals, sym1 + sym2,
                                                   'tsZscore', 'indSmaZscore')
            (z1CBBbu, z1CABbu) = crossCheck(signals, 'bb' + sym1 + sym2,
                                            'tsZscore', 'indBbu')
            (z1CBBbl, z1CABbl) = crossCheck(signals, 'bb2' + sym1 + sym2,
                                            'tsZscore2', 'indBbl')

            #print ' crossAbove: ' + str(crossAbove) + ' crossBelow: ' + str(crossBelow)
            #crossBelow = signals['tsZscore'].iloc[-1] >= signals['indSmaZscore'].iloc[-1] and crossBelow.any()
            #crossAbove = signals['tsZscore'].iloc[-1] <= signals['indSmaZscore'].iloc[-1] and crossAbove.any()
            #print ' crossAbove: ' + str(crossAbove) + ' crossBelow: ' + str(crossBelow)
            if not sentEntryOrder[sym1 + sym2] and not pos.has_key(
                    bar1['Symbol']) and not pos.has_key(bar2['Symbol']):

                #dblQty = Math.Ceiling(1/dblBeta);
                #dblQty2 = Math.Ceiling(dblBeta);

                # Create the set of short and long simple moving averages over the
                # respective periods

                # Create a 'signal' (invested or not invested) when the short moving average crosses the long
                # moving average, but only for the period greater than the shortest moving average window



                if dblZscoreData >= dblUpperThreshold and \
                    z1CABbu:
                    #crossAbove[sym1+sym2] == 1 and \

                    #Sell(instPair1, dblQty, strOrderComment);
                    #Buy(instPair2, dblQty2, strOrderComment2);

                    #if (myParam.hasOpt)
                    #{
                    #    Sell(myParam.getSym1OptInst(PutCall.Put, bar1['Close'], this), myParam.sym1OptQty, strOrderComment);
                    #    Sell(myParam.getSym2OptInst(PutCall.Call, bar2['Close'], this), myParam.sym2OptQty, strOrderComment2);
                    #}
                    sentEntryOrder[sym1 + sym2] = True
                    sentExitOrder[sym1 + sym2] = False
                    strOrderComment = '{"Entry": 1, "Exit": 0, "symPair": "' + sym1 + sym2 + '", "zScore": ' + str(
                        round(dblZscoreData, 2)) + ', "zSMA": ' + str(
                            round(signals.iloc[-1]['indSmaZscore'], 2)) + '}'
                    strOrderComment2 = '{"Entry": 1, "Exit": 0, "symPair": "' + sym1 + sym2 + '", "zScore": ' + str(
                        round(dblZscoreData2, 2)) + ', "zSMA": ' + str(
                            round(signals.iloc[-1]['indSmaZscore2'], 2)) + '}'

                    return ([bar1['Symbol'], -abs(dblQty), strOrderComment],
                            [bar2['Symbol'],
                             abs(dblQty2), strOrderComment2])
                elif dblZscoreData <= -1 * dblUpperThreshold and \
                    z1CABbu:
                    #crossBelow[sym1+sym2] and \

                    #Buy(instPair1, dblQty, strOrderComment);
                    #Sell(instPair2, dblQty2, strOrderComment2);
                    #if (myParam.hasOpt)
                    #{
                    #    Sell(myParam.getSym1OptInst(PutCall.Call, bar1['Close'], this), myParam.sym1OptQty, strOrderComment);
                    #    Sell(myParam.getSym2OptInst(PutCall.Put, bar2['Close'], this), myParam.sym2OptQty, strOrderComment2);
                    #}
                    sentEntryOrder[sym1 + sym2] = True
                    sentExitOrder[sym1 + sym2] = False
                    strOrderComment = '{"Entry": 1, "Exit": 0, "symPair": "' + sym1 + sym2 + '", "zScore": ' + str(
                        round(dblZscoreData, 2)) + ', "zSMA": ' + str(
                            round(signals.iloc[-1]['indSmaZscore'], 2)) + '}'
                    strOrderComment2 = '{"Entry": 1, "Exit": 0, "symPair": "' + sym1 + sym2 + '", "zScore": ' + str(
                        round(dblZscoreData2, 2)) + ', "zSMA": ' + str(
                            round(signals.iloc[-1]['indSmaZscore2'], 2)) + '}'

                    return ([bar1['Symbol'],
                             abs(dblQty), strOrderComment],
                            [bar2['Symbol'], -abs(dblQty2), strOrderComment2])

            elif not sentExitOrder[sym1 + sym2] and pos.has_key(
                    bar1['Symbol']) and pos.has_key(bar2['Symbol']):

                if pos[bar1['Symbol']] < 0 and pos[bar2['Symbol']] > 0 and \
                    dblZscoreData <= dblLowerThreshold and crossAbove[sym1+sym2]==1 and z1CBBbl:
                    #Buy(instPair1, dblQty, strOrderComment);
                    #Sell(instPair2, dblQty2, strOrderComment2);

                    #if (myParam.hasOpt)
                    #{
                    #   Buy(myParam.instPair1opt, myParam.sym1OptQty, strOrderComment);
                    #   Buy(myParam.instPair2opt, myParam.sym2OptQty, strOrderComment);
                    #}
                    sentEntryOrder[sym1 + sym2] = False
                    sentExitOrder[sym1 + sym2] = True
                    strOrderComment = '{"Entry": 0, "Exit": 1, "symPair": "' + sym1 + sym2 + '", "zScore": ' + str(
                        round(dblZscoreData, 2)) + ', "zSMA": ' + str(
                            round(signals.iloc[-1]['indSmaZscore'], 2)) + '}'
                    strOrderComment2 = '{"Entry": 0, "Exit": 1, "symPair": "' + sym1 + sym2 + '", "zScore": ' + str(
                        round(dblZscoreData2, 2)) + ', "zSMA": ' + str(
                            round(signals.iloc[-1]['indSmaZscore2'], 2)) + '}'

                    return ([bar1['Symbol'],
                             abs(dblQty), strOrderComment],
                            [bar2['Symbol'], -abs(dblQty2), strOrderComment2])

                elif pos[bar1['Symbol']] > 0 and pos[bar2['Symbol']] < 0 and \
                    dblZscoreData >= -1 * dblLowerThreshold and crossBelow[sym1+sym2] == 1 and z1CBBbl:
                    #Sell(instPair1, dblQty, strOrderComment);
                    #Buy(instPair2, dblQty2, strOrderComment2);

                    #if (myParam.hasOpt)
                    #{
                    #    Buy(myParam.instPair1opt, myParam.sym1OptQty, strOrderComment);
                    #    Buy(myParam.instPair2opt, myParam.sym2OptQty, strOrderComment);
                    #}
                    sentEntryOrder[sym1 + sym2] = False
                    sentExitOrder[sym1 + sym2] = True
                    strOrderComment = '{"Entry": 0, "Exit": 1, "symPair": "' + sym1 + sym2 + '", "zScore": ' + str(
                        round(dblZscoreData, 2)) + ', "zSMA": ' + str(
                            round(signals.iloc[-1]['indSmaZscore'], 2)) + '}'
                    strOrderComment2 = '{"Entry": 0, "Exit": 1, "symPair": "' + sym1 + sym2 + '", "zScore": ' + str(
                        round(dblZscoreData2, 2)) + ', "zSMA": ' + str(
                            round(signals.iloc[-1]['indSmaZscore2'], 2)) + '}'

                    return ([bar1['Symbol'], -abs(dblQty), strOrderComment],
                            [bar2['Symbol'],
                             abs(dblQty2), strOrderComment2])
Пример #15
0
def get_feature_from_vector(vector, dtype=None):
    feature_dict = {}

    feature_dict['ema_10'] = tl.EMA(vector, timeperiod=10)
    feature_dict['ema_16'] = tl.EMA(vector, timeperiod=16)
    feature_dict['ema_22'] = tl.EMA(vector, timeperiod=22)

    feature_dict['sma_10'] = tl.SMA(vector, timeperiod=10)
    feature_dict['sma_16'] = tl.SMA(vector, timeperiod=16)
    feature_dict['sma_22'] = tl.SMA(vector, timeperiod=22)

    if dtype == 'adj_close':
        upper, middle, lower = tl.BBANDS(vector,
                                         timeperiod=20,
                                         nbdevup=2,
                                         nbdevdn=2)
        feature_dict['bbands_20_upper'] = upper
        feature_dict['bbands_20_lower'] = lower

        upper, middle, lower = tl.BBANDS(vector,
                                         timeperiod=26,
                                         nbdevup=2,
                                         nbdevdn=2)
        feature_dict['bbands_26_upper'] = upper
        feature_dict['bbands_26_lower'] = lower

        upper, middle, lower = tl.BBANDS(vector,
                                         timeperiod=32,
                                         nbdevup=2,
                                         nbdevdn=2)
        feature_dict['bbands_32_upper'] = upper
        feature_dict['bbands_32_lower'] = lower
        feature_dict['momentum_12'] = tl.MOM(vector, timeperiod=12)
        feature_dict['momentum_18'] = tl.MOM(vector, timeperiod=18)
        feature_dict['momentum_24'] = tl.MOM(vector, timeperiod=24)

        ema = tl.EMA(feature_dict['momentum_12'], timeperiod=2)
        feature_dict['momentum_to_ema_12'] = np.divide(
            feature_dict['momentum_12'], ema)
        feature_dict['ema_to_mom_12'] = ema
        ema = tl.EMA(feature_dict['momentum_18'], timeperiod=2)
        feature_dict['momentum_to_ema_18'] = np.divide(
            feature_dict['momentum_18'], ema)
        feature_dict['ema_to_mom_18'] = ema
        ema = tl.EMA(feature_dict['momentum_24'], timeperiod=2)
        feature_dict['momentum_to_ema_24'] = np.divide(
            feature_dict['momentum_24'], ema)
        feature_dict['ema_to_mom_24'] = ema

        feature_dict['rate_of_change_10'] = tl.ROCP(vector, timeperiod=10)
        feature_dict['rate_of_change_16'] = tl.ROCP(vector, timeperiod=16)
        feature_dict['rate_of_change_22'] = tl.ROCP(vector, timeperiod=22)

        macd = tl.MACD(vector, fastperiod=12, slowperiod=18)[0]
        feature_dict['macd_0_18'] = macd
        ema = tl.EMA(feature_dict['macd_0_18'], timeperiod=9)
        feature_dict['macds_0_18'] = ema
        feature_dict['macdsr_0_18'] = np.divide(feature_dict['macd_0_18'], ema)

        macd = tl.MACD(vector, fastperiod=12, slowperiod=18)[1]
        feature_dict['macd_1_18'] = macd
        ema = tl.EMA(macd, timeperiod=9)
        feature_dict['macds_1_18'] = ema
        feature_dict['macdsr_1_18'] = np.divide(feature_dict['macd_1_18'], ema)

        macd = tl.MACD(vector, fastperiod=12, slowperiod=18)[2]
        feature_dict['macd_2_18'] = macd
        ema = tl.EMA(macd, timeperiod=9)
        feature_dict['macds_2_18'] = ema
        feature_dict['macdsr_2_18'] = np.divide(feature_dict['macd_2_18'], ema)

        macd = tl.MACD(vector, fastperiod=12, slowperiod=24)[0]
        feature_dict['macd_0_24'] = macd
        ema = tl.EMA(feature_dict['macd_0_24'], timeperiod=9)
        feature_dict['macds_0_24'] = ema
        feature_dict['macdsr_0_24'] = np.divide(feature_dict['macd_0_24'], ema)

        macd = tl.MACD(vector, fastperiod=12, slowperiod=24)[1]
        feature_dict['macd_1_24'] = macd
        ema = tl.EMA(feature_dict['macd_1_24'], timeperiod=9)
        feature_dict['macds_1_24'] = ema
        feature_dict['macdsr_1_24'] = np.divide(feature_dict['macd_1_24'], ema)

        macd = tl.MACD(vector, fastperiod=12, slowperiod=24)[2]
        feature_dict['macd_2_24'] = macd
        ema = tl.EMA(feature_dict['macd_2_24'], timeperiod=9)
        feature_dict['macds_2_24'] = ema
        feature_dict['macdsr_2_24'] = np.divide(feature_dict['macd_2_24'], ema)

        macd = tl.MACD(vector, fastperiod=12, slowperiod=30)[0]
        feature_dict['macd_0_30'] = macd
        ema = tl.EMA(feature_dict['macd_0_30'], timeperiod=9)
        feature_dict['macds_0_30'] = ema
        feature_dict['macdsr_0_30'] = np.divide(feature_dict['macd_0_30'], ema)

        macd = tl.MACD(vector, fastperiod=12, slowperiod=30)[1]
        feature_dict['macd_1_30'] = macd
        ema = tl.EMA(feature_dict['macd_1_30'], timeperiod=9)
        feature_dict['macds_1_30'] = ema
        feature_dict['macdsr_1_30'] = np.divide(feature_dict['macd_1_30'], ema)

        macd = tl.MACD(vector, fastperiod=12, slowperiod=30)[2]
        feature_dict['macd_2_30'] = macd
        ema = tl.EMA(feature_dict['macd_2_30'], timeperiod=9)
        feature_dict['macds_2_30'] = ema
        feature_dict['macdsr_2_30'] = np.divide(feature_dict['macd_2_30'], ema)

        feature_dict['rsi_8'] = tl.RSI(vector, timeperiod=8)
        feature_dict['rsi_14'] = tl.RSI(vector, timeperiod=14)
        feature_dict['rsi_20'] = tl.RSI(vector, timeperiod=20)
    return feature_dict
Пример #16
0
def strategy_five(series, is_backtest=True):
    '''策略:布林通道宽度、金叉死叉、顺势而为、KDJ零百转换、随机漫步'''
    # 实时线
    close = np.cumsum(series).astype(float)

    # 布林通道宽度
    upperband, middleband, lowerband = ta.BBANDS(close,
                                                 timeperiod=5,
                                                 nbdevup=2,
                                                 nbdevdn=2,
                                                 matype=0)
    bandwidth = upperband - lowerband
    mean = np.nan_to_num(bandwidth).mean()

    # 金叉死叉
    ma_fast = ta.MA(close, timeperiod=8, matype=0)
    ma_slow = ta.MA(close, timeperiod=20, matype=0)

    # 顺势而为
    ma = ta.MA(close, timeperiod=10, matype=0)
    ma = np.nan_to_num(ma)  #Nan转换为0

    # KDJ极限
    fastk, fastd = ta.STOCHRSI(close,
                               timeperiod=14,
                               fastk_period=10,
                               fastd_period=5,
                               fastd_matype=0)

    # 随机漫步
    rnd = []

    signals = []
    current_signal = [0] * 5  # 当前信号:无

    # 如果是回测
    if is_backtest:
        pre_is_right = True  # 哨兵:上期投注正确
        earn = []  # 收益记录
        order = []  # 投注资金记录

        for i in range(2, len(series)):

            # 布林通道宽度
            #if bandwidth[i-1] < bandwidth[i]: # 增:趋势区间
            if bandwidth[i - 1] > mean:  # 宽:趋势区间
                current_signal[0] = series[i - 1]  # 与前一期相同 //与前一期(趋势)相同
            else:  # 窄:震荡区间
                current_signal[0] = -series[i - 1]  # 与前一期相反

            # 金叉死叉
            y1, y2 = ma_fast[i - 2], ma_fast[i - 1]
            y3, y4 = ma_slow[i - 2], ma_slow[i - 1]
            if y1 < y3 and y2 > y4:  # 金叉
                current_signal[1] = 1
            elif y1 > y3 and y2 < y4:  # 死叉
                current_signal[1] = -1

            # 顺势而为
            if ma[i - 2] < ma[i - 1]:  # 上升趋势
                current_signal[2] = 1
            else:  # 下降趋势
                current_signal[2] = -1

            # KDJ极限
            if fastk[i - 1] == 0:  # 上升趋势
                current_signal[3] = 1
            elif fastk[i] == 100:  # 下降趋势
                current_signal[3] = -1

            # 随机漫步
            rnd.append(np.random.choice([-1, 1]))
            current_signal[4] = rnd[-1]

            # 若无信号,跳过,不做任何操作
            if sum(current_signal) == 0: continue

            # 看料
            buy = [-1, 1][sum(current_signal) > 0]

            if i < len(series) - 1:  # 若不是最后一期,则
                signals.append(buy)

                # 下单
                order.append(times[error_periods])

                # 判断对错,计算收益
                if buy == series[i]:
                    error_periods = 0  # 错误期数置零
                    earn.append(odds * order[-1])  # 赔率odds=1.96
                else:
                    error_periods += 1  # 错误期数加一
                    earn.append(0)
            else:
                print(buy)

        print('投注记录:\n', order[-show_period:], '\n合计:',
              sum(order[-show_period:]))
        print('收益记录:\n', earn[-show_period:], '\n合计:',
              sum(earn[-show_period:]))
        print('收益率:', (sum(earn[-show_period:]) - sum(order[-show_period:])) /
              sum(order[-show_period:]))

        return order, earn, signals
    else:
        # 布林通道宽度
        if bandwidth[-1] > mean:  # 宽:趋势区间
            current_signal[0] = series[-1]  # 与前一期相同 //与前一期(趋势)相同
        else:  # 窄:震荡区间
            current_signal[0] = -series[-1]  # 与前一期相反

        # 金叉死叉
        y1, y2 = ma_fast[-2], ma_fast[-1]
        y3, y4 = ma_slow[-2], ma_slow[-1]
        if y1 < y3 and y2 > y4:  # 金叉
            current_signal[1] = 1
        elif y1 > y3 and y2 < y4:  # 死叉
            current_signal[1] = -1

        # 顺势而为
        if ma[-2] < ma[-1]:  # 上升趋势
            current_signal[2] = 1
        else:  # 下降趋势
            current_signal[2] = -1

        # KDJ极限
        if fastk[-1] == 0:  # 上升趋势
            current_signal[3] = 1
        elif fastk[-1] == 100:  # 下降趋势
            current_signal[3] = -1

        # 随机漫步
        current_signal[4] = np.random.choice([-1, 1])

        print('=' * 30)
        print('五种综合: ', end='')
        print_red_color_text([-1, 1][sum(current_signal) > 0])
        print('=' * 30)

        return [-1, 1][sum(current_signal) > 0]
Пример #17
0
        df.loc[idx, 'total_money'] = record_info['money_remain'] + record_info[
            'amount_remain'] * df.loc[idx, 'close']

    return df.tail(1)['total_money'].values[0]


if __name__ == '__main__':
    """ ----------------------- 准备训练数据 ------------------------------  """
    stk_code = '300508'
    sh_index = ts.get_k_data(code=stk_code)

    closed = sh_index['close'].values
    sh_index['upper'], sh_index['middle'], sh_index['lower'] = talib.BBANDS(
        closed,
        timeperiod=10,
        # number of non-biased standard deviations from the mean
        nbdevup=2,
        nbdevdn=2,
        # Moving average type: simple moving average here
        matype=0)

    sh_index = sh_index.dropna(how='any').tail(100)
    """ --------------------- 定义 ------------------------ """
    r_bit_len = 5  # 网格二进制长度
    r_amount = 3  # 网格数量

    DNA_SIZE = r_bit_len * r_amount  # DNA 长度
    POP_SIZE = 100  # 种群大小
    CROSS_RATE = 0.8  # mating probability (DNA crossover)
    MUTATION_RATE = 0.03  # mutation probability
    N_GENERATIONS = 200  # 种群代数
    X_BOUND = [0, 20]  # 基因的上下限(此处应该设置为“相对price”的上下限)
Пример #18
0
print("Current Time =", current_time)
RSI_OVERBOUGHT = 75
RSI_OVERSOLD = 30
cols = ['T', 'O', 'H', 'L', 'C', 'V']
data = pd.read_csv('data/live.csv')
df = pd.DataFrame(data)
df.drop(df.columns[6:], axis=1, inplace=True)
df.columns = cols
df['EMA30'] = EMA(df.C, 90)
df['EMA20'] = EMA(df.C, 10)
df['EMA10'] = EMA(df.C, 5)
df['EMA200'] = EMA(df.C, 90)
df.loc[(df['EMA10'] >= df['EMA200']), 'emaUptrend'] = True
df.loc[(df['EMA10'] <= df['EMA200']), 'emaDowntrend'] = True
df['RSI'] = talib.RSI(df.C)
df['upper'], df['middle'], df['lower'] = talib.BBANDS(df.C, matype=MA_Type.T3)
df['BBsellSig'] = df.C > df.upper
df['BBbuySig'] = df.C < df.lower
df['BBsellSig'] = df.C > df.upper
df['rsiOversold'] = df.RSI < RSI_OVERSOLD
df['rsiOverbought'] = df.RSI > RSI_OVERBOUGHT
df['macd'], df["sig"], df['diff'] = MACDFIX(df.C)
df.loc[(df['diff'] >= 0), 'macdBuy'] = True
df.loc[(df['EMA20'] <= df['EMA30']) & (df['EMA10'] <= df['EMA20']) &
       (df['C'] <= df['EMA10']), 'EMAsellSig'] = True
df.loc[(df['EMA20'] >= df['EMA30']) & (df['EMA10'] >= df['EMA20']) &
       (df['C'] >= df['EMA10']), 'EMAbuySig'] = True

###BUY
df.loc[(df.emaUptrend & df.macdBuy), 'BUY'] = 1
##SELL
Пример #19
0
def attribute_gen(data):
    '''
        generate attributes from cleansed data of local database
    :param data: is tick level np.array with 28 columns
    :return: X, y, Xpred are dataframe with datetime index
    '''
    #######################################################################################
    # indexed by datetime
    data_indexed = pd.DataFrame(data)
    data_indexed = data_indexed.set_index(
        2)  # the original 28 column is removed automatically
    data_indexed.drop([0, 1], axis=1, inplace=True)  # 8503
    # type(data_indexed[7][0])  # it is int, we need float instead
    data_indexed[7] = data_indexed[7].astype(float)

    #######################################################################################
    '''
    # five minutes first & last & mean
    # 1
    data_indexed_5m_first = data_indexed.resample('5T').first()
    data_indexed_5m_first = data_indexed_5m_first.between_time('9:30', '15:00')

    inde = data_indexed_5m_first[data_indexed_5m_first[3].isna()].index
    data_indexed_5m_first.drop(inde, inplace=True)
    # data_indexed_5m_first = data_indexed_5m_first.fillna(method='backfill')
    data_indexed_5m_first.drop(data_indexed_5m_first.tail(1).index, inplace=True)
    data_indexed_5m_first.drop(data_indexed_5m_first.tail(1).index, inplace=True)

    # 2
    data_indexed_5m_last = data_indexed.resample('5T').last()  # 354
    data_indexed_5m_last = data_indexed_5m_last.between_time('9:30', '15:00')  # 133
    inde = data_indexed_5m_last[data_indexed_5m_last[3].isna()].index
    data_indexed_5m_last.drop(inde, inplace=True)  # 96
    # data_indexed_5m_last = data_indexed_5m_last.fillna(method='backfill')
    # cut the last item
    data_indexed_5m_last.drop(data_indexed_5m_last.tail(1).index, inplace=True)

    # 3

    data_indexed_5m_last = data_indexed_5m_last.between_time('9:30', '15:00')  # 133
    inde = data_indexed_5m_last[data_indexed_5m_last[3].isna()].index
    data_indexed_5m_last.drop(inde, inplace=True)  # 96
    # data_indexed_5m_last = data_indexed_5m_last.fillna(method='backfill')
    # cut the last item
    data_indexed_5m_last.drop(data_indexed_5m_last.tail(1).index, inplace=True)

    # 4
    data_indexed_5m_change = data_indexed_5m_last - data_indexed_5m_first
    '''
    ########################################################################################
    # five minutes current price last & change & max & min
    data_cp = pd.DataFrame(data[:, [2, 3]])  # data is np.array()
    data_cp = data_cp.set_index(0)
    data_cplast = data_cp.resample('5T').last()  # 354
    inde = data_cplast[data_cplast[1].isna()].index
    data_cplast.drop(inde, inplace=True)  # 96

    # data_cpfirst = data_cp.resample('5T').first()  # 354
    # inde = data_cpfirst[data_cpfirst[1].isna()].index
    # data_cpfirst.drop(inde, inplace=True)  # 96

    data_cprice_change = data_cplast.diff()
    data_cprice_change = data_cprice_change.fillna(method='bfill')

    # data_cpratio = data_cplast/data_cpfirst
    # move one step forward
    # data_cprice_change = data_cprice_change[1][data_cprice_change.index[1:len(data_cprice_change)]]
    # cut the last item
    # data_cplast = data_cplast[1][data_cplast.index[0:len(data_cplast) - 1]]

    data_cpmax = data_cp.resample('5T').max()  # 354
    indexname = data_cpmax[data_cpmax[1].isna()].index
    data_cpmax.drop(indexname, inplace=True)  # 96
    # ?????? doesn't work: data_cpmax = data_cpmax.resample('5T').agg(lambda x: max(x[i]) for i in range(len(x)))  # 354
    # cut the last item
    # data_cpmax = data_cpmax[1][data_cpmax.index[0:len(data_cpmax)-1]]

    data_cpmin = data_cp.resample('5T').min()  # 354
    ind = data_cpmin[data_cpmin[1].isna()].index
    data_cpmin.drop(ind, inplace=True)  # 96
    # cut the last item
    # data_cpmin = data_cpmin[1][data_cpmin.index[0:len(data_cpmin)-1]]

    data_cp = pd.DataFrame()
    data_cp['max'] = data_cpmax[1]
    data_cp['min'] = data_cpmin[1]
    data_cp['last'] = data_cplast[1]
    data_cp['change'] = data_cprice_change[1]
    # data_cp['ratio'] = data_cpratio[1]  ratio can not increase forecast accuracy

    ######################################################################################################
    # flag data
    data_flag = pd.DataFrame(data[:, [2, 7]])
    data_flag = data_flag.set_index(0)
    data_flag_plus = data_flag
    data_flag_minus = data_flag

    # data_flag_plus[1][data_flag_plus[1] == -1] = 0
    # data_flag_minus[1][data_flag_minus[1] == 1] = 0
    # data_flag_minus[1][data_flag_minus[1] == -1] = 1

    # flagtry = list(map(lambda x: x+1 if x == -1 else x, data_flag_plus[1]))
    data_flag_plus = data_flag_plus.applymap(lambda x: x + 1 if x == -1 else x)
    data_flag_minus = data_flag_minus.applymap(lambda x: x - 1
                                               if x == 1 else x + 2)

    data_flag_plsum = data_flag_plus.resample('5T').sum()  # 354
    data_flag_misum = data_flag_minus.resample('5T').sum()  # 354
    # index = data_flag_plsum[data_flag_plsum[1] == 0].index
    data_flag_plsum.drop(inde, inplace=True)  # 96
    data_flag_misum.drop(inde, inplace=True)  # 96
    data_flag_ratio = data_flag_plsum / data_flag_misum  # 96
    flag = pd.DataFrame()
    flag['psum'] = data_flag_plsum[1]
    # flag['msum'] = data_flag_misum[1]
    flag['ratio'] = data_flag_ratio[1]
    # cut the last item
    # flag.drop(flag.tail(1).index, inplace=True)

    ####################################################################################
    '''
    data_flag = pd.Series(data_flag[1])  # the index is attached automatically
    data_flag = data_flag.resample('5T').agg(lambda x: x[-1]/x[1] - 1)
    index = data_indexed_5m_first[data_flag[3].isna()].index
    data_flag.drop(index, inplace=True)
    data_flag = data_flag.fillna(method='backfill')
    '''
    # standardize money (column five)
    data_money = pd.DataFrame(data[:, [2, 5]])  # data is np.array()
    data_money = data_money.set_index(0)
    data_money = pd.Series(data_money[1])
    data_money_5m = data_money.resample('5T').sum()  # 354
    ind = data_money_5m[data_money_5m == 0.0].index
    data_money_5m.drop(ind, inplace=True)  # 96
    data_money_5m_d = data_money_5m.diff()
    data_money_5m_d = data_money_5m_d.fillna(method='backfill')
    # cut the last item
    # data_money_5m_d.drop(data_money_5m_d.tail(1).index, inplace=True)
    data_money = pd.DataFrame()
    data_money['money'] = data_money_5m
    data_money['diff'] = data_money_5m_d

    #########################################################################################################
    # MACD
    macd = data_indexed[3]  # 8503
    macd = pd.DataFrame(macd)
    macd_12_ema = macd.ewm(span=12, adjust=False).mean()
    macd_26_ema = macd.ewm(span=26, adjust=False).mean()
    macd_real = macd_12_ema - macd_26_ema
    macd_reference = macd_real.ewm(span=9, adjust=False).mean()
    # transform to 5 minutes' frequency
    mmaa = pd.DataFrame()
    mmaa['12'] = macd_12_ema[3]
    mmaa['26'] = macd_26_ema[3]
    mmaa['real'] = macd_real[3]
    mmaa['refer'] = macd_reference[3]
    mmaa_5m = mmaa.resample('5T')
    mmaa_5m_mean = mmaa_5m.mean()  # 354
    indd = mmaa_5m_mean[mmaa_5m_mean['12'].isna()].index
    mmaa_5m_mean.drop(indd, inplace=True)  # 96
    # cut the last item
    # mmaa_5m_mean.drop(mmaa_5m_mean.tail(1).index, inplace=True)  # 95

    # macd, macdsignal, macdhist = talib.MACD(close, fastperiod=12,
    #                                         slowperiod=26, signalperiod=9)

    ####################################################################################
    high = data_cpmax[1]
    low = data_cpmin[1]
    close = data_cplast[1]

    data_vol = pd.DataFrame(data[:, [2, 6]])  # data is np.array()
    data_vol = data_vol.set_index(0)
    data_vol = pd.Series(data_vol[1])
    data_vol_5m = data_vol.resample('5T').sum()  # 354
    ind = data_vol_5m[data_vol_5m == 0.0].index
    data_vol_5m.drop(ind, inplace=True)  # 96
    volume = data_vol_5m
    ####################################################################################
    # sma of current price
    data_sma_20 = talib.SMA(np.asarray(close), 20)
    data_sma_20 = pd.DataFrame(data_sma_20)
    data_sma_20 = data_sma_20.fillna(method='backfill')

    data_sma_10 = talib.SMA(np.asarray(close), 10)
    data_sma_10 = pd.DataFrame(data_sma_10)
    data_sma_10 = data_sma_10.fillna(method='backfill')

    data_sma_5 = talib.SMA(np.asarray(close), 5)
    data_sma_5 = pd.DataFrame(data_sma_5)
    data_sma_5 = data_sma_5.fillna(method='backfill')

    data_sma = pd.DataFrame()
    data_sma['5'] = data_sma_5[0]
    data_sma['10'] = data_sma_10[0]
    data_sma['20'] = data_sma_20[0]
    data_sma['0'] = volume.index
    data_sma = data_sma.set_index('0')

    ####################################################################################
    # Average Directional Movement Index
    # real = talib.ADX(high, low, close, timeperiod=14)
    direct_move = talib.ADX(high, low, close, timeperiod=14)
    direct_move = direct_move.fillna(method='backfill')

    ########################################################################################
    # Absolute Price Oscillator
    oscillator = talib.APO(close, fastperiod=12, slowperiod=26, matype=0)
    oscillator = oscillator.fillna(method='backfill')

    ########################################################################################
    # macd fix
    macdfix, macdsignal, macdhist = talib.MACDFIX(close,
                                                  signalperiod=9)  # nan 40
    macdfix.fillna(method='backfill')

    #########################################################################################
    # money flow
    money_flow = talib.MFI(high, low, close, volume, timeperiod=14)
    money_flow.fillna(method='backfill')

    #########################################################################################
    # minus directional indicator
    minus_direct = talib.MINUS_DI(high, low, close, timeperiod=14)
    minus_direct.fillna(method='backfill')

    #########################################################################################
    # momentum of the close prices, with a time period of 5:
    mom = talib.MOM(close, timeperiod=10)
    mom = mom.fillna(method='backfill')

    #########################################################################################
    # PLUS_DI - Plus Directional Indicator
    plus_direct = talib.PLUS_DI(high, low, close, timeperiod=14)
    plus_direct = plus_direct.fillna(method='backfill')

    #########################################################################################
    # PLUS_DM - Plus Directional Movement
    plus_direct_move = talib.PLUS_DM(high, low, timeperiod=14)
    plus_direct_move = plus_direct_move.fillna(method='backfill')

    #########################################################################################
    # PPO - Percentage Price Oscillator
    percent_oscillator = talib.PPO(close,
                                   fastperiod=12,
                                   slowperiod=26,
                                   matype=0)
    percent_oscillator = percent_oscillator.fillna(method='backfill')

    #########################################################################################
    # ROCP - Rate of change Percentage: (price-prevPrice)/prevPrice
    rate_of_change = talib.ROCP(close, timeperiod=10)
    rate_of_change = rate_of_change.fillna(method='backfill')

    #########################################################################################
    # Rate of change ratio
    rate_ratio = talib.ROCR(close, timeperiod=10)
    rate_ratio = rate_ratio.fillna(method='backfill')

    #########################################################################################
    # RSI - Relative Strength Index
    strength = talib.RSI(close, timeperiod=14)
    strength = strength.fillna(method='backfill')

    #########################################################################################
    # STOCH - Stochastic
    slowk, slowd = talib.STOCH(high,
                               low,
                               close,
                               fastk_period=5,
                               slowk_period=3,
                               slowk_matype=0,
                               slowd_period=3,
                               slowd_matype=0)
    slowk = slowk.fillna(method='backfill')
    slowd = slowd.fillna(method='backfill')
    stochastic = pd.DataFrame()
    stochastic['slowk'] = slowk
    stochastic['slowd'] = slowd

    #########################################################################################
    # STOCHF - Stochastic Fast
    fastk, fastd = talib.STOCHF(high,
                                low,
                                close,
                                fastk_period=5,
                                fastd_period=3,
                                fastd_matype=0)
    fastk = fastk.fillna(method='backfill')
    fastd = fastd.fillna(method='backfill')
    fast = pd.DataFrame()
    fast['fastk'] = fastk
    fast['fastd'] = fastd

    #########################################################################################
    # STOCHRSI - Stochastic Relative Strength Index
    fastk, fastd = talib.STOCHRSI(close,
                                  timeperiod=14,
                                  fastk_period=5,
                                  fastd_period=3,
                                  fastd_matype=0)
    fastk = fastk.fillna(method='backfill')
    fastd = fastd.fillna(method='backfill')
    relative_strength = pd.DataFrame()
    relative_strength['fastk'] = fastk
    relative_strength['fastd'] = fastd

    #########################################################################################
    # ULTOSC - Ultimate Oscillator
    ulti_osci = talib.ULTOSC(high,
                             low,
                             close,
                             timeperiod1=7,
                             timeperiod2=14,
                             timeperiod3=28)
    ulti_osci = ulti_osci.fillna(method='backfill')

    #########################################################################################
    # WILLR - Williams' %R
    willer = talib.WILLR(high, low, close, timeperiod=14)
    willer = willer.fillna(method='backfill')

    #########################################################################################
    # buy sell info factors
    buy_sell = data[:, 8:28]
    buy_sell = pd.DataFrame(buy_sell, index=data[:, 2])
    # col 8-12 buy price, col 13-17 sell price,
    # col 18-22 buy quant, col 23-27 sell quant
    buy_sell_5m = buy_sell.resample('5T').last()  # 354
    inde = buy_sell_5m[buy_sell_5m[1].isna()].index
    buy_sell_5m.drop(inde, inplace=True)  # 96

    #########################################################################################
    # bollinger bands, with triple exponential moving average:
    from talib import MA_Type
    upper, middle, lower = talib.BBANDS(close, matype=MA_Type.T3)
    #########################################################################################
    # generate label y
    data_cp2 = pd.DataFrame(data[:, [2, 3]])  # data is np.array()
    data_cp2 = data_cp2.set_index(0)
    data_cplast = data_cp2.resample('5T').last()  # 354
    inddd = data_cplast[data_cplast[1].isna()].index
    data_cplast.drop(inddd, inplace=True)  # 96
    pchange = data_cplast.diff()  # 96
    pchange = pchange.fillna(method='backfill')

    # cut the last item
    # data_cplast = data_cplast[1][data_cplast.index[0:len(data_cplast) - 1]]

    func = lambda x: np.sign(x) if x != 0 else np.sign(x + 1)
    pchange['sign'] = list(map(func, pchange[1]))
    # pchange.drop(pchange.head(1).index, inplace=True)  # 95
    ####################################################################################
    # generate train and label data
    X = pd.concat([
        mmaa_5m_mean, data_sma, direct_move, oscillator, macdfix, money_flow,
        minus_direct, mom, plus_direct, plus_direct_move, percent_oscillator,
        rate_of_change, rate_ratio, strength, stochastic, fast,
        relative_strength, ulti_osci, willer, data_money, flag, data_cp
    ],
                  axis=1)
    y = pchange['sign']
    price_change = data_cprice_change

    return X, y, price_change
    def extract_by_type(feature_type, open_prices=None, close_prices=None, high_prices=None, low_prices=None):
    
        if feature_type == 'ROCP':
            rocp1 = talib.ROCP(close_prices, timeperiod=1)
            rocp2 = talib.ROCP(close_prices, timeperiod=2)
            feature.append(rocp1)
            feature.append(rocp2)
        if feature_type == 'OROCP':
            orocp = talib.ROCP(open_prices, timeperiod=1)
            feature.append(orocp)
        if feature_type == 'HROCP':
            hrocp = talib.ROCP(high_prices, timeperiod=1)
            feature.append(hrocp)
        if feature_type == 'LROCP':
            lrocp = talib.ROCP(low_prices, timeperiod=1)
            feature.append(lrocp)
        if feature_type == 'MACD':
            macd, signal, hist = talib.MACD(close_prices, fastperiod=12, slowperiod=26, signalperiod=9)
            norm_macd = numpy.nan_to_num(macd) / math.sqrt(numpy.var(numpy.nan_to_num(macd)))
            norm_signal = numpy.nan_to_num(signal) / math.sqrt(numpy.var(numpy.nan_to_num(signal)))
            norm_hist = numpy.nan_to_num(hist) / math.sqrt(numpy.var(numpy.nan_to_num(hist)))
            macdrocp = talib.ROCP(norm_macd + numpy.max(norm_macd) - numpy.min(norm_macd), timeperiod=1)
            signalrocp = talib.ROCP(norm_signal + numpy.max(norm_signal) - numpy.min(norm_signal), timeperiod=1)
            histrocp = talib.ROCP(norm_hist + numpy.max(norm_hist) - numpy.min(norm_hist), timeperiod=1)
            # feature.append(macd / 100.0)
            # feature.append(signal / 100.0)
            # feature.append(hist / 100.0)
            feature.append(norm_macd)
            feature.append(norm_signal)
            feature.append(norm_hist)

            feature.append(macdrocp)
            feature.append(signalrocp)
            feature.append(histrocp)
        if feature_type == 'RSI':
            rsi6 = talib.RSI(close_prices, timeperiod=6)
            rsi12 = talib.RSI(close_prices, timeperiod=12)
            rsi24 = talib.RSI(close_prices, timeperiod=24)
            rsi6rocp = talib.ROCP(rsi6 + 100., timeperiod=1)
            rsi12rocp = talib.ROCP(rsi12 + 100., timeperiod=1)
            rsi24rocp = talib.ROCP(rsi24 + 100., timeperiod=1)
            feature.append(rsi6 / 100.0 - 0.5)
            feature.append(rsi12 / 100.0 - 0.5)
            feature.append(rsi24 / 100.0 - 0.5)
            # feature.append(numpy.maximum(rsi6 / 100.0 - 0.8, 0))
            # feature.append(numpy.maximum(rsi12 / 100.0 - 0.8, 0))
            # feature.append(numpy.maximum(rsi24 / 100.0 - 0.8, 0))
            # feature.append(numpy.minimum(rsi6 / 100.0 - 0.2, 0))
            # feature.append(numpy.minimum(rsi6 / 100.0 - 0.2, 0))
            # feature.append(numpy.minimum(rsi6 / 100.0 - 0.2, 0))
            # feature.append(numpy.maximum(numpy.minimum(rsi6 / 100.0 - 0.5, 0.3), -0.3))
            # feature.append(numpy.maximum(numpy.minimum(rsi6 / 100.0 - 0.5, 0.3), -0.3))
            # feature.append(numpy.maximum(numpy.minimum(rsi6 / 100.0 - 0.5, 0.3), -0.3))
            feature.append(rsi6rocp)
            feature.append(rsi12rocp)
            feature.append(rsi24rocp)
        if feature_type == 'UO':
            ult_osc = talib.ULTOSC(high_prices, low_prices, close_prices, timeperiod1=7, timeperiod2=14, timeperiod3=28)
            feature.append(ult_osc / 100.0 - 0.5)
        if feature_type == 'BOLL':
            upperband, middleband, lowerband = talib.BBANDS(close_prices, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)
            feature.append((upperband - close_prices) / close_prices)
            feature.append((middleband - close_prices) / close_prices)
            feature.append((lowerband - close_prices) / close_prices)         
        if feature_type == 'MA':
            ma5 = talib.MA(close_prices, timeperiod=5)
            ma10 = talib.MA(close_prices, timeperiod=10)
            ma20 = talib.MA(close_prices, timeperiod=20)
            ma25 = talib.MA(close_prices, timeperiod=25)
            ma30 = talib.MA(close_prices, timeperiod=30)
            ma40 = talib.MA(close_prices, timeperiod=40)
            ma50 = talib.MA(close_prices, timeperiod=50)
            ma60 = talib.MA(close_prices, timeperiod=60)
            #ma360 = talib.MA(close_prices, timeperiod=70)
            #ma720 = talib.MA(close_prices, timeperiod=720)
            ma5rocp = talib.ROCP(ma5, timeperiod=1)
            ma10rocp = talib.ROCP(ma10, timeperiod=1)
            ma20rocp = talib.ROCP(ma20, timeperiod=1)
            ma25rocp = talib.ROCP(ma25, timeperiod=1)
            ma30rocp = talib.ROCP(ma30, timeperiod=1)
            ma40rocp = talib.ROCP(ma40, timeperiod=1)
            ma50rocp = talib.ROCP(ma50, timeperiod=1)
            ma60rocp = talib.ROCP(ma60, timeperiod=1)
            #ma360rocp = talib.ROCP(ma360, timeperiod=1)
            #ma720rocp = talib.ROCP(ma720, timeperiod=1)
            feature.append(ma5rocp)
            feature.append(ma10rocp)
            feature.append(ma20rocp)
            feature.append(ma25rocp)
            feature.append(ma30rocp)
            feature.append(ma40rocp)
            feature.append(ma50rocp)
            feature.append(ma60rocp)
            #feature.append(ma360rocp)
            #feature.append(ma720rocp)
            feature.append((ma5 - close_prices) / close_prices)
            feature.append((ma10 - close_prices) / close_prices)
            feature.append((ma20 - close_prices) / close_prices)
            feature.append((ma25 - close_prices) / close_prices)
            feature.append((ma30 - close_prices) / close_prices)
            feature.append((ma40 - close_prices) / close_prices)
            feature.append((ma50 - close_prices) / close_prices)
            feature.append((ma60 - close_prices) / close_prices)
            #feature.append((ma360 - close_prices) / close_prices)
            #feature.append((ma720 - close_prices) / close_prices)
        if feature_type == 'STOCH':
            slow_stoch_k, slow_stoch_d = talib.STOCH(high_prices ,low_prices ,close_prices ,fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0)
            fast_stoch_k, fast_stoch_d = talib.STOCHF(high_prices , low_prices , close_prices , fastk_period=5, fastd_period=3, fastd_matype=0)
            fast_rsi_k, fast_rsi_d = talib.STOCHRSI(close_prices, timeperiod=14, fastk_period=5, fastd_period=3, fastd_matype=0)                      
            feature.append(slow_stoch_k / 100.0 - 0.5)
            feature.append(slow_stoch_d / 100.0 - 0.5)
            feature.append(fast_stoch_k / 100.0 - 0.5)
            feature.append(fast_stoch_d / 100.0 - 0.5)
            feature.append(fast_rsi_k / 100.0 - 0.5)
            feature.append(fast_rsi_d / 100.0 - 0.5)
        if feature_type == 'AO':          
            median_price = (high_prices + low_prices) / 2
            ao = talib.SMA(median_price, 5)-talib.SMA(median_price, 34)          
            feature.append(ao)
        if feature_type == 'ROC':
            roc5 = talib.ROC(close_prices, timeperiod=5)
            roc10 = talib.ROC(close_prices, timeperiod=10)
            roc20 = talib.ROC(close_prices, timeperiod=20)
            roc25 = talib.ROC(close_prices, timeperiod=25)
            feature.append(roc5)
            feature.append(roc10)
            feature.append(roc20)
            feature.append(roc25)
        if feature_type == 'WILLR':
            willr = talib.WILLR(high_prices,low_prices,close_prices, timeperiod=14)
            feature.append(willr / 100.0 - 0.5)

        return feature
Пример #21
0
def momentum_process(event):
    print(event.widget.get())
    momentum = event.widget.get()

    upperband, middleband, lowerband = ta.BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)
    fig, axes = plt.subplots(2, 1, sharex=True)
    ax1, ax2 = axes[0], axes[1]
    axes[0].plot(close, 'rd-', markersize=3)
    axes[0].plot(upperband, 'y-')
    axes[0].plot(middleband, 'b-')
    axes[0].plot(lowerband, 'y-')
    axes[0].set_title(momentum, fontproperties="SimHei")

    if momentum == '绝对价格振荡器':
        real = ta.APO(close, fastperiod=12, slowperiod=26, matype=0)
        axes[1].plot(real, 'r-')
    elif momentum == '钱德动量摆动指标':
        real = ta.CMO(close, timeperiod=14)
        axes[1].plot(real, 'r-')
    elif momentum == '移动平均收敛/散度':
        macd, macdsignal, macdhist = ta.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9)
        axes[1].plot(macd, 'r-')
        axes[1].plot(macdsignal, 'g-')
        axes[1].plot(macdhist, 'b-')
    elif momentum == '带可控MA类型的MACD':
        macd, macdsignal, macdhist = ta.MACDEXT(close, fastperiod=12, fastmatype=0, slowperiod=26, slowmatype=0, signalperiod=9, signalmatype=0)
        axes[1].plot(macd, 'r-')
        axes[1].plot(macdsignal, 'g-')
        axes[1].plot(macdhist, 'b-')
    elif momentum == '移动平均收敛/散度 固定 12/26':
        macd, macdsignal, macdhist = ta.MACDFIX(close, signalperiod=9)
        axes[1].plot(macd, 'r-')
        axes[1].plot(macdsignal, 'g-')
        axes[1].plot(macdhist, 'b-')
    elif momentum == '动量':
        real = ta.MOM(close, timeperiod=10)
        axes[1].plot(real, 'r-')
    elif momentum == '比例价格振荡器':
        real = ta.PPO(close, fastperiod=12, slowperiod=26, matype=0)
        axes[1].plot(real, 'r-')
    elif momentum == '变化率':
        real = ta.ROC(close, timeperiod=10)
        axes[1].plot(real, 'r-')
    elif momentum == '变化率百分比':
        real = ta.ROCP(close, timeperiod=10)
        axes[1].plot(real, 'r-')
    elif momentum == '变化率的比率':
        real = ta.ROCR(close, timeperiod=10)
        axes[1].plot(real, 'r-')
    elif momentum == '变化率的比率100倍':
        real = ta.ROCR100(close, timeperiod=10)
        axes[1].plot(real, 'r-')
    elif momentum == '相对强弱指数':
        real = ta.RSI(close, timeperiod=14)
        axes[1].plot(real, 'r-')
    elif momentum == '随机相对强弱指标':
        fastk, fastd = ta.STOCHRSI(close, timeperiod=14, fastk_period=5, fastd_period=3, fastd_matype=0)
        axes[1].plot(fastk, 'r-')
        axes[1].plot(fastd, 'r-')
    elif momentum == '三重光滑EMA的日变化率':
        real = ta.TRIX(close, timeperiod=30)
        axes[1].plot(real, 'r-')

    plt.show()
Пример #22
0
def TA(S, s, c):
    S = S.fillna(0)
    ope = numpy.asfarray(S.Open)
    high = numpy.asfarray(S.High)
    low = numpy.asfarray(S.Low)
    close = numpy.asfarray(S.Close)
    volume = numpy.asfarray(S.Volume)

    ##ROI calculation
    ROI = [(close[i + 1] - close[i]) / close[i] for i in range(len(close) - 1)]
    ROI.append(0)  #add zero value for last day
    d = pandas.DataFrame(ROI, index=S.index, columns=['ROI'])
    d.to_csv("C:\\Users\\...\\Documents\\Data_TA\\{0}\\ROI_{1}.csv".format(
        s, c))

    ##Baselines
    try:
        bah.append((S.Close['2013-04-30'] - S.Close['2002-05-01']) /
                   S.Close['2002-05-01'])
        sah.append((-S.Close['2013-04-30'] + S.Close['2002-05-01']) /
                   S.Close['2002-05-01'])
    except:
        bah.append((S.Close['2013-04-30'] - S.Close['2002-05-02']) /
                   S.Close['2002-05-02'])
        sah.append((-S.Close['2013-04-30'] + S.Close['2002-05-02']) /
                   S.Close['2002-05-02'])

    rp.append(
        numpy.dot(numpy.random.uniform(-1, 1, len(S)), numpy.asfarray(ROI)))

    ##talib application
    #overlap
    BBANDS = ta.BBANDS(close)
    DEMA = ta.DEMA(close)
    EMA = ta.EMA(close)
    HT_TRENDLINE = ta.HT_TRENDLINE(close)
    KAMA = ta.KAMA(close)
    MA = ta.MA(close)
    MAMA = ta.MAMA(close)
    MIDPOINT = ta.MIDPOINT(close)
    MIDPRICE = ta.MIDPRICE(high, low)
    SAR = ta.SAR(high, low)
    SAREXT = ta.SAREXT(high, low)
    SMA = ta.SMA(close)
    T3 = ta.T3(close)
    TEMA = ta.TEMA(close)
    TRIMA = ta.TRIMA(close)
    WMA = ta.WMA(close)
    #momentum
    ADX = ta.ADX(high, low, close)
    ADXR = ta.ADXR(high, low, close)
    APO = ta.APO(close)
    AROON = ta.AROON(high, low)
    AROONOSC = ta.AROONOSC(high, low)
    BOP = ta.BOP(ope, high, low, close)
    CCI = ta.CCI(high, low, close)
    CMO = ta.CMO(close)
    DX = ta.DX(high, low, close)
    MACD = ta.MACD(close)
    MACDEXT = ta.MACDEXT(close)
    MFI = ta.MFI(high, low, close, volume)
    MINUS_DI = ta.MINUS_DI(high, low, close)
    MINUS_DM = ta.MINUS_DM(high, low)
    MOM = ta.MOM(close)
    PLUS_DI = ta.PLUS_DI(high, low, close)
    PLUS_DM = ta.PLUS_DM(high, low)
    PPO = ta.PPO(close)
    ROC = ta.ROC(close)
    ROCP = ta.ROCP(close)
    ROCR = ta.ROCR(close)
    RSI = ta.RSI(close)
    STOCH = ta.STOCH(high, low, close)
    STOCHF = ta.STOCHF(high, low, close)
    STOCHRSI = ta.STOCHRSI(close)
    TRIX = ta.TRIX(close)
    ULTOSC = ta.ULTOSC(high, low, close)
    WILLR = ta.WILLR(high, low, close)
    #volume
    AD = ta.AD(high, low, close, volume)
    ADOSC = ta.ADOSC(high, low, close, volume)
    OBV = ta.OBV(close, volume)
    #cycle
    HT_DCPERIOD = ta.HT_DCPERIOD(close)
    HT_DCPHASE = ta.HT_DCPHASE(close)
    HT_PHASOR = ta.HT_PHASOR(close)
    HT_SINE = ta.HT_SINE(close)
    HT_TRENDMODE = ta.HT_TRENDMODE(close)
    #price
    AVGPRICE = ta.AVGPRICE(ope, high, low, close)
    MEDPRICE = ta.MEDPRICE(high, low)
    TYPPRICE = ta.TYPPRICE(high, low, close)
    WCLPRICE = ta.WCLPRICE(high, low, close)
    #volatility
    ATR = ta.ATR(high, low, close)
    NATR = ta.NATR(high, low, close)
    TRANGE = ta.TRANGE(high, low, close)
    #pattern
    CDL2CROWS = ta.CDL2CROWS(ope, high, low, close)
    CDL3BLACKCROWS = ta.CDL3BLACKCROWS(ope, high, low, close)
    CDL3INSIDE = ta.CDL3INSIDE(ope, high, low, close)
    CDL3LINESTRIKE = ta.CDL3LINESTRIKE(ope, high, low, close)
    CDL3OUTSIDE = ta.CDL3OUTSIDE(ope, high, low, close)
    CDL3STARSINSOUTH = ta.CDL3STARSINSOUTH(ope, high, low, close)
    CDL3WHITESOLDIERS = ta.CDL3WHITESOLDIERS(ope, high, low, close)
    CDLABANDONEDBABY = ta.CDLABANDONEDBABY(ope, high, low, close)
    CDLADVANCEBLOCK = ta.CDLADVANCEBLOCK(ope, high, low, close)
    CDLBELTHOLD = ta.CDLBELTHOLD(ope, high, low, close)
    CDLBREAKAWAY = ta.CDLBREAKAWAY(ope, high, low, close)
    CDLCLOSINGMARUBOZU = ta.CDLCLOSINGMARUBOZU(ope, high, low, close)
    CDLCONCEALBABYSWALL = ta.CDLCONCEALBABYSWALL(ope, high, low, close)
    CDLCOUNTERATTACK = ta.CDLCOUNTERATTACK(ope, high, low, close)
    CDLDARKCLOUDCOVER = ta.CDLDARKCLOUDCOVER(ope, high, low, close)
    CDLDOJI = ta.CDLDOJI(ope, high, low, close)
    CDLDOJISTAR = ta.CDLDOJISTAR(ope, high, low, close)
    CDLDRAGONFLYDOJI = ta.CDLDRAGONFLYDOJI(ope, high, low, close)
    CDLENGULFING = ta.CDLENGULFING(ope, high, low, close)
    CDLEVENINGDOJISTAR = ta.CDLEVENINGDOJISTAR(ope, high, low, close)
    CDLEVENINGSTAR = ta.CDLEVENINGSTAR(ope, high, low, close)
    CDLGAPSIDESIDEWHITE = ta.CDLGAPSIDESIDEWHITE(ope, high, low, close)
    CDLGRAVESTONEDOJI = ta.CDLGRAVESTONEDOJI(ope, high, low, close)
    CDLHAMMER = ta.CDLHAMMER(ope, high, low, close)
    CDLHANGINGMAN = ta.CDLHANGINGMAN(ope, high, low, close)
    CDLHARAMI = ta.CDLHARAMI(ope, high, low, close)
    CDLHARAMICROSS = ta.CDLHARAMICROSS(ope, high, low, close)
    CDLHIGHWAVE = ta.CDLHIGHWAVE(ope, high, low, close)
    CDLHIKKAKE = ta.CDLHIKKAKE(ope, high, low, close)
    CDLHIKKAKEMOD = ta.CDLHIKKAKEMOD(ope, high, low, close)
    CDLHOMINGPIGEON = ta.CDLHOMINGPIGEON(ope, high, low, close)
    CDLIDENTICAL3CROWS = ta.CDLIDENTICAL3CROWS(ope, high, low, close)
    CDLINNECK = ta.CDLINNECK(ope, high, low, close)
    CDLINVERTEDHAMMER = ta.CDLINVERTEDHAMMER(ope, high, low, close)
    CDLKICKING = ta.CDLKICKING(ope, high, low, close)
    CDLKICKINGBYLENGTH = ta.CDLKICKINGBYLENGTH(ope, high, low, close)
    CDLLADDERBOTTOM = ta.CDLLADDERBOTTOM(ope, high, low, close)
    CDLLONGLEGGEDDOJI = ta.CDLLONGLEGGEDDOJI(ope, high, low, close)
    CDLLONGLINE = ta.CDLLONGLINE(ope, high, low, close)
    CDLMARUBOZU = ta.CDLMARUBOZU(ope, high, low, close)
    CDLMATCHINGLOW = ta.CDLMATCHINGLOW(ope, high, low, close)
    CDLMATHOLD = ta.CDLMATHOLD(ope, high, low, close)
    CDLMORNINGDOJISTAR = ta.CDLMORNINGDOJISTAR(ope, high, low, close)
    CDLMORNINGSTAR = ta.CDLMORNINGSTAR(ope, high, low, close)
    CDLONNECK = ta.CDLONNECK(ope, high, low, close)
    CDLPIERCING = ta.CDLPIERCING(ope, high, low, close)
    CDLRICKSHAWMAN = ta.CDLRICKSHAWMAN(ope, high, low, close)
    CDLRISEFALL3METHODS = ta.CDLRISEFALL3METHODS(ope, high, low, close)
    CDLSEPARATINGLINES = ta.CDLSEPARATINGLINES(ope, high, low, close)
    CDLSHOOTINGSTAR = ta.CDLSHOOTINGSTAR(ope, high, low, close)
    CDLSHORTLINE = ta.CDLSHORTLINE(ope, high, low, close)
    CDLSPINNINGTOP = ta.CDLSPINNINGTOP(ope, high, low, close)
    CDLSTALLEDPATTERN = ta.CDLSTALLEDPATTERN(ope, high, low, close)
    CDLSTICKSANDWICH = ta.CDLSTICKSANDWICH(ope, high, low, close)
    CDLTAKURI = ta.CDLTAKURI(ope, high, low, close)
    CDLTASUKIGAP = ta.CDLTASUKIGAP(ope, high, low, close)
    CDLTHRUSTING = ta.CDLTHRUSTING(ope, high, low, close)
    CDLTRISTAR = ta.CDLTRISTAR(ope, high, low, close)
    CDLUNIQUE3RIVER = ta.CDLUNIQUE3RIVER(ope, high, low, close)
    CDLUPSIDEGAP2CROWS = ta.CDLUPSIDEGAP2CROWS(ope, high, low, close)
    CDLXSIDEGAP3METHODS = ta.CDLXSIDEGAP3METHODS(ope, high, low, close)

    f = numpy.column_stack(
        (ATR, NATR, TRANGE, HT_DCPERIOD, HT_DCPHASE, HT_PHASOR[0],
         HT_PHASOR[1], HT_SINE[0], HT_SINE[1], HT_TRENDMODE, AVGPRICE,
         MEDPRICE, TYPPRICE, WCLPRICE, ADX, ADXR, APO, AROON[0], AROON[1],
         AROONOSC, BOP, CCI, CMO, DX, MACD[0], MACD[1], MACD[2], MACDEXT[0],
         MACDEXT[1], MACDEXT[2], MFI, MINUS_DI, MINUS_DM, MOM, PLUS_DI,
         PLUS_DM, PPO, ROC, ROCP, ROCR, RSI, STOCH[0], STOCH[1], STOCHF[0],
         STOCHF[1], STOCHRSI[0], STOCHRSI[1], TRIX, ULTOSC, WILLR, CDL2CROWS,
         CDL3BLACKCROWS, CDL3INSIDE, CDL3LINESTRIKE, CDL3OUTSIDE,
         CDL3STARSINSOUTH, CDL3WHITESOLDIERS, CDLABANDONEDBABY,
         CDLADVANCEBLOCK, CDLBELTHOLD, CDLBREAKAWAY, CDLCLOSINGMARUBOZU,
         CDLCONCEALBABYSWALL, CDLCOUNTERATTACK, CDLDARKCLOUDCOVER, CDLDOJI,
         CDLDOJISTAR, CDLDRAGONFLYDOJI, CDLENGULFING, CDLEVENINGDOJISTAR,
         CDLEVENINGSTAR, CDLGAPSIDESIDEWHITE, CDLGRAVESTONEDOJI, CDLHAMMER,
         CDLHANGINGMAN, CDLHARAMI, CDLHARAMICROSS, CDLHIGHWAVE, CDLHIKKAKE,
         CDLHIKKAKEMOD, CDLHOMINGPIGEON, CDLIDENTICAL3CROWS, CDLINNECK,
         CDLINVERTEDHAMMER, CDLKICKING, CDLKICKINGBYLENGTH, CDLLADDERBOTTOM,
         CDLLONGLEGGEDDOJI, CDLLONGLINE, CDLMARUBOZU, CDLMATCHINGLOW,
         CDLMATHOLD, CDLMORNINGDOJISTAR, CDLMORNINGSTAR, CDLONNECK,
         CDLPIERCING, CDLRICKSHAWMAN, CDLRISEFALL3METHODS, CDLSEPARATINGLINES,
         CDLSHOOTINGSTAR, CDLSHORTLINE, CDLSPINNINGTOP, CDLSTALLEDPATTERN,
         CDLSTICKSANDWICH, CDLTAKURI, CDLTASUKIGAP, CDLTHRUSTING, CDLTRISTAR,
         CDLUNIQUE3RIVER, CDLUPSIDEGAP2CROWS, CDLXSIDEGAP3METHODS, BBANDS[0],
         BBANDS[1], BBANDS[2], DEMA, EMA, HT_TRENDLINE, KAMA, MA, MAMA[0],
         MAMA[1], MIDPOINT, MIDPRICE, SAR, SAREXT, SMA, T3, TEMA, TRIMA, WMA,
         AD, ADOSC, OBV))

    h = numpy.apply_along_axis(nor, 0, f)  # normalize columnwise

    df = pandas.DataFrame(
        h,
        index=S.index,
        columns=[
            'ATR', 'NATR', 'TRANGE', 'HT_DCPERIOD', 'HT_DCPHASE',
            'HT_PHASOR[0]', 'HT_PHASOR[1]', 'HT_SINE[0]', 'HT_SINE[1]',
            'HT_TRENDMODE', 'AVGPRICE', 'MEDPRICE', 'TYPPRICE', 'WCLPRICE',
            'ADX', 'ADXR', 'APO', 'AROON[0]', 'AROON[1]', 'AROONOSC', 'BOP',
            'CCI', 'CMO', 'DX', 'MACD[0]', 'MACD[1]', 'MACD[2]', 'MACDEXT[0]',
            'MACDEXT[1]', 'MACDEXT[2]', 'MFI', 'MINUS_DI', 'MINUS_DM', 'MOM',
            'PLUS_DI', 'PLUS_DM', 'PPO', 'ROC', 'ROCP', 'ROCR', 'RSI',
            'STOCH[0]', 'STOCH[1]', 'STOCHF[0]', 'STOCHF[1]', 'STOCHRSI[0]',
            'STOCHRSI[1]', 'TRIX', 'ULTOSC', 'WILLR', 'CDL2CROWS',
            'CDL3BLACKCROWS', 'CDL3INSIDE', 'CDL3LINESTRIKE', 'CDL3OUTSIDE',
            'CDL3STARSINSOUTH', 'CDL3WHITESOLDIERS', 'CDLABANDONEDBABY',
            'CDLADVANCEBLOCK', 'CDLBELTHOLD', 'CDLBREAKAWAY',
            'CDLCLOSINGMARUBOZU', 'CDLCONCEALBABYSWALL', 'CDLCOUNTERATTACK',
            'CDLDARKCLOUDCOVER', 'CDLDOJI', 'CDLDOJISTAR', 'CDLDRAGONFLYDOJI',
            'CDLENGULFING', 'CDLEVENINGDOJISTAR', 'CDLEVENINGSTAR',
            'CDLGAPSIDESIDEWHITE', 'CDLGRAVESTONEDOJI', 'CDLHAMMER',
            'CDLHANGINGMAN', 'CDLHARAMI', 'CDLHARAMICROSS', 'CDLHIGHWAVE',
            'CDLHIKKAKE', 'CDLHIKKAKEMOD', 'CDLHOMINGPIGEON',
            'CDLIDENTICAL3CROWS', 'CDLINNECK', 'CDLINVERTEDHAMMER',
            'CDLKICKING', 'CDLKICKINGBYLENGTH', 'CDLLADDERBOTTOM',
            'CDLLONGLEGGEDDOJI', 'CDLLONGLINE', 'CDLMARUBOZU',
            'CDLMATCHINGLOW', 'CDLMATHOLD', 'CDLMORNINGDOJISTAR',
            'CDLMORNINGSTAR', 'CDLONNECK', 'CDLPIERCING', 'CDLRICKSHAWMAN',
            'CDLRISEFALL3METHODS', 'CDLSEPARATINGLINES', 'CDLSHOOTINGSTAR',
            'CDLSHORTLINE', 'CDLSPINNINGTOP', 'CDLSTALLEDPATTERN',
            'CDLSTICKSANDWICH', 'CDLTAKURI', 'CDLTASUKIGAP', 'CDLTHRUSTING',
            'CDLTRISTAR', 'CDLUNIQUE3RIVER', 'CDLUPSIDEGAP2CROWS',
            'CDLXSIDEGAP3METHODS', 'BBANDS[0]', 'BBANDS[1]', 'BBANDS[2]',
            'DEMA', 'EMA', 'HT_TRENDLINE', 'KAMA', 'MA', 'MAMA[0]', 'MAMA[1]',
            'MIDPOINT', 'MIDPRICE', 'SAR', 'SAREXT', 'SMA', 'T3', 'TEMA',
            'TRIMA', 'WMA', 'AD', 'ADOSC', 'OBV'
        ])
    df.to_csv("C:\\Users\\...\\Documents\\Data_TA\\{0}\\{1}.csv".format(s, c))
Пример #23
0
xy = np.loadtxt('shinhan_test.csv', delimiter=',')

t_open = np.transpose(xy[:, [0]])
t_high = np.transpose(xy[:, [1]])  #x,y 행렬 전치 해줌 ( 그래야 talib가 먹힘 )
t_low = np.transpose(xy[:, [2]])
t_vol = np.transpose(xy[:, [3]])
t_y = np.transpose(xy)

open = np.array(t_open[0], dtype='float')
high = np.array(t_high[0], dtype='float')
low = np.array(t_low[0], dtype='float')
volume = np.array(t_vol[0], dtype='float')
close = np.array(t_y[0], dtype='float')

b_upper, b_middle, b_lower = ta.BBANDS(close)  #bollinger ban
ma = ta.MA(close, timeperiod=predict_len)  #moving average
dmi = ta.DX(high, low, close, timeperiod=predict_len)  #direct movement index
macd, macdsignal, macdhist = ta.MACD(
    close, fastperiod=predict_len, slowperiod=predict_len * 2,
    signalperiod=4)  #moving average convergence/divergence
slowk, slowd = ta.STOCH(high,
                        low,
                        close,
                        fastk_period=predict_len,
                        slowk_period=3,
                        slowk_matype=0,
                        slowd_period=3,
                        slowd_matype=0)  #Stochastic
mom = ta.MOM(close, timeperiod=predict_len)
rsi = ta.RSI(close, timeperiod=predict_len * 2)  #Relative Strength Index
Пример #24
0
def get_all_factors(open, high, low, close, volume):
    '''get all factors when n minutes as the period'''
    SMA = talib.MA(close, 30, matype=0)
    EMA = talib.MA(close, 30, matype=1)
    WMA = talib.MA(close, 30, matype=2)
    DEMA = talib.MA(close, 30, matype=3)
    TEMA = talib.MA(close, 30, matype=4)

    MA5 = talib.MA(close, 5, matype=0)
    MA10 = talib.MA(close, 10, matype=0)
    MA20 = talib.MA(close, 20, matype=0)
    MA60 = talib.MA(close, 60, matype=0)
    MA120 = talib.MA(close, 120, matype=0)
    # ======================================== MACD =============================================
    macd, macdsignal, macdhist = talib.MACD(close,
                                            fastperiod=12,
                                            slowperiod=26,
                                            signalperiod=9)
    # ========================================= RSI =============================================
    rsi = talib.RSI(close, timeperiod=6)
    # ========================================= KDJ =============================================
    slowk, slowd = talib.STOCH(high,
                               low,
                               close,
                               fastk_period=9,
                               slowk_period=3,
                               slowd_period=3,
                               slowk_matype=0,
                               slowd_matype=0)
    # ========================================== BOLLING ========================================
    upper, middle, lower = talib.BBANDS(
        close,
        timeperiod=26,
        # number of non-biased standard deviations from the mean
        nbdevup=2,
        nbdevdn=2,
        # Moving average dataType: simple moving average here
        matype=0)
    # =========================================== SAR ============================================
    sar = talib.SAR(high, low, acceleration=0.05, maximum=0.2)

    mat = open  #0
    mat = np.column_stack((mat, high))  #1
    mat = np.column_stack((mat, low))  #2
    mat = np.column_stack((mat, close))  #3
    mat = np.column_stack((mat, volume))  #4

    mat = np.column_stack((mat, upper))  #5
    mat = np.column_stack((mat, middle))  #6
    mat = np.column_stack((mat, lower))

    mat = np.column_stack((mat, slowk))
    mat = np.column_stack((mat, slowd))

    mat = np.column_stack((mat, macd))
    mat = np.column_stack((mat, macdhist))
    mat = np.column_stack((mat, macdsignal))

    mat = np.column_stack((mat, SMA))
    mat = np.column_stack((mat, EMA))
    mat = np.column_stack((mat, WMA))
    mat = np.column_stack((mat, DEMA))
    mat = np.column_stack((mat, TEMA))

    mat = np.column_stack((mat, rsi))

    mat = np.column_stack((mat, sar))

    mat = np.column_stack((mat, MA5))
    mat = np.column_stack((mat, MA10))
    mat = np.column_stack((mat, MA20))
    mat = np.column_stack((mat, MA60))
    mat = np.column_stack((mat, MA120))
    # np.savetxt('1316.csv', mat, delimiter = ',')
    # 25
    return mat
Пример #25
0
def get_bbands(df, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0):
    return talib.BBANDS(df.close,
                        timeperiod=timeperiod,
                        nbdevup=nbdevup,
                        nbdevdn=nbdevdn,
                        matype=matype)
Пример #26
0
def bband_func(x, index):
    xc = x.close
    return ta.BBANDS(xc)[index]
Пример #27
0
def technical_indicators_panda_dataframe(df_price):

    open = df_price['Open']
    high = df_price['High']
    low = df_price['Low']
    close = df_price['Close']
    volume = df_price['Volume']

    ## Commoditty Channel Index
    cci = tb.CCI(high, low, close, timeperiod=20)

    ## Rate of change
    roc = tb.ROC(close, timeperiod=21)

    ## Momentum Indicators Functions

    #Aroon
    aroondown, aroonup = tb.AROON(high, low, timeperiod=14)

    #Average Directional Movement Index
    adx = tb.ADX(high, low, close, timeperiod=14)
    di_plus = tb.PLUS_DI(high, low, close, timeperiod=14)
    di_minus = tb.MINUS_DI(high, low, close, timeperiod=14)

    #Money Flow Index
    mfi = tb.MFI(high, low, close, volume, timeperiod=14)

    #Relative Strength Index
    rsi = tb.RSI(close, timeperiod=14)

    #Stochastic
    slowk, slowd = tb.STOCH(high,
                            low,
                            close,
                            fastk_period=5,
                            slowk_period=3,
                            slowk_matype=0,
                            slowd_period=3,
                            slowd_matype=0)

    #STOCHF - Stochastic Fast
    fastk, fastd = tb.STOCHF(high,
                             low,
                             close,
                             fastk_period=5,
                             fastd_period=3,
                             fastd_matype=0)

    #Moving Average Convergence/Divergence
    macd, macdema, macdhist = tb.MACD(close,
                                      fastperiod=12,
                                      slowperiod=26,
                                      signalperiod=9)

    ## Overlap Studies Functions

    #Bollinger Bands
    upperband, middleband, lowerband = tb.BBANDS(close,
                                                 timeperiod=5,
                                                 nbdevup=2,
                                                 nbdevdn=2,
                                                 matype=0)

    #Weighted Moving Average
    wma5 = tb.WMA(close, timeperiod=5)
    wma30 = tb.WMA(close, timeperiod=30)

    #Exponential Moving Average
    ema5 = tb.EMA(close, timeperiod=5)
    ema21 = tb.EMA(close, timeperiod=21)

    #Double Exponential Moving Average
    dema5 = tb.DEMA(close, timeperiod=5)
    dema21 = tb.DEMA(close, timeperiod=21)

    #Triple Exponential Moving Average
    tema = tb.TEMA(close, timeperiod=30)

    #Triangular Moving Average
    trima5 = tb.DEMA(close, timeperiod=5)
    trima30 = tb.TRIMA(close, timeperiod=30)

    ## Volume indicators Functions

    #AD - Chaikin A/D Line
    chaikin = tb.AD(high, low, close, volume)

    ##=> MERGE

    kwargs = {"cci":cci, "roc": roc, "aroondown": aroondown, "aroonup": aroonup, "adx": adx, "di_plus":di_plus, "di_minus":di_minus, "mfi": mfi, "rsi": rsi, "slowk": slowk, "slowd": slowd, "fastk": fastk, "fastd": fastd, "macd": macd, "macdema": macdema, "macdhist": macdhist,\
      "upperband": upperband , "middleband": middleband , "lowerband": lowerband, "wma5" : wma5, "wma30" : wma30,  "ema5" : ema5, "ema21" : ema21, "dema21": dema21, "dema5": dema5, "tema": tema, "trima5": trima5,"trima30": trima30,\
      "chaikin": chaikin}

    return df_price.assign(**kwargs)
Пример #28
0
def predict(inputHisDf,
            lookAheadDays=3,
            windowSize=20,
            minCorr=0.9,
            onlyPositiveCorr=True):
    trendWindow = 5
    stdGap = 1.25
    hisDf = inputHisDf.set_index('index', drop=False).tail(windowSize + 1)
    pU, pM, pL = ta.BBANDS(
        hisDf['OrigClose'].head(windowSize).astype(float).values,
        timeperiod=trendWindow,
        nbdevup=stdGap,
        nbdevdn=stdGap)
    volU, volM, volL = ta.BBANDS(
        hisDf['OrigVolume'].head(windowSize).astype(float).values,
        timeperiod=trendWindow,
        nbdevup=stdGap,
        nbdevdn=stdGap)
    preP = hisDf['OrigClose'].iat[-2]
    curP = hisDf['OrigClose'].iat[-1]

    preV = hisDf['OrigVolume'].iat[-2]
    curV = hisDf['OrigVolume'].iat[-1]

    pUSlope = _array_slope(pU[-trendWindow:])
    pMSlope = _array_slope(pM[-trendWindow:])
    volUSlope = _array_slope(volU[-trendWindow:])
    volMSlope = _array_slope(volM[-trendWindow:])
    if volMSlope > 0:  #goes upper with larger std
        if curP > pL[-1] and preP < pL[-1]:
            return 1
    if curP < pU[-1] and preP > pU[-1]:
        return -1
    '''
    if pUSlope > 0 and pMSlope > 0 and pUSlope-pMSlope > 0: #goes upper with larger std
        if curP > pU[-1] and preP < pU[-1]:
            return 1
        elif curP < pU[-1] and preP > pU[-1]:
            return -1
        elif curP < pL[-1] and preP > pL[-1]:
            return -1
        elif curP > pL[-1] and preP < pL[-1]:
            return 1

    elif pUSlope < 0 and pMSlope < 0 and pUSlope-pMSlope < 0: #goes down with small std
        if curP > pL[-1] and preP < pL[-1]:
            return 1
        elif curP < pL[-1] and preP > pL[-1]:
            return -1
    if volUSlope > 0 and volMSlope > 0 and volUSlope-volMSlope > 0:
        if curP > pL[-1] and preP < pL[-1]:
            return 1
        if curP > pM[-1] and pMSlope > 0:
            return 1
        if curP < pU[-1] and preP > pU[-1]:
            return -1
        if curP < pM[-1] and pMSlope < 0:
            return -1
    elif volUSlope < 0 and volMSlope < 0 and volUSlope-volMSlope < 0:
        if curP < pU[-1] and preP > pU[-1]:
            return -1
    '''
    return 0
Пример #29
0
 def _rolling_algo(self, data, n, a1, a2, i):
     """ 逐步运行函数。"""
     upper, middle, lower = talib.BBANDS(data, n, a1, a2)
     return (upper[i], middle[i], lower[i])
    close_prices = np.array([x[4] for x in rates_sorted])
    # low_prices = np.array([x[1] for x in rates_sorted])
    # high_prices = np.array([x[2] for x in rates_sorted])
    close_timestamp = rates_sorted[-1][0]

    if args.yolo:
        print(close_prices)

    # Compute Bollinger Bands
    # nbdevup: number of non-biased standard deviations from the mean
    # nbdevdn: 
    # matype: moving average type: simple moving average here (0)
    upper, middle, lower = talib.BBANDS(
        close_prices,
        timeperiod=args.periods,
        nbdevup=2,
        nbdevdn=2,
        matype=2)
 
    action = 'NOTHING'

    # If the last close price is under the lower band
    if close_prices[-1] <= lower[-1]:
        action = 'BUY'

    # If close_prices is above the recent upper band
    elif close_prices[-1] >= upper[-1]:
        action = 'SELL'

    print('{} >>> {}'.format(close_timestamp, action))
    result.append([close_timestamp, action])