Exemple #1
0
    def total(self, dfs, dfs2=None, period=60):
        # 计算参数
        df0 = dfs[self.mCodes[0]]
        df0["rel_price"] = close = df0["close"]
        df0["datetime"] = df0.index

        s0 = self.shift[0]
        p_l = df0["p_l"] = (df0["close"] + s0)
        p_h = df0["p_h"] = (df0["close"] - s0)

        # MA指标
        df0["ma10"] = ma10 = ta.MA(close, timeperiod=10)
        df0["ma20"] = ma20 = ta.MA(close, timeperiod=20)

        df0["ma55"] = ma55 = ta.MA(close, timeperiod=55)

        df0['atrb'] = ta.ATR(df0['high'], df0['low'], close, timeperiod=21)

        # 调整异常high、low指标
        df0['high1'] = df0['high']
        df0['low1'] = df0['low']
        df0['high'] = df0.apply(lambda row: self.k_fix(row, 1), axis=1)
        df0['low'] = df0.apply(lambda row: self.k_fix(row, -1), axis=1)

        mac = ma10 - ma20

        # isPoint
        df0['mad'] = mac * mac.shift(1)
        df0['mam'] = mam = df0.apply(lambda row: self.isMam(row), axis=1)
        minidx, maxidx = ta.MINMAXINDEX(mam, timeperiod=80)
        df0['interval'] = abs(minidx - maxidx)

        # 唐奇安线
        df0['tu_s'] = ta.MAX(df0['high'].shift(1),
                             timeperiod=self.tangStartPeriod0)
        df0['td_s'] = ta.MIN(df0['low'].shift(1),
                             timeperiod=self.tangStartPeriod0)

        df0['tu_s1'] = ta.MAX(df0['high'].shift(1),
                              timeperiod=self.tangStartPeriod1)
        df0['td_s1'] = ta.MIN(df0['low'].shift(1),
                              timeperiod=self.tangStartPeriod1)

        df0['tu_d'] = ta.MIN(df0['high'].shift(1),
                             timeperiod=self.tangDropPeriod)
        df0['td_d'] = ta.MIN(df0['low'].shift(1),
                             timeperiod=self.tangDropPeriod)

        df0['tu_e'] = ta.MAX(df0['high'].shift(1),
                             timeperiod=self.tangEndPeriod)
        df0['td_e'] = ta.MIN(df0['low'].shift(1),
                             timeperiod=self.tangEndPeriod)

        df0['isout'] = isout = df0.apply(lambda row: self.isout(row), axis=1)

        df0['isout3'] = ta.SUM(isout, timeperiod=3)
        df0['isout5'] = ta.SUM(isout, timeperiod=5)

        df1 = None
        # 循环 scale
        docs = []
        for scale in self.scaleList:
            for conds in self.iterCond():
                uid = self.uidKey % ('_'.join(self.codes), str(period),
                                     str(scale), self.klineType[:-1], conds)

                isCvs = False
                for key in self.csvList:
                    if uid.find(key) > -1:
                        isCvs = True
                        break

                if isCvs:
                    cs = []
                    bans = 'ma,p_l,p_h,top,lower,std,delta,volume,sard,rel_price,width,volm,'.split(
                        ',')
                    for c in df0.columns:
                        if c not in bans:
                            cs.append(c)

                    file = self.Rice.basePath + '%s_pre.csv' % (uid)
                    print(uid, '---------------------------- to_cvs', file)
                    df0.to_csv(file, index=0, columns=cs)

                tot = self.detect(df0, df1, period=period, uid=uid)

                if tot is not None and tot['amount'] != 0:
                    tot.update({
                        "scale": scale,
                        "code": self.codes[0],
                        "period": period,
                        "uid": uid,
                        "shift": (p_l - p_h).mean(),
                        "createdate": public.getDatetime()
                    })
                    docs.append(tot)
        return docs
Exemple #2
0
def on_data(context):
    context.time_now += 1
    data = get_reg_kdata(reg_idx=context.reg_kdata[0],
                         length=context.ma + 4,
                         fill_up=True,
                         df=True)
    if data['close'].isna().any():
        return
    long_positions = context.account().positions['volume_long']
    datalist = [
        data[data['target_idx'] == x] for x in pd.unique(data.target_idx)
    ]
    for target in datalist:
        target_idx = target.target_idx.iloc[0]
        high = target.high.values.astype(float)
        low = target.low.values.astype(float)
        close = target.close.values.astype(float)
        atr = talib.ATR(high, low, close, context.atr)
        upperband, _, lowerband = talib.BBANDS(close,
                                               timeperiod=context.boll,
                                               nbdevup=2,
                                               nbdevdn=2,
                                               matype=0)
        ma55 = talib.MA(close, 55)
        ma233 = talib.MA(close, 233)
        if long_positions[target_idx] > 0:
            p12 = (close[-1] <= context.buyprice[target_idx] - 2 * atr[-1]) or \
                  (close[-1] <= context.stopprice[target_idx])
            if p12:
                order_target_volume(0, target_idx, 0, 1, 2)
                context.buyprice[target_idx] = 0
                context.times[target_idx] = context.time_now
                context.stopprice[target_idx] = 0
                context.counts[target_idx] = 0
                context.selltimes[target_idx] = context.time_now
            p16 = close[-1] >= 1.1 * context.buyprice[target_idx] and context.buyprice[target_idx] != 0 and \
                  context.times[target_idx] != context.time_now
            if p16:
                context.stopprice[target_idx] = close[-1] * 0.9618
                context.buyprice[target_idx] = close[-1]
                context.counts[target_idx] += 1
                if context.counts[target_idx] >= 2:
                    context.stopprice[target_idx] = close[-1]
                p17 = context.times[
                    target_idx] != context.time_now and context.counts[
                        target_idx] <= 4
                if p17:
                    order_value(0, target_idx,
                                context.initial / context.Tlen * 10, 1, 1, 2)
                context.times[target_idx] = context.time_now
        p34 = ma55[-3] > ma233[-3] and ma55[-2] > ma233[-2] and ma55[
            -1] > ma233[-1]
        if p34:
            context.candidates_times[target_idx] = context.time_now
            p35 = (context.time_now -
                   context.candidates_times[target_idx]) >= 150
            p36 = (context.time_now -
                   context.candidates_times[target_idx]) < 150
            if p36:
                context.candidates.append(target_idx)
            if p35:
                context.candidates_times[target_idx] = 0
        a = long_positions[target_idx] == 0
        b = target_idx in context.candidates
        c = context.times[target_idx] != context.time_now
        d = context.counts[target_idx] == 0
        e = context.time_now - context.selltimes[target_idx] > 23
        long_open = a and b and c and d and e
        if long_open and (close[-1] > upperband[-1]) and (
                upperband[-1] -
                lowerband[-1]) > 1.2 * (upperband - lowerband)[-21:].mean():
            order_value(0, target_idx, context.initial / context.Tlen * 10, 1,
                        1, 2)
            context.buyprice[target_idx] = close[-1]
            context.stopprice[target_idx] = close[-1] * 0.9382
Exemple #3
0
    def on_bar(self, bar):
        if self.cls_mode == gm.MD_MODE_PLAYBACK:
            if bar.strtime[0:10] != self.cur_date[0:10]:
                self.cur_date = bar.strtime[0:10] + ' 08:00:00'
                # 新的交易日
                self.init_data_newday()

        symbol = bar.exchange + '.' + bar.sec_id

        if symbol in self.dict_prev_close and self.dict_prev_close[
                symbol] is None:
            self.dict_prev_close[symbol] = bar.open

        self.movement_stop_profit_loss(bar)
        self.fixation_stop_profit_loss(bar)

        pos = self.get_position(bar.exchange, bar.sec_id, OrderSide_Bid)

        # 补充当天价格
        if symbol in self.dict_price:
            if self.dict_price[symbol][0][-1] < bar.high:
                self.dict_price[symbol][0][-1] = bar.high

            if self.dict_price[symbol][1][-1] > bar.low:
                self.dict_price[symbol][1][-1] = bar.low

            self.dict_price[symbol][2][-1] = bar.close

        if self.dict_open_close_signal[symbol] is False:
            # 当天未有对该代码开、平仓
            if symbol in self.dict_price:

                atr_index = talib.ATR(high=self.dict_price[symbol][0],
                                      low=self.dict_price[symbol][1],
                                      close=self.dict_price[symbol][2],
                                      timeperiod=self.atr_period)

                if pos is None and symbol not in self.dict_open_cum_days \
                        and (bar.close > self.dict_prev_close[symbol] + atr_index[-1] * self.buy_multi_atr):
                    # 有开仓机会则设置已开仓的交易天数
                    self.dict_open_cum_days[symbol] = 0

                    cash = self.get_cash()
                    cur_open_vol = self.open_vol
                    if cash.available / bar.close > self.open_vol:
                        cur_open_vol = self.open_vol
                    else:
                        cur_open_vol = int(
                            cash.available / bar.close / 100) * 100

                    if cur_open_vol == 0:
                        print(
                            'no available cash to buy, available cash: %.2f' %
                            cash.available)
                    else:
                        self.open_long(bar.exchange, bar.sec_id, bar.close,
                                       cur_open_vol)
                        self.dict_open_close_signal[symbol] = True
                        logging.info(
                            'open long, symbol:%s, time:%s, price:%.2f' %
                            (symbol, bar.strtime, bar.close))
                elif pos is not None and (bar.close <
                                          self.dict_prev_close[symbol] -
                                          atr_index[-1] * self.buy_multi_atr):
                    vol = pos.volume - pos.volume_today
                    if vol > 0:
                        self.close_long(bar.exchange, bar.sec_id, bar.close,
                                        vol)
                        self.dict_open_close_signal[symbol] = True
                        logging.info(
                            'close long, symbol:%s, time:%s, price:%.2f' %
                            (symbol, bar.strtime, bar.close))

        if symbol in self.dict_prev_close:
            self.dict_prev_close[symbol] = bar.close
Exemple #4
0
 def position(self):
     #仓位管理
      vol = ta.ATR(self.high, self.low, self.close, timeperiod = self.N1)
 def atrStopLoss(self, am, paraDict):
     bandPeriod = paraDict['bandPeriod']
     atrTime = paraDict['atrTime']
     atr = ta.ATR(am.high, am.low, am.close, bandPeriod)
     stopLossAtr = atrTime * atr
     return stopLossAtr
Exemple #6
0
def part_test(
    con_id,
    begin_time,
    end_time,
    # p_window, p_limit,
    # v_window, v_limit,
    # voli_window, voli_limit,
    CCI_window,
    CCI_limit,
    # hold_time
):
    print(con_id, begin_time, end_time)
    try:
        # print(con_id, begin_time, end_time)
        # data_df = fut_data.load_intra_data(con_id, ['High', 'Low', 'Close', 'Volume', 'OpenInterest'])
        data_df = fut_data.load_intra_reshape_data(
            con_id, ['High', 'Low', 'Close', 'Volume', 'OpenInterest'])
        if con_id == 'J1501.DCE':
            print(1)
        # begin_time = pd.to_datetime('20190101')
        # # end_time = begin_time + timedelta(1)
        # end_time = pd.to_datetime('20190401')

        # p_window = 1
        # p_limit = 1
        # v_window = 20
        # v_limit = 2

        part_data_df = data_df.truncate(before=begin_time, after=end_time)
        part_data_df['OpenInterest_core'] = FutIndex.boll_fun(
            data_df['OpenInterest'], 100)
        part_data_df['weekday'] = pd.to_datetime(
            part_data_df['Date']).dt.weekday
        part_data_df['weekday_pos'] = (
            (part_data_df['weekday'] != 3)
            # & (part_data_df['weekday'] != 3)
            # & (part_data_df['weekday'] != 3)
            # (part_data_df['weekday'] != 4)
        ).astype(int)
        part_data_df['month'] = part_data_df['Date'].str.slice(5, 7)
        # part_data_df['month_pos'] = ((part_data_df['month'] != '10') & (part_data_df['month'] != '12')).astype(int)
        part_data_df['month_pos'] = (part_data_df['month'] != '1').astype(int)

        # part_data_df['time_pos_cut'] = part_data_df.apply(lambda x: -1 if (((x['Time'] > '14:51')
        #                                                                     & (x['Time'] <= '15:00')
        #                                                                     # | (x['Time'] > '21:00')
        #                                                                     # & (x['Time'] <= '22:00')
        #                                                                     # | (x['Time'] > '21:00')
        #                                                                     # & (x['Time'] <= '22:00')
        #                                                                     )) else 1, axis=1)
        part_data_df[
            'Vol_OI'] = part_data_df['Volume'] / part_data_df['OpenInterest']

        part_data_df['Volume_boll'] = FutIndex.boll_fun(
            part_data_df[['Volume']], CCI_window)
        part_data_df['past_roll_Volume'] = bt.AZ_Rolling_mean(
            part_data_df[['Volume']], CCI_window)
        v_window = 60
        part_data_df['Volume_zscore'] = bt.AZ_Col_zscore(
            part_data_df[['Volume']], CCI_window)
        part_data_df['Volume_signal'] = part_data_df['Volume_zscore'][
            part_data_df['Volume_zscore'] < 1].astype(int)
        # part_data_df['Volume_signal'] = (part_data_df['Volume_zscore'] < 2).astype(int).replace(0, -1)

        p_window = 5
        # part_data_df['past_min_pct_change'] = (part_data_df['Close'] - part_data_df['Close'].shift(p_window)) \
        #                                       / part_data_df['Close'].shift(p_window)

        part_data_df['past_min_pct_change'] = (
            part_data_df['Close'] / part_data_df['Close'].shift(p_window) - 1)
        part_data_df['past_min_pct_signal'] = part_data_df['past_min_pct_change'] \
            .apply(lambda x: 0 if abs(x) < 0.004 else (1 if x > 0.004 else -1))

        test_window = CCI_window
        macd, macdsignal, macdhist = ta.MACD(part_data_df['Close'], 12, 26, 9)
        part_data_df['macd'] = macd
        RSI = ta.RSI(part_data_df['Close'], test_window)
        RSI = RSI - 50
        RSI[RSI > 20] = 20
        RSI[RSI < -20] = -20
        part_data_df['RSI'] = RSI
        part_data_df['RSI_signal'] = Signal.fun_1(part_data_df['RSI'], 1)
        part_data_df['RSI_pos'] = Position.fun_1(part_data_df['RSI_signal'],
                                                 limit=60)

        # aroondown, aroonup = ta.AROON(part_data_df['High'], part_data_df['Low'], test_window)

        obv = ta.OBV(part_data_df['Close'], part_data_df['Volume'])
        part_data_df['obv'] = obv

        atr = ta.ATR(part_data_df['High'], part_data_df['Low'],
                     part_data_df['Close'], test_window)
        part_data_df['atr'] = atr

        adx = ta.ADX(part_data_df['High'], part_data_df['Low'],
                     part_data_df['Close'], test_window)
        part_data_df['adx'] = adx

        trix = ta.TRIX(part_data_df['Close'], 60)
        part_data_df['trix'] = trix

        willr = ta.WILLR(part_data_df['High'], part_data_df['Low'],
                         part_data_df['Close'], test_window)
        part_data_df['willr'] = willr

        part_data_df['CCI_score'] = FutIndex.CCI_fun(part_data_df['High'],
                                                     part_data_df['Low'],
                                                     part_data_df['Close'],
                                                     CCI_window)

        part_data_df['CCI_signal'] = Signal.fun_1(part_data_df['CCI_score'],
                                                  CCI_limit)

        part_data_df['CCI_pos'] = Position.fun_1(part_data_df['CCI_signal'])

        part_data_df['boll_score'], ma_n, md_n = FutIndex.boll_fun(
            part_data_df['Close'], CCI_window, return_line=True)
        part_data_df['boll_signal'] = Signal.fun_1(part_data_df['boll_score'],
                                                   CCI_limit)

        part_data_df['boll_pos'] = Position.fun_1(part_data_df['boll_signal'])
        # part_data_df['boll_pos'] = Position.fun_3(part_data_df['boll_signal'], part_data_df['past_min_pct_signal'])

        # part_data_df['trend_signal'] = bt.AZ_Rolling(part_data_df['Close'], 500).std()
        # part_data_df['trend_pos'] = (part_data_df['trend_signal'] < 40).astype(int)

        part_data_df['trend_indicator'] = bt.AZ_Rolling(part_data_df['Close'], 100). \
            apply(lambda x: (x[-1] / x[0] - 1) / (max(x) / min(x) - 1), raw=False)
        part_data_df['trend_pos'] = (part_data_df['trend_indicator'] <
                                     0.5).astype(int)

        # part_data_df['position'] = part_data_df['boll_pos'] * part_data_df['weekday_pos'] * part_data_df['month_pos']

        part_data_df['position'] = part_data_df['CCI_pos']
        # * part_data_df['trend_pos']  # * part_data_df['trend_pos']

        part_data_df['position_sft'] = (part_data_df['position'].shift(2) *
                                        part_data_df['weekday_pos']).fillna(0)
        # * part_data_df['month_pos'])

        part_data_df['price_return'] = part_data_df['Close'] - part_data_df[
            'Close'].shift(1)

        # part_data_df['price_return_sum'] = bt.AZ_Rolling(part_data_df['price_return'], hold_time).sum() \
        #     .shift(-hold_time + 1)
        part_data_df['pnl'] = part_data_df['position_sft'] * part_data_df[
            'price_return']
        part_data_df['asset'] = part_data_df['pnl'].cumsum()
        # part_data_df['pnl_test'] = part_data_df['signal'] * part_data_df['price_return_sum'].shift(-2)

        part_data_df['turnover'] = (part_data_df['position_sft'] - part_data_df['position_sft'].shift(1)) \
                                   * part_data_df['Close']

        # 剔除开盘收盘5min的signal
        # if '1910' in con_id:
        # plt.figure(figsize=[64, 64])
        # ax1 = plt.subplot(4, 1, 1)
        # ax2 = plt.subplot(4, 1, 2)
        # ax3 = plt.subplot(4, 1, 3)
        # ax1.plot(part_data_df['asset'].values)
        # # ax2.plot(part_data_df['Close'].values, '--', color='#75bbfd')
        # ax2.scatter(np.array(range(len(part_data_df.index)))[(part_data_df['position_sft'] > 0)],
        #             part_data_df['Close'][part_data_df['position_sft'] > 0], s=0.5, color='red')
        #
        # ax2.scatter(np.array(range(len(part_data_df.index)))[(part_data_df['position_sft'] == 0)],
        #             part_data_df['Close'][part_data_df['position_sft'] == 0], s=0.5, color='black')
        #
        # ax2.scatter(np.array(range(len(part_data_df.index)))[(part_data_df['position_sft'] < 0)],
        #             part_data_df['Close'][part_data_df['position_sft'] < 0], s=0.5, color='blue')
        #
        # # ax2.scatter(np.array(range(len(part_data_df.index)))[(part_data_df['past_min_pct_signal'] > 0)],
        # #             part_data_df['Close'][part_data_df['past_min_pct_signal'] > 0], s=20, color='y')
        # # ax2.scatter(np.array(range(len(part_data_df.index)))[(part_data_df['past_min_pct_signal'] < 0)],
        # #             part_data_df['Close'][part_data_df['past_min_pct_signal'] < 0], s=20, color='#f504c9')
        #
        # ax3.bar(range(len(part_data_df.index)), part_data_df['Volume'].values)
        #
        # ax1.grid()
        # ax2.grid()
        # ax3.grid()
        # plt.title(con_id)
        # savfig_send(con_id)

        part_pnl_df = part_data_df.groupby('Date')['pnl'].sum()
        part_turnover = part_data_df.groupby('Date')['turnover'].apply(
            lambda x: sum(abs(x)))
        return part_pnl_df, part_turnover, part_data_df
    except Exception as error:
        print(error)
        return pd.Series(), pd.Series(), pd.Series()
 def atr(self, n, array=False):
     """ATR指标"""
     result = talib.ATR(self.high, self.low, self.close, n)
     if array:
         return result
     return result[-1]
Exemple #8
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
Exemple #9
0
            row['Coin'],
            row['Pair_tuple'],
            limit=250,
            aggregate=1,
            exchange=row['Exchange'])
        closes = df_daily.close.values
        lows = df_daily.low.values
        highs = df_daily.high.values
        opens = df_daily.open.values
        volumetos = df_daily.volumeto.values
        rsi = talib.RSI(closes, timeperiod=14)
        ema12 = talib.EMA(closes, timeperiod=12)
        ema26 = talib.EMA(closes, timeperiod=26)
        ema50 = talib.EMA(closes, timeperiod=50)
        ema200 = talib.EMA(closes, timeperiod=200)
        atr = talib.ATR(highs, lows, closes, timeperiod=14)
        obv = talib.OBV(closes, volumetos)

        list_indicators.append([
            row.Coin + '/' + row.Pair_tuple, closes[-2], rsi[-2], ema50[-2],
            ema200[-2]
        ])
        print(i)
    except:
        list_missing.append([row.Coin + '/' + row.Pair_tuple, row.Exchange])
        pass

df_indicators = pd.DataFrame(
    list_indicators,
    columns=['Pair', '1H Close', '1H RSI', '1H EMA50', '1H EMA200'])
df_indicators.set_index('Pair', inplace=True)
def ATR(high, low, close, timeperiod=14):
    # AVERAGE TRUE RANGE
    real_ = ta.ATR(high, low, close, timeperiod)
    return real_
Exemple #11
0
    df['OBV'] = ta.OBV(df.close.values, df.volume.values.astype(float))
    df['ADOSC'] = ta.ADOSC(df.high.values,
                           df.low.values,
                           df.close.values,
                           df.volume.values.astype(float),
                           fastperiod=3,
                           slowperiod=10)
    df['EMA5'] = ta.EMA(df.close.values, timeperiod=5)
    df['EMA10'] = ta.EMA(df.close.values, timeperiod=10)
    df['EMA20'] = ta.EMA(df.close.values, timeperiod=20)
    df['EMA60'] = ta.EMA(df.close.values, timeperiod=60)
    df['EMA120'] = ta.EMA(df.close.values, timeperiod=120)
    df['CRTDR'] = (df.close.values - df.low.values) / (df.high.values -
                                                       df.low.values)
    df['ATR'] = ta.ATR(df.high.values,
                       df.low.values,
                       df.close.values,
                       timeperiod=12)

    #look at returns
    df['1day_returns'] = np.log(df.close / df.close.shift(1))
    df['5day_returns'] = np.log(df.close / df.close.shift(5))
    df['10day_returns'] = np.log(df.close / df.close.shift(10))
    df['20day_returns'] = np.log(df.close / df.close.shift(20))
    df['60day_returns'] = np.log(df.close / df.close.shift(60))

    #Signals if price goes up or down in future
    df['1day_Signal'] = 0
    df['5day_Signal'] = 0
    df['10day_Signal'] = 0
    df['20day_Signal'] = 0
    df['60day_Signal'] = 0
Exemple #12
0
def get_factors(high, low, close, volume, set_bool):
    BBANDS = False
    DEMA = False
    EMA = False
    HT_TRENDLINE = False
    KAMA = False
    MA = False
    MAMA = False
    MIDPOINT = False
    MIDPRICE = False
    SAR = False
    SAREXT = False
    SMA = False
    T3 = False
    TEMA = False
    TRIMA = False
    WMA = False
    AD = False
    ADOSC = False
    OBV = False
    HT_DCPERIOD = False
    HT_DCPHASE = False
    HT_PHASOR = False
    HT_SINE = False
    HT_TRENDMODE = False
    AVGPRICE = False
    MEDPRICE = False
    TYPPRICE = False
    WCLPRICE = False
    ATR = False
    NATR = False
    TRANGE = False
    ADX = False
    ADXR = False
    APO = False
    AROON = False
    AROONOSC = False
    BOP = False
    CCI = False
    CMO = False
    DX = False
    MACD = False
    ivergence = False
    MACDEXT = False
    MACDFIX = False
    MFI = False
    MINUS_DI = False
    MINUS_DM = False
    MOM = False
    PLUS_DI = False
    PLUS_DM = False
    PPO = False
    ROC = False
    ROCP = False
    ROCR = False
    ROCR100 = False
    RSI = False
    STOCH = False
    STOCHF = False
    STOCHRSI = False
    TRIX = False
    ULTOSC = False
    WILLR = False
    if 'BBANDS' in set_bool:
        BBANDS = True
    if 'DEMA' in set_bool:
        DEMA = True
    if 'EMA' in set_bool:
        EMA = True
    if 'HT_TRENDLINE' in set_bool:
        HT_TRENDLINE = True
    if 'KAMA' in set_bool:
        KAMA = True
    if 'MA' in set_bool:
        MA = True
    if 'MAMA' in set_bool:
        MAMA = True
    if 'MIDPOINT' in set_bool:
        MIDPOINT = True
    if 'MIDPRICE' in set_bool:
        MIDPRICE = True
    if 'SAR' in set_bool:
        SAR = True
    if 'SAREXT' in set_bool:
        SAREXT = True
    if 'SMA' in set_bool:
        SMA = True
    if 'T3' in set_bool:
        T3 = True
    if 'TEMA' in set_bool:
        TEMA = True
    if 'TRIMA' in set_bool:
        TRIMA = True
    if 'WMA' in set_bool:
        WMA = True
    if 'AD' in set_bool:
        AD = True
    if 'ADOSC' in set_bool:
        ADOSC = True
    if 'OBV' in set_bool:
        OBV = True
    if 'HT_DCPERIOD' in set_bool:
        HT_DCPERIOD = True
    if 'HT_DCPHASE' in set_bool:
        HT_DCPHASE = True
    if 'HT_PHASOR' in set_bool:
        HT_PHASOR = True
    if 'HT_SINE' in set_bool:
        HT_SINE = True
    if 'HT_TRENDMODE' in set_bool:
        HT_TRENDMODE = True
    if 'AVGPRICE' in set_bool:
        AVGPRICE = True
    if 'MEDPRICE' in set_bool:
        MEDPRICE = True
    if 'TYPPRICE' in set_bool:
        TYPPRICE = True
    if 'WCLPRICE' in set_bool:
        WCLPRICE = True
    if 'ATR' in set_bool:
        ATR = True
    if 'NATR' in set_bool:
        NATR = True
    if 'TRANGE' in set_bool:
        TRANGE = True
    if 'ADX' in set_bool:
        ADX = True
    if 'ADXR' in set_bool:
        ADXR = True
    if 'APO' in set_bool:
        APO = True
    if 'AROON' in set_bool:
        AROON = True
    if 'AROONOSC' in set_bool:
        AROONOSC = True
    if 'BOP' in set_bool:
        BOP = True
    if 'CCI' in set_bool:
        CCI = True
    if 'CMO' in set_bool:
        CMO = True
    if 'DX' in set_bool:
        DX = True
    if 'MACD' in set_bool:
        MACD = True
    if 'ivergence' in set_bool:
        ivergence = True
    if 'MACDEXT' in set_bool:
        MACDEXT = True
    if 'MACDFIX' in set_bool:
        MACDFIX = True
    if 'MFI' in set_bool:
        MFI = True
    if 'MINUS_DI' in set_bool:
        MINUS_DI = True
    if 'MINUS_DM' in set_bool:
        MINUS_DM = True
    if 'MOM' in set_bool:
        MOM = True
    if 'PLUS_DI' in set_bool:
        PLUS_DI = True
    if 'PLUS_DM' in set_bool:
        PLUS_DM = True
    if 'PPO' in set_bool:
        PPO = True
    if 'ROC' in set_bool:
        ROC = True
    if 'ROCP' in set_bool:
        ROCP = True
    if 'ROCR' in set_bool:
        ROCR = True
    if 'ROCR100' in set_bool:
        ROCR100 = True
    if 'RSI' in set_bool:
        RSI = True
    if 'STOCH' in set_bool:
        STOCH = True
    if 'STOCHF' in set_bool:
        STOCHF = True
    if 'STOCHRSI' in set_bool:
        STOCHRSI = True
    if 'TRIX' in set_bool:
        TRIX = True
    if 'ULTOSC' in set_bool:
        ULTOSC = True
    if 'WILLR' in set_bool:
        WILLR = True
    fators = [
        'BBANDS', 'DEMA', 'EMA', 'HT_TRENDLINE', 'KAMA', 'MA', 'MAMA',
        'MIDPOINT', 'MIDPRICE', 'SAR', 'SAREXT', 'SMA', 'T3', 'TEMA', 'TRIMA',
        'WMA', 'AD', 'ADOSC', 'OBV', 'HT_DCPERIOD', 'HT_DCPHASE', 'HT_PHASOR',
        'HT_SINE', 'HT_TRENDMODE', 'AVGPRICE', 'MEDPRICE', 'TYPPRICE',
        'WCLPRICE', 'ATR', 'NATR', 'TRANGE', 'ADX', 'ADXR', 'APO', 'AROON',
        'AROONOSC', 'BOP', 'CCI', 'CMO', 'DX', 'MACD', 'ivergence', 'MACDEXT',
        'MACDFIX', 'MFI', 'MINUS_DI', 'MINUS_DM', 'MOM', 'PLUS_DI', 'PLUS_DM',
        'PPO', 'ROC', 'ROCP', 'ROCR', 'ROCR100', 'RSI', 'STOCH', 'STOCHF',
        'STOCHRSI', 'TRIX', 'ULTOSC', 'WILLR'
    ]
    data_sets = np.zeros([len(high), 1])
    if BBANDS == True:
        upperband, middleband, lowerband = ta.BBANDS(close,
                                                     timeperiod=5,
                                                     nbdevup=2,
                                                     nbdevdn=2,
                                                     matype=0)
        upperband = array_process(upperband)
        middleband = array_process(middleband)
        lowerband = array_process(lowerband)
        data_sets = np.hstack([data_sets, upperband, middleband, lowerband])
    if DEMA == True:
        dema = ta.DEMA(close, timeperiod=30)
        dema = array_process(dema)
        data_sets = np.hstack([data_sets, dema])
    if EMA == True:
        ema = ta.EMA(close, timeperiod=30)
        ema = array_process(ema)
        data_sets = np.hstack([data_sets, ema])
    if HT_TRENDLINE == True:
        trendline = ta.HT_TRENDLINE(close)
        trendline = array_process(trendline)
        data_sets = np.hstack([data_sets, trendline])
    if KAMA == True:
        kama = ta.KAMA(close, timeperiod=30)
        kama = array_process(kama)
        data_sets = np.hstack([data_sets, kama])
    if MA == True:
        ma = ta.MA(close, timeperiod=30, matype=0)
        ma = array_process(ma)
        data_sets = np.hstack([data_sets, ma])
    if MAMA == True:
        mama, fama = ta.MAMA(close, fastlimit=0, slowlimit=0)
        mama = array_process(mama)
        fama = array_process(fama)
        data_sets = np.hstack([data_sets, mama, fama])
    if MIDPOINT == True:
        midpoint = ta.MIDPOINT(close, timeperiod=14)
        midpoint = array_process(midpoint)
        data_sets = np.hstack([data_sets, midpoint])
    if MIDPRICE == True:
        midprice = ta.MIDPRICE(high, low, timeperiod=14)
        midprice = array_process(midprice)
        data_sets = np.hstack([data_sets, midprice])
    if SAR == True:
        sar = ta.SAR(high, low, acceleration=0, maximum=0)
        sar = array_process(sar)
        data_sets = np.hstack([data_sets, sar])
    if SAREXT == True:
        sarext = ta.SAREXT(high,
                           low,
                           startvalue=0,
                           offsetonreverse=0,
                           accelerationinitlong=0,
                           accelerationlong=0,
                           accelerationmaxlong=0,
                           accelerationinitshort=0,
                           accelerationshort=0,
                           accelerationmaxshort=0)
        sarext = array_process(sarext)
        data_sets = np.hstack([data_sets, sarext])
    if SMA == True:
        sma = ta.SMA(close, timeperiod=30)
        sma = array_process(sma)
        data_sets = np.hstack([data_sets, sma])
    if T3 == True:
        t3 = ta.T3(close, timeperiod=5, vfactor=0)
        t3 = array_process(t3)
        data_sets = np.hstack([data_sets, t3])
    if TEMA == True:
        tema = ta.TEMA(close, timeperiod=30)
        tema = array_process(tema)
        data_sets = np.hstack([data_sets, tema])
    if TRIMA == True:
        trima = ta.TRIMA(close, timeperiod=30)
        trima = array_process(trima)
        data_sets = np.hstack([data_sets, trima])
    if WMA == True:
        wma = ta.WMA(close, timeperiod=30)
        wma = array_process(wma)
        data_sets = np.hstack([data_sets, wma])
    if AD == True:
        ad = ta.AD(high, low, close, volume)
        ad = array_process(ad)
        data_sets = np.hstack([data_sets, ad])
    if ADOSC == True:
        adosc = ta.ADOSC(high, low, close, volume, fastperiod=3, slowperiod=10)
        adosc = array_process(adosc)
        data_sets = np.hstack([data_sets, adosc])
    if OBV == True:
        obv = ta.OBV(close, volume)
        obv = array_process(obv)
        data_sets = np.hstack([data_sets, obv])
    if HT_DCPERIOD == True:
        dcperiod = ta.HT_DCPERIOD(close)
        dcperiod = array_process(dcperiod)
        data_sets = np.hstack([data_sets, dcperiod])
    if HT_DCPHASE == True:
        dcphase = ta.HT_DCPHASE(close)
        dcphase = array_process(dcphase)
        data_sets = np.hstack([data_sets, dcphase])
    if HT_PHASOR == True:
        inphase, quadrature = ta.HT_PHASOR(close)
        inphase = array_process(inphase)
        data_sets = np.hstack([data_sets, inphase])
        quadrature = array_process(quadrature)
        data_sets = np.hstack([data_sets, quadrature])
    if HT_SINE == True:
        sine, leadsine = ta.HT_SINE(close)
        sine = array_process(sine)
        data_sets = np.hstack([data_sets, sine])
        leadsine = array_process(leadsine)
        data_sets = np.hstack([data_sets, leadsine])
    if HT_TRENDMODE == True:
        integer = ta.HT_TRENDMODE(close)
        integer = array_process(integer)
        data_sets = np.hstack([data_sets, integer])
    if AVGPRICE == True:
        avgprice = ta.AVGPRICE(open, high, low, close)
        avgprice = array_process(avgprice)
        data_sets = np.hstack([data_sets, avgprice])
    if MEDPRICE == True:
        medprice = ta.MEDPRICE(high, low)
        medprice = array_process(medprice)
        data_sets = np.hstack([data_sets, medprice])
    if TYPPRICE == True:
        typprice = ta.TYPPRICE(high, low, close)
        typprice = array_process(typprice)
        data_sets = np.hstack([data_sets, typprice])
    if WCLPRICE == True:
        wclprice = ta.WCLPRICE(high, low, close)
        wclprice = array_process(wclprice)
        data_sets = np.hstack([data_sets, wclprice])
    if ATR == True:
        atr = ta.ATR(high, low, close, timeperiod=14)
        atr = array_process(atr)
        data_sets = np.hstack([data_sets, atr])
    if NATR == True:
        natr = ta.NATR(high, low, close, timeperiod=14)
        natr = array_process(natr)
        data_sets = np.hstack([data_sets, natr])
    if TRANGE == True:
        trange = ta.TRANGE(high, low, close)
        natr = array_process(trange)
        data_sets = np.hstack([data_sets, trange])
    if ADX == True:
        adx = ta.ADX(high, low, close, timeperiod=14)
        adx = array_process(adx)
        data_sets = np.hstack([data_sets, adx])
    if ADXR == True:
        adxr = ta.ADXR(high, low, close, timeperiod=14)
        adxr = array_process(adxr)
        data_sets = np.hstack([data_sets, adxr])
    if APO == True:
        apo = ta.APO(close, fastperiod=12, slowperiod=26, matype=0)
        apo = array_process(apo)
        data_sets = np.hstack([data_sets, apo])
    if AROON == True:
        aroondown, aroonup = ta.AROON(high, low, timeperiod=14)
        aroondown = array_process(aroondown)
        data_sets = np.hstack([data_sets, aroondown])
        aroonup = array_process(aroonup)
        data_sets = np.hstack([data_sets, aroonup])
    if AROONOSC == True:
        aroonosc = ta.AROONOSC(high, low, timeperiod=14)
        aroonosc = array_process(aroonosc)
        data_sets = np.hstack([data_sets, aroonosc])
    if BOP == True:
        bop = ta.BOP(open, high, low, close)
        bop = array_process(bop)
        data_sets = np.hstack([data_sets, bop])
    if CCI == True:
        cci = ta.CCI(high, low, close, timeperiod=14)
        cci = array_process(cci)
        data_sets = np.hstack([data_sets, cci])
    if CMO == True:
        cmo = ta.CMO(close, timeperiod=14)
        cmo = array_process(cmo)
        data_sets = np.hstack([data_sets, cmo])
    if DX == True:
        dx = ta.DX(high, low, close, timeperiod=14)
        dx = array_process(dx)
        data_sets = np.hstack([data_sets, dx])
    if MACD == True:
        macd, macdsignal, macdhist = ta.MACD(close,
                                             fastperiod=12,
                                             slowperiod=26,
                                             signalperiod=9)
        macd = array_process(macd)
        data_sets = np.hstack([data_sets, macd])
        macdhist = array_process(macdhist)
        data_sets = np.hstack([data_sets, macdhist])
        macdsignal = array_process(macdsignal)
        data_sets = np.hstack([data_sets, macdsignal])
    if MACDEXT == True:
        macd, macdsignal, macdhist = ta.MACDEXT(close,
                                                fastperiod=12,
                                                fastmatype=0,
                                                slowperiod=26,
                                                slowmatype=0,
                                                signalperiod=9,
                                                signalmatype=0)
        macd = array_process(macd)
        data_sets = np.hstack([data_sets, macd])
        macdhist = array_process(macdhist)
        data_sets = np.hstack([data_sets, macdhist])
        macdsignal = array_process(macdsignal)
        data_sets = np.hstack([data_sets, macdsignal])
    if MACDFIX == True:
        macd, macdsignal, macdhist = ta.MACDFIX(close, signalperiod=9)
        macd = array_process(macd)
        data_sets = np.hstack([data_sets, macd])
        macdhist = array_process(macdhist)
        data_sets = np.hstack([data_sets, macdhist])
        macdsignal = array_process(macdsignal)
        data_sets = np.hstack([data_sets, macdsignal])
    if MFI == True:
        mfi = ta.MFI(high, low, close, volume, timeperiod=14)
        mfi = array_process(mfi)
        data_sets = np.hstack([data_sets, mfi])
    if MINUS_DI == True:
        minus_di = ta.MINUS_DI(high, low, close, timeperiod=14)
        minus_di = array_process(minus_di)
        data_sets = np.hstack([data_sets, minus_di])
    if MINUS_DM == True:
        minus_dm = ta.MINUS_DM(high, low, timeperiod=14)
        minus_dm = array_process(minus_dm)
        data_sets = np.hstack([data_sets, minus_dm])
    if MOM == True:
        mom = ta.MOM(close, timeperiod=10)
        mom = array_process(mom)
        data_sets = np.hstack([data_sets, mom])
    if PLUS_DI == True:
        plus_di = ta.PLUS_DI(high, low, close, timeperiod=14)
        plus_di = array_process(plus_di)
        data_sets = np.hstack([data_sets, plus_di])
    if PLUS_DM == True:
        plus_dm = ta.PLUS_DM(high, low, timeperiod=14)
        plus_dm = array_process(plus_dm)
        data_sets = np.hstack([data_sets, plus_dm])
    if PPO == True:
        ppo = ta.PPO(close, fastperiod=12, slowperiod=26, matype=0)
        ppo = array_process(ppo)
        data_sets = np.hstack([data_sets, ppo])
    if ROC == True:
        roc = ta.ROC(close, timeperiod=10)
        roc = array_process(roc)
        data_sets = np.hstack([data_sets, roc])
    if ROCP == True:
        rocp = ta.ROCP(close, timeperiod=10)
        rocp = array_process(rocp)
        data_sets = np.hstack([data_sets, rocp])
    if ROCR == True:
        rocr = ta.ROCR(close, timeperiod=10)
        rocr = array_process(rocr)
        data_sets = np.hstack([data_sets, rocr])
    if ROCR100 == True:
        rocr100 = ta.ROCR100(close, timeperiod=10)
        rocr100 = array_process(rocr100)
        data_sets = np.hstack([data_sets, rocr100])
    if RSI == True:
        rsi = ta.RSI(close, timeperiod=14)
        rsi = array_process(rsi)
        data_sets = np.hstack([data_sets, rsi])
    if STOCH == True:
        slowk, slowd = ta.STOCH(high,
                                low,
                                close,
                                fastk_period=5,
                                slowk_period=3,
                                slowk_matype=0,
                                slowd_period=3,
                                slowd_matype=0)
        slowd = array_process(slowd)
        data_sets = np.hstack([data_sets, slowd])
        slowk = array_process(slowk)
        data_sets = np.hstack([data_sets, slowk])
    if STOCHF == True:
        fastk, fastd = ta.STOCHF(high,
                                 low,
                                 close,
                                 fastk_period=5,
                                 fastd_period=3,
                                 fastd_matype=0)
        fastd = array_process(fastd)
        data_sets = np.hstack([data_sets, fastd])
        fastk = array_process(fastk)
        data_sets = np.hstack([data_sets, fastk])
    if STOCHRSI == True:
        fastk, fastd = ta.STOCHRSI(close,
                                   timeperiod=14,
                                   fastk_period=5,
                                   fastd_period=3,
                                   fastd_matype=0)
        fastk = array_process(fastk)
        data_sets = np.hstack([data_sets, fastk])
        fastd = array_process(fastd)
        data_sets = np.hstack([data_sets, fastd])
    if TRIX == True:
        trix = ta.TRIX(close, timeperiod=30)
        trix = array_process(trix)
        data_sets = np.hstack([data_sets, trix])
    if ULTOSC == True:
        ultosc = ta.ULTOSC(high,
                           low,
                           close,
                           timeperiod1=7,
                           timeperiod2=14,
                           timeperiod3=28)
        ultosc = array_process(ultosc)
        data_sets = np.hstack([data_sets, ultosc])
    if WILLR == True:
        willr = ta.WILLR(high, low, close, timeperiod=14)
        willr = array_process(willr)
        data_sets = np.hstack([data_sets, willr])
    return data_sets[:, 1:]
Exemple #13
0
def show(args, klines, kline_column_names, display_count, disp_ic_keys):
    for index, value in enumerate(kline_column_names):
        if value == "high":
            highindex = index
        if value == "low":
            lowindex = index
        if value == "open":
            openindex = index
        if value == "close":
            closeindex = index
        if value == "volume":
            volumeindex = index
        if value == "open_time":
            opentimeindex = index

    klines_df = pd.DataFrame(klines, columns=kline_column_names)
    open_times = [
        datetime.fromtimestamp((float(open_time) / 1000))
        for open_time in klines_df["open_time"][-display_count:]
    ]
    close_times = [
        datetime.fromtimestamp((float(close_time) / 1000))
        for close_time in klines_df["close_time"][-display_count:]
    ]

    fig, axes = plt.subplots(len(disp_ic_keys) + 1, 1, sharex=True)
    fig.subplots_adjust(left=0.05,
                        bottom=0.04,
                        right=1,
                        top=1,
                        wspace=0,
                        hspace=0)
    fig.suptitle(args.s + '    ' + args.i)

    quotes = []
    for k in klines[-display_count:]:
        d = datetime.fromtimestamp(k[0] / 1000)
        quote = (dts.date2num(d), float(k[1]), float(k[4]), float(k[2]),
                 float(k[3]))
        quotes.append(quote)

    i = -1

    # kine
    i += 1
    ax = axes[i]
    mpf.candlestick_ochl(axes[i],
                         quotes,
                         width=0.02,
                         colorup='g',
                         colordown='r')
    ax.set_ylabel('price')
    ax.grid(True)
    ax.autoscale_view()
    ax.xaxis_date()

    handle_overlap_studies(args, ax, klines_df, close_times, display_count)
    """
    if args.EBANDS: # BANDS
        name = 'EBANDS'
        upperband, middleband, lowerband = tal.EBANDS(klines_df, timeperiod=26)
        ax.plot(close_times, middleband[-display_count:], "b--", label=name)
        ax.plot(close_times, upperband[-display_count:], 'y--', label=name+' upperband')
        ax.plot(close_times, lowerband[-display_count:], 'y--', label=name+' lowerband')
    """

    ic_key = 'macd'
    if ic_key in disp_ic_keys:
        i += 1
        ax = axes[i]
        ax.set_ylabel('macd')
        ax.grid(True)

        klines_df = ic.pd_macd(klines_df)
        difs = [round(a, 2) for a in klines_df["dif"]]
        deas = [round(a, 2) for a in klines_df["dea"]]
        macds = [round(a, 2) for a in klines_df["macd"]]
        ax.plot(close_times, difs[-display_count:], "y", label="dif")
        ax.plot(close_times, deas[-display_count:], "b", label="dea")
        ax.plot(close_times,
                macds[-display_count:],
                "r",
                drawstyle="steps",
                label="macd")

    ic_key = 'RSI'
    if ic_key in disp_ic_keys:
        i += 1
        ax = axes[i]
        ax.set_ylabel(ic_key)
        ax.grid(True)
        rsis = talib.RSI(klines_df["close"], timeperiod=14)
        rsis = [round(a, 2) for a in rsis][-display_count:]
        ax.plot(close_times, rsis, "r", label=ic_key)
        ax.plot(close_times, [70] * len(rsis), '-', color='r')
        ax.plot(close_times, [30] * len(rsis), '-', color='r')
        """
        rs2 = ic.py_rsis(klines, closeindex, period=14)
        rs2 = [round(a, 2) for a in rs2][-display_count:]
        axes[i].plot(close_times, rs2, "y", label="rsi2")
        """
    """
    fastk, fastd = talib.STOCHRSI(klines_df["close"], timeperiod=14)
    rsifks = [round(a, 2) for a in fastk][-display_count:]
    rsifds = [round(a, 2) for a in fastd][-display_count:]
    axes[i].plot(close_times, rsifks, "b", label="rsi")
    axes[i].plot(close_times, rsifds, "y", label="rsi")
    """

    ic_key = 'KDJ'
    if ic_key in disp_ic_keys:
        i += 1
        ax = axes[i]
        ax.set_ylabel(ic_key)
        ax.grid(True)
        """
        ks, ds = talib.STOCH(klines_df["high"], klines_df["low"], klines_df["close"],
            fastk_period=9, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0)
        js = ks - ds
        """
        ks, ds, js = ic.pd_kdj(klines_df)
        ks = [round(a, 2) for a in ks][-display_count:]
        ds = [round(a, 2) for a in ds][-display_count:]
        js = [round(a, 2) for a in js][-display_count:]
        ax.plot(close_times, ks, "b", label="K")
        ax.plot(close_times, ds, "y", label="D")
        ax.plot(close_times, js, "m", label="J")

    # Volume Indicator
    ic_key = 'AD'
    if ic_key in disp_ic_keys:
        real = talib.AD(klines_df["high"], klines_df["low"],
                        klines_df["close"], klines_df["volume"])
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'ADOSC'
    if ic_key in disp_ic_keys:
        real = talib.ADOSC(klines_df["high"],
                           klines_df["low"],
                           klines_df["close"],
                           klines_df["volume"],
                           fastperiod=3,
                           slowperiod=10)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'OBV'
    if ic_key in disp_ic_keys:
        real = talib.OBV(klines_df["close"], klines_df["volume"])
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    # Volatility Indicator
    ic_key = 'ATR'
    if ic_key in disp_ic_keys:
        real = talib.ATR(klines_df["high"],
                         klines_df["low"],
                         klines_df["close"],
                         timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'NATR'
    if ic_key in disp_ic_keys:
        real = talib.NATR(klines_df["high"],
                          klines_df["low"],
                          klines_df["close"],
                          timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'TRANGE'
    if ic_key in disp_ic_keys:
        real = talib.TRANGE(klines_df["high"], klines_df["low"],
                            klines_df["close"])
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    # Price Transform
    ic_key = 'AVGPRICE'
    if ic_key in disp_ic_keys:
        real = talib.AVGPRICE(klines_df["open"], klines_df["high"],
                              klines_df["low"], klines_df["close"])
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'MEDPRICE'
    if ic_key in disp_ic_keys:
        real = talib.MEDPRICE(klines_df["high"], klines_df["low"])
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'TYPPRICE'
    if ic_key in disp_ic_keys:
        real = talib.TYPPRICE(klines_df["high"], klines_df["low"],
                              klines_df["close"])
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'WCLPRICE'
    if ic_key in disp_ic_keys:
        real = talib.WCLPRICE(klines_df["high"], klines_df["low"],
                              klines_df["close"])
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    # Cycle Indicator
    ic_key = 'HT_DCPERIOD'
    if ic_key in disp_ic_keys:
        real = talib.HT_DCPERIOD(klines_df["close"])
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'HT_DCPHASE'
    if ic_key in disp_ic_keys:
        real = talib.HT_DCPHASE(klines_df["close"])
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'HT_PHASOR'
    if ic_key in disp_ic_keys:
        real = talib.HT_PHASOR(klines_df["close"])
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'HT_SINE'
    if ic_key in disp_ic_keys:
        real = talib.HT_SINE(klines_df["close"])
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'HT_TRENDMODE'
    if ic_key in disp_ic_keys:
        real = talib.HT_TRENDMODE(klines_df["close"])
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    # Statistic
    ic_key = 'BETA'
    if ic_key in disp_ic_keys:
        real = talib.BETA(klines_df["high"], klines_df["low"], timeperiod=5)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'CORREL'
    if ic_key in disp_ic_keys:
        real = talib.CORREL(klines_df["high"], klines_df["low"], timeperiod=30)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'LINEARREG'
    if ic_key in disp_ic_keys:
        real = talib.LINEARREG(klines_df["close"], timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'LINEARREG_ANGLE'
    if ic_key in disp_ic_keys:
        real = talib.LINEARREG_ANGLE(klines_df["close"], timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'LINEARREG_INTERCEPT'
    if ic_key in disp_ic_keys:
        real = talib.LINEARREG_INTERCEPT(klines_df["close"], timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'LINEARREG_SLOPE'
    if ic_key in disp_ic_keys:
        real = talib.LINEARREG_SLOPE(klines_df["close"], timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'STDDEV'  # Standard Deviation
    if ic_key in disp_ic_keys:
        real = talib.STDDEV(klines_df["close"], timeperiod=5, nbdev=1)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'TSF'  # Time Series Forecast
    if ic_key in disp_ic_keys:
        real = talib.TSF(klines_df["close"], timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'VAR'  # Variance
    if ic_key in disp_ic_keys:
        real = talib.VAR(klines_df["close"], timeperiod=5, nbdev=1)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    # Momentum Indicator
    ic_key = 'DX'
    if ic_key in disp_ic_keys:
        dxs = talib.DX(klines_df["high"],
                       klines_df["low"],
                       klines_df["close"],
                       timeperiod=14)
        adxs = talib.ADX(klines_df["high"],
                         klines_df["low"],
                         klines_df["close"],
                         timeperiod=14)
        adxrs = talib.ADXR(klines_df["high"],
                           klines_df["low"],
                           klines_df["close"],
                           timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, dxs[-display_count:], "r:")
        ts.ax(axes[i], ic_key, close_times, adxs[-display_count:], "y:")
        ts.ax(axes[i], ic_key, close_times, adxrs[-display_count:], "k:")

    ic_key = 'APO'
    if ic_key in disp_ic_keys:
        real = talib.APO(klines_df["close"],
                         fastperiod=12,
                         slowperiod=26,
                         matype=0)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'AROON'
    if ic_key in disp_ic_keys:
        aroondown, aroonup = talib.AROON(klines_df["high"],
                                         klines_df["low"],
                                         timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key + ' DOWN', close_times,
              aroondown[-display_count:], "y:")
        ts.ax(axes[i], ic_key + ' UP', close_times, aroonup[-display_count:],
              "y:")

    ic_key = 'AROONOSC'
    if ic_key in disp_ic_keys:
        real = talib.AROONOSC(klines_df["high"],
                              klines_df["low"],
                              timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'BOP'
    if ic_key in disp_ic_keys:
        real = talib.BOP(klines_df["open"], klines_df["high"],
                         klines_df["low"], klines_df["close"])
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'CCI'
    if ic_key in disp_ic_keys:
        real = talib.CCI(klines_df["high"],
                         klines_df["low"],
                         klines_df["close"],
                         timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'CMO'
    if ic_key in disp_ic_keys:
        real = talib.CMO(klines_df["close"], timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'MACD'
    if ic_key in disp_ic_keys:
        macd, macdsignal, macdhist = talib.MACD(klines_df["close"],
                                                fastperiod=12,
                                                slowperiod=26,
                                                signalperiod=9)
        i += 1
        ts.ax(axes[i], ic_key, close_times, macd[-display_count:], "y")
        ts.ax(axes[i], ic_key, close_times, macdsignal[-display_count:], "b")
        ts.ax(axes[i],
              ic_key,
              close_times,
              macdhist[-display_count:],
              "r",
              drawstyle="steps")

    ic_key = 'MACDEXT'
    if ic_key in disp_ic_keys:
        macd, macdsignal, macdhist = talib.MACDEXT(klines_df["close"],
                                                   fastperiod=12,
                                                   fastmatype=0,
                                                   slowperiod=26,
                                                   slowmatype=0,
                                                   signalperiod=9,
                                                   signalmatype=0)
        i += 1
        ts.ax(axes[i], ic_key, close_times, macd[-display_count:], "y")
        ts.ax(axes[i], ic_key, close_times, macdsignal[-display_count:], "b")
        ts.ax(axes[i],
              ic_key,
              close_times,
              macdhist[-display_count:],
              "r",
              drawstyle="steps")

    ic_key = 'MACDFIX'
    if ic_key in disp_ic_keys:
        macd, macdsignal, macdhist = talib.MACDFIX(klines_df["close"],
                                                   signalperiod=9)
        i += 1
        ts.ax(axes[i], ic_key, close_times, macd[-display_count:], "y")
        ts.ax(axes[i], ic_key, close_times, macdsignal[-display_count:], "b")
        ts.ax(axes[i],
              ic_key,
              close_times,
              macdhist[-display_count:],
              "r",
              drawstyle="steps")

    ic_key = 'MFI'
    if ic_key in disp_ic_keys:
        real = talib.MFI(klines_df["high"], klines_df["low"],
                         klines_df["close"], klines_df["volume"])
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'MINUS_DI'
    if ic_key in disp_ic_keys:
        real = talib.MINUS_DI(klines_df["high"],
                              klines_df["low"],
                              klines_df["close"],
                              timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'MINUS_DM'
    if ic_key in disp_ic_keys:
        real = talib.MINUS_DM(klines_df["high"],
                              klines_df["low"],
                              timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'MOM'
    if ic_key in disp_ic_keys:
        real = talib.MOM(klines_df["close"], timeperiod=10)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'PLUS_DI'
    if ic_key in disp_ic_keys:
        real = talib.PLUS_DI(klines_df["high"],
                             klines_df["low"],
                             klines_df["close"],
                             timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'PLUS_DM'
    if ic_key in disp_ic_keys:
        real = talib.PLUS_DM(klines_df["high"],
                             klines_df["low"],
                             timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'PPO'
    if ic_key in disp_ic_keys:
        real = talib.PPO(klines_df["close"],
                         fastperiod=12,
                         slowperiod=26,
                         matype=0)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'ROC'
    if ic_key in disp_ic_keys:
        real1 = talib.ROC(klines_df["close"], timeperiod=10)
        real2 = talib.ROCP(klines_df["close"], timeperiod=10)
        real3 = talib.ROCR(klines_df["close"], timeperiod=10)
        real4 = talib.ROCR100(klines_df["close"], timeperiod=10)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real1[-display_count:], "y:")
        ts.ax(axes[i], ic_key, close_times, real2[-display_count:], "k:")
        ts.ax(axes[i], ic_key, close_times, real3[-display_count:], "m:")
        ts.ax(axes[i], ic_key, close_times, real4[-display_count:], "b:")

    ic_key = 'STOCH'
    if ic_key in disp_ic_keys:
        slowk, slowd = talib.STOCH(klines_df["high"],
                                   klines_df["low"],
                                   klines_df["close"],
                                   fastk_period=5,
                                   slowk_period=3,
                                   slowk_matype=0,
                                   slowd_period=3,
                                   slowd_matype=0)
        i += 1
        slowj = 3 * slowk - 2 * slowd
        ts.ax(axes[i], ic_key, close_times, slowk[-display_count:], "b")
        ts.ax(axes[i], ic_key, close_times, slowd[-display_count:], "y")
        ts.ax(axes[i], ic_key, close_times, slowj[-display_count:], "m")

    ic_key = 'STOCHF'
    if ic_key in disp_ic_keys:
        fastk, fastd = talib.STOCHF(klines_df["high"],
                                    klines_df["low"],
                                    klines_df["close"],
                                    fastk_period=5,
                                    fastd_period=3,
                                    fastd_matype=0)
        i += 1
        fastj = 3 * fastk - 2 * fastd
        ts.ax(axes[i], ic_key, close_times, fastk[-display_count:], "y:")
        ts.ax(axes[i], ic_key, close_times, fastd[-display_count:], "b:")
        ts.ax(axes[i], ic_key, close_times, fastj[-display_count:], "m")

    ic_key = 'STOCHRSI'
    if ic_key in disp_ic_keys:
        fastk, fastd = talib.STOCHRSI(klines_df["close"],
                                      timeperiod=14,
                                      fastk_period=5,
                                      fastd_period=3,
                                      fastd_matype=0)
        i += 1
        ts.ax(axes[i], ic_key, close_times, fastk[-display_count:], "y:")
        ts.ax(axes[i], ic_key, close_times, fastd[-display_count:], "b:")

    ic_key = 'TRIX'
    if ic_key in disp_ic_keys:
        real = talib.TRIX(klines_df["close"], timeperiod=30)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'ULTOSC'
    if ic_key in disp_ic_keys:
        real = talib.ULTOSC(klines_df["high"],
                            klines_df["low"],
                            klines_df["close"],
                            timeperiod1=7,
                            timeperiod2=14,
                            timeperiod3=28)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'WILLR'
    if ic_key in disp_ic_keys:
        real = talib.WILLR(klines_df["high"],
                           klines_df["low"],
                           klines_df["close"],
                           timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    plt.show()
Exemple #14
0
 def get_quota(self):
     #stock_amount = cral_CNstock_order_ana.main()
     close = self.__df['close']
     high_prices = self.__df['high'].values
     low_prices = self.__df['low'].values
     close_prices = close.values
     ma5 = talib.MA(close_prices, 5)
     ma10 = talib.MA(close_prices, 10)
     ma20 = talib.MA(close_prices, 20)
     ma30 = talib.MA(close_prices, 30)
     K, D = talib.STOCH(high_prices,
                        low_prices,
                        close_prices,
                        fastk_period=9,
                        slowk_period=3)
     J = K * 3 - D * 2
     sar = talib.SAR(high_prices,
                     low_prices,
                     acceleration=0.05,
                     maximum=0.2)
     sar = pd.DataFrame(sar - close)
     sar.index = self.__df.date
     atr = talib.ATR(high_prices, low_prices, close_prices)
     natr = talib.NATR(high_prices, low_prices, close_prices)
     trange = talib.TRANGE(high_prices, low_prices, close_prices)
     cci = talib.CCI(high_prices, low_prices, close_prices, 14)
     dif, dea, bar = talib.MACDFIX(close_prices)
     bar = bar * 2
     df_all = self.__df.drop(['code', 'open', 'low', 'high', 'volume'],
                             axis=1).set_index('date')
     df_all.insert(0, 'ma5', ma5)
     df_all.insert(0, 'ma10', ma10)
     df_all.insert(0, 'ma20', ma20)
     df_all.insert(0, 'ma30', ma30)
     df_all.insert(0, 'K', K)
     df_all.insert(0, 'D', D)
     df_all.insert(0, 'J', J)
     df_all.insert(0, 'cci', cci)
     df_all.insert(0, 'bar', bar)
     df_all.insert(0, 'dif', dif)
     df_all.insert(0, 'dea', dea)
     df_all.insert(0, 'sar', sar)
     #df_all = pd.concat([df_all,stock_amount],axis=1)
     df_yesterday = df_all.T
     index_c = df_all.index
     added = [np.nan] * len(df_all.columns)
     df_yesterday.insert(0, len(df_yesterday.columns), added)
     df_yesterday = df_yesterday.T
     df_yesterday = df_yesterday.drop(df_all.index[len(df_all.index) - 1])
     df_yesterday.insert(0, 'index_c', index_c)
     df_yesterday = df_yesterday.set_index('index_c')
     df_dif = df_all - df_yesterday
     df_dif_close_plus_one_day = df_dif.copy()
     for i in range(len(df_dif_close_plus_one_day['close']) - 1):
         df_dif_close_plus_one_day['close'][i] = df_dif_close_plus_one_day[
             'close'][i + 1]
     df_dif_close_plus_one_day['close'][
         len(df_dif_close_plus_one_day['close']) - 1] = np.nan
     df_dif = df_dif.dropna(axis=0, how='any')
     df_dif_close_plus_one_day = df_dif_close_plus_one_day.dropna(axis=0,
                                                                  how='any')
     return df_dif, df_dif_close_plus_one_day
Exemple #15
0
def ta_atr(n, k_data):
    atr = pd.DataFrame()
    atr['atr'] = ta.ATR(k_data.high, k_data.low, k_data.close, timeperiod=n)
    return (atr.round(3))
Exemple #16
0
    def run_factor_plot(self):

        list_signal = []
        is_win = False
        self.kl_pd['Ma30'] = self.kl_pd.Close.rolling(window=30).mean()#pd.rolling_mean(self.kl_pd.Close,window=30)#增加M30移动平均线 

        #print self.kl_pd.loc['2017-12-27':'2018-02-09'].filter(['Close','Ma30'])
        
        #self.kl_pd.apply(self._day_task, axis=1)
        
        self.kl_pd['atr14'] = talib.ATR(self.kl_pd.High.values,self.kl_pd.Low.values,self.kl_pd.Close.values,timeperiod=14)#计算ATR14 
        self.kl_pd['atr21'] = talib.ATR(self.kl_pd.High.values,self.kl_pd.Low.values,self.kl_pd.Close.values,timeperiod=21)#计算ATR21 
        
        #pd.DataFrame({'close':self.kl_pd.Close, 'atr14':self.kl_pd.atr14,'art21':self.kl_pd.art21,})
        self.kl_pd['artwin'] = self.kl_pd.Close - self.kl_pd['atr14']*3#止盈对应的买入价位
        self.kl_pd['artloss'] = self.kl_pd.Close + self.kl_pd['atr14']*1#止损对应的买入价位
        
        p1 = plt.subplot(3,1,1)
        self.kl_pd.Close.plot()
        self.kl_pd.Ma30.plot(c='black')
        self.kl_pd.artwin.plot()
        self.kl_pd.artloss.plot()

        plt.title(u'浙大网新')
        plt.ylim(np.min(self.kl_pd.Close)-5,np.max(self.kl_pd.Close)+5)#设置Y轴范围
        plt.xticks([])  #去掉纵坐标值
        plt.legend(['Close','30ave','atrwin','artloss'],loc='best')

        
        for kl_index,today in self.kl_pd.iterrows():

            signal = self._day_task(kl_index, self.buy_price)
            
            if signal > 0:# 买入    
                if is_win == False:#空仓则买
                    start = self.kl_pd.index.get_loc(kl_index)
                    is_win = True
                    self.buy_price = today.Close
                    self.posit_num = int(self.cash_hold/today.Close)
                    self.cash_hold = 0 
                    print("Start order",kl_index,today.Close)
                    plt.annotate('B',xy=(kl_index,self.kl_pd.Close.asof(kl_index)),xytext=(kl_index, self.kl_pd.Close.asof(kl_index)+4),arrowprops=dict(facecolor='yellow',shrink=0.1),horizontalalignment='left',verticalalignment='top')

            elif signal < 0:# 卖出 
                if is_win == True:#避免未买先卖
                    end = self.kl_pd.index.get_loc(kl_index)
                    is_win = False
                    self.buy_price = 0
                    print("End order",kl_index,today.Close)
                    self.cash_hold = int(self.posit_num*today.Close)
                    self.market_total = 0

                    if self.kl_pd.Close[end] < self.kl_pd.Close[start]:#赔钱显示绿色
                        plt.fill_between(self.kl_pd.index[start:end],0,self.kl_pd.Close[start:end],color='green',alpha=0.38)
                        
                    else:#赚钱显示绿色
                        plt.fill_between(self.kl_pd.index[start:end],0,self.kl_pd.Close[start:end],color='red',alpha=0.38)
            list_signal.append(is_win) 
            
            if is_win == True:
                self.market_total = int(self.posit_num*today.Close)
                self.profit_curve.append(self.market_total)
            else:
                self.profit_curve.append(self.cash_hold)

        self.kl_pd['keep'] = list_signal
        self.kl_pd['keep'].fillna(method = 'ffill',inplace = True)

        """ 计算基准收益 """
        self.kl_pd['benchmark_profit'] = np.log(self.kl_pd.Close/self.kl_pd.Close.shift(1))
        """ 计算趋势突破策略收益 """
        self.kl_pd['trend_profit'] = self.kl_pd.keep*self.kl_pd.benchmark_profit  
        """ 可视化收益情况对比 """       
        p2 = plt.subplot(3,1,2)  
        self.kl_pd[['benchmark_profit','trend_profit']].cumsum().plot(grid=True,ax = p2)
        plt.xticks([])  #去掉纵坐标值
        plt.legend(['benchmark_profit','trend_profit'],loc='best')
                
        p3 = plt.subplot(3,1,3)       
        p3.xaxis.set_minor_locator(mdates.WeekdayLocator(byweekday=(1),interval=1))
        p3.xaxis.set_minor_formatter(mdates.DateFormatter('%d\n%a'))                
        self.kl_pd['profit'] = self.profit_curve
        self.kl_pd.profit.plot()
        plt.legend(['profit'],loc='best')
        plt.xticks([])  #去掉纵坐标值
        #plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0, hspace=0.25)
        plt.subplots_adjust(left=0.09,bottom=0.20, right=0.94,top=0.95, wspace=0, hspace=0.25)
        plt.show()
Exemple #17
0
import numpy as np

from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

df = quandl.get("CHRIS/CME_ES2")
df.head()
df.tail()
df.shape

# need to find ta ta lib
# import talib as ta
df['EMA10'] = ta.EMA(df['Settle'].values, timeperiod=10)
df['EMA30'] = ta.EMA(df['Settle'].values, timeperiod=30)
df['ATR'] = ta.ATR(df['High'].values,
                   df['Low'].values,
                   df['Settle'].values,
                   timeperiod=14)
df['ADX'] = ta.ADX(df['High'].values,
                   df['Low'].values,
                   df['Settle'].values,
                   timeperiod=14)
df['RSI'] = ta.RSI(df['Settle'].values, timeperiod=14)
macd, macdsignal, macdhist = ta.MACD(df['Settle'].values,
                                     fastperiod=12,
                                     slowperiod=26,
                                     signalperiod=9)
df['MACD'] = macd
df['MACDsignal'] = macdsignal
df.tail()

# Calc Predictors
Exemple #18
0
    def onBar(self, bar):
        """收到Bar推送(必须由用户继承实现)"""
        # 撤销之前发出的尚未成交的委托(包括限价单和停止单)
        for orderID in self.orderList:
            self.cancelOrder(orderID)
        self.orderList = []

        # 保存K线数据
        self.closeArray[0:self.bufferSize -
                        1] = self.closeArray[1:self.bufferSize]
        self.highArray[0:self.bufferSize -
                       1] = self.highArray[1:self.bufferSize]
        self.lowArray[0:self.bufferSize - 1] = self.lowArray[1:self.bufferSize]

        self.closeArray[-1] = bar.close
        self.highArray[-1] = bar.high
        self.lowArray[-1] = bar.low

        self.bufferCount += 1
        if self.bufferCount < self.bufferSize:
            return

        # 计算指标数值
        self.atrValue = talib.ATR(self.highArray, self.lowArray,
                                  self.closeArray, self.atrLength)[-1]
        self.atrArray[0:self.bufferSize - 1] = self.atrArray[1:self.bufferSize]
        self.atrArray[-1] = self.atrValue

        self.atrCount += 1
        if self.atrCount < self.bufferSize:
            return

        self.atrMa = talib.MA(self.atrArray, self.atrMaLength)[-1]
        self.rsiValue = talib.RSI(self.closeArray, self.rsiLength)[-1]

        # 判断是否要进行交易

        # 当前无仓位
        if self.pos == 0:
            self.intraTradeHigh = bar.high
            self.intraTradeLow = bar.low

            # ATR数值上穿其移动平均线,说明行情短期内波动加大
            # 即处于趋势的概率较大,适合CTA开仓
            if self.atrValue > self.atrMa:
                # 使用RSI指标的趋势行情时,会在超买超卖区钝化特征,作为开仓信号
                if self.rsiValue > self.rsiBuy:
                    # 这里为了保证成交,选择超价5个整指数点下单
                    self.buy(bar.close + 5, 1)
                    return

                if self.rsiValue < self.rsiSell:
                    self.short(bar.close - 5, 1)
                    return

        # 持有多头仓位
        if self.pos == 1:
            # 计算多头持有期内的最高价,以及重置最低价
            self.intraTradeHigh = max(self.intraTradeHigh, bar.high)
            self.intraTradeLow = bar.low
            # 计算多头移动止损
            longStop = self.intraTradeHigh * (1 - self.trailingPercent / 100)
            # 发出本地止损委托,并且把委托号记录下来,用于后续撤单
            orderID = self.sell(longStop, 1, stop=True)
            self.orderList.append(orderID)
            return

        # 持有空头仓位
        if self.pos == -1:
            self.intraTradeLow = min(self.intraTradeLow, bar.low)
            self.intraTradeHigh = bar.high

            shortStop = self.intraTradeLow * (1 + self.trailingPercent / 100)
            orderID = self.cover(shortStop, 1, stop=True)
            self.orderList.append(orderID)
            return

        # 发出状态更新事件
        self.putEvent()
    "/Users/wuyong/alldata/original_data/trades_bian_ethusdt_s_2.csv",
    index_col=0)
# print(data_zb.head())
data_zb["tickid"] = data_zb["dealtime"]
# data_zb["tickid"] = data_zb.index
data_zb["close"] = data_zb["price"]
# print(data_zb.head(30))
# print(len(data_zb))
data_k = pd.read_csv(
    "/Users/wuyong/alldata/original_data/trades_bian_ethusdt_m_2.csv",
    index_col=0)
# print(data_k.head(20))
# atr = ta.ATR(data_k['high'].values, data_k['low'].values, data_k['close'].values, timeperiod=90)
# data_k["atr_90"] = atr
atr = ta.ATR(data_k['high'].values,
             data_k['low'].values,
             data_k['close'].values,
             timeperiod=7)
data_k["atr_7"] = atr
data_k["growth"] = data_k["close"] - data_k["open"]
data_k["growth"] = data_k["growth"].apply(lambda x: 1 if x > 0 else 0)
data_k["growth"] = ts_sum(data_k["growth"])
data_k["high_35"] = ts_max(data_k["high"], window=55)
data_k["low_30"] = ts_min(data_k["low"], window=55)
data_k["low_days"] = ts_lowday(data_k["low"], window=35)
data_k["ma7"] = ta.MA(data_k["close"].values, timeperiod=7, matype=0)
data_k["ma90"] = ta.MA(data_k["close"].values, timeperiod=90, matype=0)
data_k["ma450"] = ta.MA(data_k["close"].values, timeperiod=450, matype=0)
data_k["diff"] = data_k["ma7"] - data_k["ma90"]
data_k["diff"] = data_k["diff"].apply(lambda x: 0 if x > 0 else x)
data_k["diff"] = data_k["diff"].apply(lambda x: 1 if x < 0 else x)
data_k["filter"] = [
data['SAR'] = talib.SAR(data.High, data.Low, acceleration=0.02, maximum=0.2)

# Plot Parabolic SAR with close price
data[['Close', 'SAR']][:500].plot(figsize=(10,5))
plt.grid()
plt.show()

'''ADX'''

real = ADX(high, low, close, timeperiod=14)

'''Bollinger bands'''

up, mid, low = BBANDS(close, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0)


'''RSI'''

 RSI(close, timeperiod=14)
 


''' ATR'''

odayATR = talib.ATR(df1['High'],df1['Low'],df1['Close'],timeperiod=20)

'''Stochastic'''

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

Exemple #21
0
def feat_imp():
    

    import pandas as pd
    import numpy as np
    import talib as ta
    import matplotlib.pyplot as plt
    #get_ipython().run_line_magic('matplotlib', 'inline')
    #from nsepy import get_history
    from datetime import date
    import LSTM9
    from LSTM9 import CSV_file


    # In[2]:


    df=pd.read_csv(LSTM9.CSV_file+'.csv',index_col='Date',parse_dates=True)

    #df=pd.read_csv('995_PAGE_IND.csv',index_col='datetime',parse_dates=True)
    #df=pd.read_csv('995_PAGE_IND.csv',index_col='datetime',parse_dates=True)
    #del df['Volume']
    #del df['Turnover (Lacs)']
    O=df['Open']
    H=df['High']
    L=df['Low']
    C=df['Close']


    # In[3]:


    df['ADX'] = ta.ADX(O, L, C, timeperiod=14)
    df['RSI'] = ta.RSI( C, timeperiod=14)


    df['SMA_10']=C.rolling(10).mean()
    df['SMA_21']=C.rolling(21).mean()
    df['SMA_3']=C.rolling(3).mean()
    df['SMA_50']=C.rolling(50).mean()


    df['exp_10'] = C.ewm(span=10, adjust=False).mean()
    df['exp_21'] = C.ewm(span=21, adjust=False).mean()


    #Average True Range
    df['ATR']=ta.ATR(H,L,C,timeperiod=14)




    #Commodiy Channel Index 
    df['CCI']=ta.CCI(H,L,C,timeperiod=14)


    #Momentum
    df['MOM']=ta.MOM(C,timeperiod=10)


    #ROC
    df['ROC']=ta.ROC(C,timeperiod=10)


    #ROCP
    df['ROCR']=ta.ROCP(C,timeperiod=10)



    #Williams %R

    df['Williams %R']=ta.WILLR(H,L,C,timeperiod=14)


    #Stochastic %K


    df['slowk'], df['slowd'] = ta.STOCH(H, L, C, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0)


    # In[4]:


    #drop all the nan values
    df=df.dropna()
    df.head()


    #For Converting into a Binary Classification Problem we will assign them into 1 or 0 values
    df['pred_price']=np.where(df['Close'].shift(-1)>df['Close'],1,0)


    A=df['pred_price'].unique()

    print(A)


    # In[5]:


    #Seperating into target and test set

    y=df['pred_price']
    x=df.drop(columns=['pred_price'])



    #define train/test split ratio
    split_ratio=0.9


    train_x=x[0:int(split_ratio*len(x))]
    test_x=x[int(split_ratio*len(x)):(len(x))]



    print('Observations: %d' % (len(x)))
    print('Train Dataset:',train_x.shape)
    print('Test Dataset:',test_x.shape)


    print('----------------------------')


    train_y=y[0:int(split_ratio*len(y))]
    test_y=y[int(split_ratio*len(y)):(len(y))]



    print('Observations: %d' % (len(y)))
    print('Train Dataset:',train_y.shape)
    print('Test Dataset:',test_y.shape)










    # In[6]:


    #Normalizing the data


    from sklearn.preprocessing import MinMaxScaler
    scaler=MinMaxScaler(feature_range=(0,1)) #scaling Down
    train_x_scaled=scaler.fit_transform(train_x)

    test_x_scaled=scaler.fit_transform(test_x)

    print(train_x_scaled)


    # In[22]:


    import time 

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.colors import ListedColormap
    from sklearn.model_selection import train_test_split
    from sklearn.preprocessing import StandardScaler
    from sklearn.datasets import make_moons, make_circles, make_classification
    from sklearn.neural_network import MLPClassifier
    from sklearn.neighbors import KNeighborsClassifier
    from sklearn.svm import SVC
    from sklearn.gaussian_process import GaussianProcessClassifier
    from sklearn.gaussian_process.kernels import RBF
    from sklearn.tree import DecisionTreeClassifier
    from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
    from sklearn.naive_bayes import GaussianNB
    from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
    from sklearn.feature_selection import RFE
    from sklearn.linear_model import LogisticRegression



    dict_classifiers={
        "Logistic Regression":LogisticRegression(solver='lbfgs',max_iter=5000),
        "Nearest Neighbors" : KNeighborsClassifier(),
        "Support Vector Machine": SVC(gamma='auto'),
        #"Gradient Boosting Classifier": XGBClassifier(),
        "Decision Tree": DecisionTreeClassifier(),
        "Random Forest":RandomForestClassifier(n_estimators=100),
        "Neural Net":MLPClassifier(solver='adam',alpha=0.0001,learning_rate='constant',learning_rate_init=0.001),
        "Naive Bayes":GaussianNB()
    }


    # In[23]:


    no_classifiers=len(dict_classifiers.keys())
    import time 


    def batch_classify(train_x_scaled,train_y,verbose=True):
        df_results=pd.DataFrame(data=np.zeros(shape=(no_classifiers,3)),columns=['classifier','train_score','training_time'])

        
        
        count=0
        for key,classifier in dict_classifiers.items():
            t_start=time.process_time()
            classifier.fit(train_x_scaled,train_y)
            t_end=time.process_time()
            t_diff=t_end-t_start

            train_score=classifier.score(train_x_scaled,train_y)
            df_results.loc[count,'classifier']=key
            df_results.loc[count,'train_score']=train_score
            df_results.loc[count,'training_time']=t_diff
            if verbose:
                print('trained {c} in {f:2f}s'.format(c=key,f=t_diff))
            count+=1
        return df_results
        


    # In[24]:


    df_results=batch_classify(train_x_scaled,train_y)
    print(df_results)


    # In[25]:


    log_reg = LogisticRegression(solver='lbfgs', max_iter=5000)
    log_reg.fit(train_x_scaled, train_y)


    # In[26]:


    import sklearn
    predictions=log_reg.predict(test_x_scaled)
    print('accuracy:',sklearn.metrics.accuracy_score(test_y,predictions))
    print("confusion matrix:",sklearn.metrics.confusion_matrix(test_y,predictions))
    print("classification report:",sklearn.metrics.classification_report(test_y,predictions))


    # In[27]:


    #roc curve


    y_pred_proba=log_reg.predict_proba(test_x_scaled)[:,1]

    fpr,tpr,thresholds=sklearn.metrics.roc_curve(test_y,y_pred_proba)

    roc_auc=sklearn.metrics.auc(fpr,tpr)


    #plot of Roc
    print('ROC AUC is ' +str(roc_auc))
    plt.plot([0,1],[0,1],'k--')
    plt.plot(fpr,tpr)
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.title('ROC curve')
    plt.show(block=False)
    plt.pause(5)
    plt.close()


    # In[28]:


    #Feature Importance

    feature_importance=abs(log_reg.coef_[0])
    print(feature_importance)
    feature_importance=100.0*((feature_importance)/feature_importance.max())
    sorted_idx=np.argsort(feature_importance)
    pos=np.arange(sorted_idx.shape[0])+0.5

    featfig=plt.figure(figsize=(20,10))
    featax=featfig.add_subplot(1,1,1)
    featax.barh(pos,feature_importance[sorted_idx],align='center')
    featax.set_yticks(pos)
    featax.set_yticklabels(np.array(train_x.columns)[sorted_idx],fontsize=15)
    featax.set_xlabel('Relative Feature Importance')

    plt.tight_layout()
    plt.show()
Exemple #22
0
 def ATR_factor(self, df, timeperiod=14):
     return talib.ATR(
         df.loc[:, self.map_dict['high']].values,
         df.loc[:, self.map_dict['low']].values,
         df.loc[:, self.map_dict['close']].values,
         timeperiod)
Exemple #23
0
    def addIndi(self, enrich, endf):
        # Overlays
        if enrich == 'bbands':
            bbup, bbmid, bblow = ta.BBANDS(endf['Close'], timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)
            endf.insert(0, column='bblow', value=bblow)
            endf.insert(0, column='bbmid', value=bbmid)
            endf.insert(0, column='bbup', value=bbup)
            return endf
        if enrich == 'mama':
            mama, fama = ta.MAMA(endf['Close'])
            endf.insert(0, column='fama', value=fama)
            endf.insert(0, column='mama', value=mama)
            return endf
        if enrich == 'dema':
            endf.insert(0, column='dema', value=ta.DEMA(endf['Close'], timeperiod=30))
            return endf
        if enrich == 'ema':
            endf.insert(0, column='ema', value=ta.EMA(endf['Close'], timeperiod=30))  # Unstable period
            return endf
        if enrich == 'ht_trendline':
            endf.insert(0, column='ht_trendline', value=ta.HT_TRENDLINE(endf['Close']))  # Unstable period
            return endf
        if enrich == 'kama':
            endf.insert(0, column='kama', value=ta.KAMA(endf['Close'], timeperiod=30))  # Unstable period
            return endf
        if enrich == 'ma':
            endf.insert(0, column='ma', value=ta.MA(endf['Close'], timeperiod=30, matype=0))
            return endf
        if enrich == 'midpoint':
            endf.insert(0, column='midpoint', value=ta.MIDPOINT(endf['Close'], timeperiod=14))
            return endf
        if enrich == 'midprice':
            endf.insert(0, column='midprice', value=ta.MIDPRICE(endf['High'], endf['Low'], timeperiod=14))
            return endf
        if enrich == 'sar':
            endf.insert(0, column='sar', value=ta.SAR(endf['High'], endf['Low'], acceleration=0, maximum=0))
            return endf
        if enrich == 'sarext':
            endf.insert(0, column='sarext', value=ta.SAREXT(endf['High'], endf['Low'], startvalue=0, offsetonreverse=0, accelerationinitlong=0, accelerationlong=0, accelerationmaxlong=0, accelerationinitshort=0, accelerationshort=0, accelerationmaxshort=0))
            return endf
        if enrich == 'sma':
            endf.insert(0, column='sma', value=ta.SMA(endf['Close'], timeperiod=30))
            return endf
        if enrich == 't3':
            endf.insert(0, column='t3', value=ta.T3(endf['Close'], timeperiod=5, vfactor=0))  # Unstable period
            return endf
        if enrich == 'tema':
            endf.insert(0, column='tema', value=ta.TEMA(endf['Close'], timeperiod=30))
            return endf
        if enrich == 'trima':
            endf.insert(0, column='trima', value=ta.TRIMA(endf['Close'], timeperiod=30))
            return endf
        if enrich == 'wma':
            endf.insert(0, column='wma', value=ta.WMA(endf['Close'], timeperiod=30))
            return endf

        # Momentum
        if enrich == 'adx':
            endf.insert(0, column='adx', value=ta.ADX(endf['High'], endf['Low'], endf['Close'], timeperiod=14))
            return endf
        if enrich == 'adxr':
            endf.insert(0, column='adxr', value=ta.ADXR(endf['High'], endf['Low'], endf['Close'], timeperiod=14))
            return endf
        if enrich == 'apo':
            endf.insert(0, column='apo', value=ta.APO(endf['Close'], fastperiod=12, slowperiod=26, matype=0))
            return endf
        if enrich == 'aroonosc':
            endf.insert(0, column='aroonosc', value=ta.AROONOSC(endf['High'], endf['Low'], timeperiod=14))
            return endf
        if enrich == 'aroon':
            aroondown, aroonup = ta.AROON(endf['High'], endf['Low'], timeperiod=14)
            endf.insert(0, column='aroonup', value=aroonup)
            endf.insert(0, column='aroondown', value=aroondown)
            return endf
        if enrich == 'bop':
            endf.insert(0, column='bop', value=ta.BOP(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cci':
            endf.insert(0, column='cci', value=ta.CCI(endf['High'], endf['Low'], endf['Close'], timeperiod=14))
            return endf
        if enrich == 'cmo':
            endf.insert(0, column='cmo', value=ta.CMO(endf['Close'], timeperiod=14))
            return endf
        if enrich == 'dx':
            endf.insert(0, column='dx', value=ta.DX(endf['High'], endf['Low'], endf['Close'], timeperiod=14))
            return endf
        if enrich == 'macd':
            macd, macdsignal, macdhist = ta.MACD(endf['Close'], fastperiod=12, slowperiod=26, signalperiod=9)
            endf.insert(0, column='macd', value=macd)
            endf.insert(0, column='macdsignal', value=macdsignal)
            endf.insert(0, column='macdhist', value=macdhist)
            return endf
        if enrich == 'mfi':
            endf.insert(0, column='mfi', value=ta.MFI(endf['High'], endf['Low'], endf['Close'], endf['Volume'], timeperiod=14))
            return endf
        if enrich == 'mom':
            endf.insert(0, column='mom', value=ta.MOM(endf['Close'], timeperiod=10))
            return endf
        if enrich == 'ppo':
            endf.insert(0, column='ppo', value=ta.PPO(endf['Close'], fastperiod=12, slowperiod=26, matype=0))
            return endf
        if enrich == 'roc':
            endf.insert(0, column='roc', value=ta.ROC(endf['Close'], timeperiod=10))
            return endf
        if enrich == 'rocp':
            endf.insert(0, column='rocp', value=ta.ROCP(endf['Close'], timeperiod=10))
            return endf
        if enrich == 'rsi':
            endf.insert(0, column='rsi', value=ta.RSI(endf['Close'], timeperiod=14))
            return endf
        if enrich == 'stoch':
            slowk, slowd = ta.STOCH(endf['High'], endf['Low'], endf['Close'], fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0)
            endf.insert(0, column='slowk', value=slowk)
            endf.insert(0, column='slowd', value=slowd)
            return endf
        if enrich == 'trix':
            endf.insert(0, column='trix', value=ta.TRIX(endf['Close'], timeperiod=30))
            return endf
        if enrich == 'ultosc':
            endf.insert(0, column='ultosc', value=ta.ULTOSC(endf['High'], endf['Low'], endf['Close'], timeperiod1=7, timeperiod2=14, timeperiod3=28))
            return endf
        if enrich == 'willr':
            endf.insert(0, column='willr', value=ta.WILLR(endf['High'], endf['Low'], endf['Close'], timeperiod=14))
            return endf

        # Volume
        if enrich == 'ad':
            endf.insert(0, column='ad', value=ta.AD(endf['High'], endf['Low'], endf['Close'], endf['Volume']))
            return endf
        if enrich == 'adosc':
            endf.insert(0, column='adosc', value=ta.ADOSC(endf['High'], endf['Low'], endf['Close'], endf['Volume'], fastperiod=3, slowperiod=10))
            return endf
        if enrich == 'obv':
            endf.insert(0, column='obv', value=ta.OBV(endf['Close'], endf['Volume']))
            return endf

        # Volitility
        if enrich == 'atr':
            endf.insert(0, column='atr', value=ta.ATR(endf['High'], endf['Low'], endf['Close'], timeperiod=14))
            return endf
        if enrich == 'natr':
            endf.insert(0, column='natr', value=ta.NATR(endf['High'], endf['Low'], endf['Close'], timeperiod=14))
            return endf
        if enrich == 'trange':
            endf.insert(0, column='trange', value=ta.TRANGE(endf['High'], endf['Low'], endf['Close']))
            return endf

        # Pattern
        if enrich == 'cdl2crows':
            endf.insert(0, column='cdl2crows', value=ta.CDL2CROWS(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdl3blackcrows':
            endf.insert(0, column='cdl3blackcrows', value=ta.CDL3BLACKCROWS(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdl3inside':
            endf.insert(0, column='cdl3inside', value=ta.CDL3INSIDE(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdl3linestrike':
            endf.insert(0, column='cdl3linestrike', value=ta.CDL3LINESTRIKE(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdl3outside':
            endf.insert(0, column='cdlcdl3outside', value=ta.CDL3OUTSIDE(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdl3starsinsouth':
            endf.insert(0, column='cdl3starsinsouth', value=ta.CDL3STARSINSOUTH(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdl3whitesoldiers':
            endf.insert(0, column='cdl3whitesoldiers', value=ta.CDL3WHITESOLDIERS(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlabandonedbaby':
            endf.insert(0, column='cdlabandonedbaby', value=ta.CDLABANDONEDBABY(endf['Open'], endf['High'], endf['Low'], endf['Close'], penetration=0))
            return endf
        if enrich == 'cdladvanceblock':
            endf.insert(0, column='cdladvanceblock', value=ta.CDLADVANCEBLOCK(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlbelthold':
            endf.insert(0, column='cdlbelthold', value=ta.CDLBELTHOLD(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlbreakaway':
            endf.insert(0, column='cdlbreakaway', value=ta.CDLBREAKAWAY(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlclosingmarubozu':
            endf.insert(0, column='cdlclosingmarubozu', value=ta.CDLCLOSINGMARUBOZU(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlconcealbabyswall':
            endf.insert(0, column='cdlconcealbabyswall', value=ta.CDLCONCEALBABYSWALL(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlcounterattack':
            endf.insert(0, column='cdlcounterattack', value=ta.CDLCOUNTERATTACK(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdldarkcloudcover':
            endf.insert(0, column='cdldarkcloudcover', value=ta.CDLDARKCLOUDCOVER(endf['Open'], endf['High'], endf['Low'], endf['Close'], penetration=0))
            return endf
        if enrich == 'cdldoji':
            endf.insert(0, column='cdldoji', value=ta.CDLDOJI(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdldojistar':
            endf.insert(0, column='cdldojistar', value=ta.CDLDOJISTAR(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdldragonflydoji':
            endf.insert(0, column='cdldragonflydoji', value=ta.CDLDRAGONFLYDOJI(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlengulfing':
            endf.insert(0, column='cdlengulfing', value=ta.CDLENGULFING(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdleveningdojistar':
            endf.insert(0, column='cdleveningdojistar', value=ta.CDLEVENINGDOJISTAR(endf['Open'], endf['High'], endf['Low'], endf['Close'], penetration=0))
            return endf
        if enrich == 'cdleveningstar':
            endf.insert(0, column='cdleveningstar', value=ta.CDLEVENINGSTAR(endf['Open'], endf['High'], endf['Low'], endf['Close'], penetration=0))
            return endf
        if enrich == 'cdlgapsidesidewhite':
            endf.insert(0, column='cdlgapsidesidewhite', value=ta.CDLGAPSIDESIDEWHITE(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlgravestonedoji':
            endf.insert(0, column='cdlgravestonedoji', value=ta.CDLGRAVESTONEDOJI(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlhammer':
            endf.insert(0, column='cdlhammer', value=ta.CDLHAMMER(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlhangingman':
            endf.insert(0, column='cdlhangingman', value=ta.CDLHANGINGMAN(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlharami':
            endf.insert(0, column='cdlharami', value=ta.CDLHARAMI(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlharamicross':
            # print(endf.info(),file=sys.stderr)
            endf.insert(0, column='cdlharamicross', value=ta.CDLHARAMICROSS(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            # print(endf.info(),file=sys.stderr)
            return endf
        if enrich == 'cdlhighwave':
            print(endf.info(), file=sys.stderr)
            endf.insert(0, column='cdlhighwave', value=ta.CDLHIGHWAVE(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlhikkake':
            endf.insert(0, column='cdlhikkake', value=ta.CDLHIKKAKE(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlhikkakemod':
            endf.insert(0, column='cdlhikkakemod', value=ta.CDLHIKKAKEMOD(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlhomingpigeon':
            endf.insert(0, column='cdlhomingpigeon', value=ta.CDLHOMINGPIGEON(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlidentical3crows':
            endf.insert(0, column='cdlidentical3crows', value=ta.CDLIDENTICAL3CROWS(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlinneck':
            endf.insert(0, column='cdlinneck', value=ta.CDLINNECK(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlinvertedhammer':
            endf.insert(0, column='cdlinvertedhammer', value=ta.CDLINVERTEDHAMMER(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlkicking':
            endf.insert(0, column='cdlkicking', value=ta.CDLKICKING(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlkickingbylength':
            endf.insert(0, column='cdlkickingbylength', value=ta.CDLKICKINGBYLENGTH(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlladderbottom':
            endf.insert(0, column='cdlladderbottom', value=ta.CDLLADDERBOTTOM(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdllongleggeddoji':
            endf.insert(0, column='cdllongleggeddoji', value=ta.CDLLONGLEGGEDDOJI(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdllongline':
            endf.insert(0, column='cdllongline', value=ta.CDLLONGLINE(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlmarubozu':
            endf.insert(0, column='cdlmarubozu', value=ta.CDLMARUBOZU(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlmatchinglow':
            endf.insert(0, column='cdlmatchinglow', value=ta.CDLMATCHINGLOW(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlmathold':
            endf.insert(0, column='cdlmathold', value=ta.CDLMATHOLD(endf['Open'], endf['High'], endf['Low'], endf['Close'], penetration=0))
            return endf
        if enrich == 'cdlmorningdojistar':
            endf.insert(0, column='cdlmorningdojistar', value=ta.CDLMORNINGDOJISTAR(endf['Open'], endf['High'], endf['Low'], endf['Close'], penetration=0))
            return endf
        if enrich == 'cdlmorningstar':
            endf.insert(0, column='cdlmorningstar', value=ta.CDLMORNINGSTAR(endf['Open'], endf['High'], endf['Low'], endf['Close'], penetration=0))
            return endf
        if enrich == 'cdlonneck':
            endf.insert(0, column='cdlonneck', value=ta.CDLONNECK(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlpiercing':
            endf.insert(0, column='cdlpiercing', value=ta.CDLPIERCING(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlrickshawman':
            endf.insert(0, column='cdlrickshawman', value=ta.CDLRICKSHAWMAN(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlrisefall3methods':
            endf.insert(0, column='cdlrisefall3methods', value=ta.CDLRISEFALL3METHODS(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlseparatinglines':
            endf.insert(0, column='cdlseparatinglines', value=ta.CDLSEPARATINGLINES(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlshootingstar':
            endf.insert(0, column='cdlshootingstar', value=ta.CDLSHOOTINGSTAR(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlshortline':
            endf.insert(0, column='cdlshortline', value=ta.CDLSHORTLINE(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlspinningtop':
            endf.insert(0, column='cdlspinningtop', value=ta.CDLSPINNINGTOP(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlstalledpattern':
            endf.insert(0, column='cdlstalledpattern', value=ta.CDLSTALLEDPATTERN(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlsticksandwich':
            endf.insert(0, column='cdlsticksandwich', value=ta.CDLSTICKSANDWICH(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdltakuri':
            endf.insert(0, column='cdltakuri', value=ta.CDLTAKURI(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdltasukigap':
            endf.insert(0, column='cdltasukigap', value=ta.CDLTASUKIGAP(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlthrusting':
            endf.insert(0, column='cdlthrusting', value=ta.CDLTHRUSTING(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdltristar':
            endf.insert(0, column='cdltristar', value=ta.CDLTRISTAR(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlunique3river':
            endf.insert(0, column='cdlunique3river', value=ta.CDLUNIQUE3RIVER(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlupsidegap2crows':
            endf.insert(0, column='cdlupsidegap2crows', value=ta.CDLUPSIDEGAP2CROWS(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'cdlxsidegap3methods':
            endf.insert(0, column='cdlxsidegap3methods', value=ta.CDLXSIDEGAP3METHODS(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf

        # Price
        if enrich == 'avgprice':
            endf.insert(0, column='avgprice', value=ta.AVGPRICE(endf['Open'], endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'medprice':
            endf.insert(0, column='medprice', value=ta.MEDPRICE(endf['High'], endf['Low']))
            return endf
        if enrich == 'typprice':
            endf.insert(0, column='typprice', value=ta.TYPPRICE(endf['High'], endf['Low'], endf['Close']))
            return endf
        if enrich == 'wclprice':
            endf.insert(0, column='wclprice', value=ta.WCLPRICE(endf['High'], endf['Low'], endf['Close']))
            return endf

        # Stats
        if enrich == 'beta':
            endf.insert(0, column='beta', value=ta.BETA(endf['High'], endf['Low'], timeperiod=5))
            return endf
        if enrich == 'correl':
            endf.insert(0, column='correl', value=ta.CORREL(endf['High'], endf['Low'], timeperiod=30))
            return endf
        if enrich == 'linearreg':
            endf.insert(0, column='linearreg', value=ta.LINEARREG(endf['Close'], timeperiod=14))
            return endf
        if enrich == 'linearreg_angle':
            endf.insert(0, column='linearreg_angle', value=ta.LINEARREG_ANGLE(endf['Close'], timeperiod=14))
            return endf
        if enrich == 'linearreg_intercept':
            endf.insert(0, column='linearreg_intercept', value=ta.LINEARREG_INTERCEPT(endf['Close'], timeperiod=14))
            return endf
        if enrich == 'linearreg_slope':
            endf.insert(0, column='linearreg_slope', value=ta.LINEARREG_SLOPE(endf['Close'], timeperiod=14))
            return endf
        if enrich == 'stddev':
            endf.insert(0, column='stddev', value=ta.STDDEV(endf['Close'], timeperiod=5, nbdev=1))
            return endf
        if enrich == 'tsf':
            endf.insert(0, column='tsf', value=ta.TSF(endf['Close'], timeperiod=14))
            return endf
        if enrich == 'var':
            endf.insert(0, column='var', value=ta.VAR(endf['Close'], timeperiod=5, nbdev=1))
            return endf
Exemple #24
0
 def atrStoploss(self):
     atrPeriod = self.paraDict['atrPeriod']
     atr = ta.ATR(self.high, self.low, self.close, atrPeriod)
     return atr
def SuperTrend(data, period, multiplier, columns=['h', 'l', 'o', 'c']):
    high_i = columns[0]
    low_i = columns[1]
    open_i = columns[2]
    close_i = columns[3]

    data['MP'] = (data[high_i] + data[low_i]) / 2
    data['ATR'] = talib.ATR(data[high_i],
                            data[low_i],
                            data[close_i].shift(1),
                            timeperiod=period)
    data['ATR'] = data['ATR'].fillna(0)

    data['BASIC UPPERBAND'] = data['MP'] + multiplier * data['ATR']
    data['BASIC LOWERBAND'] = data['MP'] - multiplier * data['ATR']
    data['FINAL UPPERBAND'] = np.float64()
    data['FINAL LOWERBAND'] = np.float64()

    for i in range(0, len(data)):
        if i < period:
            data.iloc[i, data.columns.get_loc('FINAL UPPERBAND')] = 0
            data.iloc[i, data.columns.get_loc('FINAL LOWERBAND')] = 0
        else:
            data.iloc[i, data.columns.get_loc('FINAL UPPERBAND')] = np.where(
                np.logical_or(
                    data['BASIC UPPERBAND'].iloc[i] <
                    data['FINAL UPPERBAND'].iloc[i - 1],
                    data[close_i].iloc[i - 1] >
                    data['FINAL UPPERBAND'].iloc[i - 1]),
                data['BASIC UPPERBAND'].iloc[i],
                data['FINAL UPPERBAND'].iloc[i - 1])

            data.iloc[i, data.columns.get_loc('FINAL LOWERBAND')] = np.where(
                np.logical_or(
                    data['BASIC LOWERBAND'].iloc[i] >
                    data['FINAL LOWERBAND'].iloc[i - 1],
                    data[close_i].iloc[i - 1] <
                    data['FINAL LOWERBAND'].iloc[i - 1]),
                data['BASIC LOWERBAND'].iloc[i],
                data['FINAL LOWERBAND'].iloc[i - 1])
    # endfor

    data['SuperTrend'] = 0

    for i in range(0, len(data)):
        if i < period:
            data.iloc[i, data.columns.get_loc('SuperTrend')] = 0
        else:
            conditions = [np.logical_and(data['SuperTrend'].iloc[i-1] == data['FINAL UPPERBAND'].iloc[i-1],  \
                 data[close_i].iloc[i] < data['FINAL UPPERBAND'].iloc[i])
                 , np.logical_and(data['SuperTrend'].iloc[i-1] == data['FINAL UPPERBAND'].iloc[i-1], data[close_i].iloc[i] > data['FINAL UPPERBAND'].iloc[i])
                 , np.logical_and(data['SuperTrend'].iloc[i-1] == data['FINAL LOWERBAND'].iloc[i-1], data[close_i].iloc[i] > data['FINAL LOWERBAND'].iloc[i])
                 , np.logical_and(data['SuperTrend'].iloc[i-1] == data['FINAL LOWERBAND'].iloc[i-1], data[close_i].iloc[i] < data['FINAL LOWERBAND'].iloc[i])]
            choices = [
                data['FINAL UPPERBAND'].iloc[i],
                data['FINAL LOWERBAND'].iloc[i],
                data['FINAL LOWERBAND'].iloc[i],
                data['FINAL UPPERBAND'].iloc[i]
            ]
            data.iloc[i, data.columns.get_loc('SuperTrend')] = np.select(
                conditions, choices)
    # endfor

    # Drop all zeros
    data = data.drop(data[(data.SuperTrend == 0.0)].index)
    return data
Exemple #26
0
    xdata = df.drop(columns=[
        'Unnamed: 0', 'Target2', 'Date', 'Close', 'Open', 'High', 'Low',
        'Volume', 'Adj Close'
    ],
                    axis=1)
    ydata = df['Target2']
    high, low, close, open = df['High'], df['Low'], df['Close'], df['Open']

    columns = [
        'sma', 'ema', 'atr', 'adx', 'cci', 'roc', 'rsi', 'willr', 'fastk',
        'fastd'
    ]

    sma = talib.SMA(close, timeperiod=timestep)
    ema = talib.EMA(close, timeperiod=timestep)
    atr = talib.ATR(high, low, close, timeperiod=timestep)
    adx = talib.ADX(high, low, close, timeperiod=timestep)
    cci = talib.CCI(high, low, close, timeperiod=timestep)
    roc = talib.ROC(close, timeperiod=timestep)
    rsi = talib.RSI(close, timeperiod=timestep)
    willr = talib.WILLR(high, low, close, timeperiod=timestep)
    fastk, fastd = talib.STOCHF(high,
                                low,
                                close,
                                fastk_period=timestep,
                                fastd_period=3,
                                fastd_matype=0)

    xdata['sma'] = sma
    xdata['ema'] = ema
    xdata['atr'] = atr
Exemple #27
0
            for k in range(len(ticker_data)):
                open_list.append(ticker_data[k].o)
                high_list.append(ticker_data[k].h)
                low_list.append(ticker_data[k].l)
                close_list.append(ticker_data[k].c)
                volume_list.append(ticker_data[k].v)

            ohlc_df['open'] = open_list
            ohlc_df['high'] = high_list
            ohlc_df['low'] = low_list
            ohlc_df['close'] = close_list
            ohlc_df['volume'] = volume_list
            ohlc_df['avg_vol'] = ohlc_df['volume'].rolling(window=14).mean()
            ohlc_df['atr'] = ta.ATR(ohlc_df['high'],
                                    ohlc_df['low'],
                                    ohlc_df['close'],
                                    timeperiod=14)
            ohlc_df['atr_pct'] = ohlc_df['atr'] / ohlc_df['close']
            ohlc_df['CDL2CROWS'] = ta.CDL2CROWS(ohlc_df['open'],
                                                ohlc_df['high'],
                                                ohlc_df['low'],
                                                ohlc_df['close'])
            ohlc_df['CDL3BLACKCROWS'] = ta.CDL3BLACKCROWS(
                ohlc_df['open'], ohlc_df['high'], ohlc_df['low'],
                ohlc_df['close'])
            ohlc_df['CDL3INSIDE'] = ta.CDL3INSIDE(ohlc_df['open'],
                                                  ohlc_df['high'],
                                                  ohlc_df['low'],
                                                  ohlc_df['close'])
            ohlc_df['CDL3LINESTRIKE'] = ta.CDL3LINESTRIKE(
                ohlc_df['open'], ohlc_df['high'], ohlc_df['low'],
Exemple #28
0
for sym in symbol_list:
    # 查询历史行情
    df_data = history(symbol=sym,
                      frequency='1d',
                      start_time=start_year,
                      end_time=end_year,
                      fields='eob,open,high,low,close',
                      adjust=1,
                      df=True)
    df_data.rename(columns={'eob': 'datetime'}, inplace=True)
    # df_data = get_stk(sym, start_year, end_year)
    # df_data = get_k(sym, 60, 0, start_year, end_year)
    if len(df_data) == 0:
        continue
    df_data.loc[:, 'atr'] = ta.ATR(df_data.high,
                                   df_data.low,
                                   df_data.close,
                                   timeperiod=atr_n)
    df_data.loc[:, 'chg'] = (df_data['close'] - df_data['close'].shift(1)
                             ) / df_data['close'].shift(1)
    # df_data.loc[:,'ma5'] = df_data.close.rolling(5,min_periods=0).mean()
    # df_data.loc[:,'ma21'] = df_data.close.rolling(21,min_periods=0).mean()

    # cci_n= [15, 30, 60]
    # cci_m = pd.DataFrame()
    # for n in cci_n:
    #     cci_m = pd.concat([cci_m, ta_cci(n,df_data)], axis=1)
    # df_data =  pd.concat([df_data, cci_m], axis=1)

    # for N in [32]:#range(4,41):
    N = 20
    M = 2 * N
def ohlc_gen_compute(data, from1):
    ### Check to make sure they are even number
    if (data.shape[0] % 2) == 1:
        data = data.iloc[1:]
    #
    data["Date"] = data.index
    data["Week"] = data["Date"].dt.week
    data["Year"] = data["Date"].dt.year
    #Create weekly data from daily data
    data_weekly = data[data.index >= from1].groupby(["Year", "Week"]).agg({
        "Date":
        "first",
        'Open':
        'first',
        'High':
        'max',
        'Low':
        'min',
        'Close':
        'last',
        'Volume':
        'sum'
    })
    #Add TA in daily and weekly data
    data_weekly["Week"] = data_weekly.index
    data_weekly.index = data_weekly["Date"]
    #
    dayofyear = data['Date'].dt.dayofyear
    #
    # new column introduced by Kevin Davey
    data['prevClose'] = data['Close'].shift(1)
    data['prevprevClose'] = data['Close'].shift(2)
    # 0 = Monday, 6 = Sunday
    data['dayofweek'] = data.index.to_series().dt.dayofweek
    #
    data['ATR21'] = TA.ATR(data['High'],
                           data['Low'],
                           data['Close'],
                           timeperiod=21)
    data['prevATR21'] = data['ATR21'].shift(1)
    data['trailing_ATR'] = data['prevClose'] - 3 * data['prevATR21']
    #
    data['SAR'] = TA.SAR(data['High'], data['Low'])
    data['ADX'] = TA.ADX(data['High'], data['Low'], data['Close'])
    data['prevADX'] = data['ADX'].shift(1)
    data['ADX-trend'] = data['ADX'] - data['ADX'].shift(1)  # today - previous
    #
    data['firstday'] = (dayofyear <
                        dayofyear.shift(1)) | (dayofyear.shift(1).isnull())
    #
    data["EMA9"] = TA.EMA(data["Close"], 9)
    data["EMA19"] = TA.EMA(data["Close"], 19)
    data["EMA50"] = TA.EMA(data["Close"], 50)
    #
    # Gruppy line short term
    data["EMA3"] = TA.EMA(data["Close"], 3)
    data["EMA5"] = TA.EMA(data["Close"], 5)
    data["EMA8"] = TA.EMA(data["Close"], 8)
    data["EMA10"] = TA.EMA(data["Close"], 10)
    data["EMA12"] = TA.EMA(data["Close"], 12)
    data["EMA15"] = TA.EMA(data["Close"], 15)
    #
    # Gruppy line long term
    data["EMA30"] = TA.EMA(data["Close"], 30)
    data["EMA35"] = TA.EMA(data["Close"], 35)
    data["EMA40"] = TA.EMA(data["Close"], 40)
    data["EMA45"] = TA.EMA(data["Close"], 45)
    data["EMA50"] = TA.EMA(data["Close"], 50)
    data["EMA60"] = TA.EMA(data["Close"], 60)
    data['guppy_long_width'] = data["EMA60"] - data["EMA30"]
    data['guppy_long_width'] = data['guppy_long_width'].abs()
    data['guppy_30over60'] = data["EMA30"] > data["EMA60"]
    #
    ST_ema = ['EMA5', 'EMA8', 'EMA10', 'EMA12', 'EMA15']
    LT_ema = ['EMA35', 'EMA40', 'EMA45', 'EMA50', 'EMA60']
    data['guppy_ShortTermTrend'] = 0
    # condition = (data['EMA3'] > data[ST_ema].max(axis=1)) & data['EMA3'].notna() & data['EMA15'].notna()
    condition = (data['EMA3']>data['EMA5']) &\
                (data['EMA5']>data['EMA8']) &\
                (data['EMA8']>data['EMA10']) &\
                (data['EMA10']>data['EMA12']) &\
                (data['EMA12']>data['EMA15'])
    data.loc[condition, 'guppy_ShortTermTrend'] = 1
    condition = (data['EMA3']<data['EMA5']) &\
                (data['EMA5']<data['EMA8']) &\
                (data['EMA8']<data['EMA10']) &\
                (data['EMA10']<data['EMA12']) &\
                (data['EMA12']<data['EMA15'])
    # condition = (data['EMA3'] < data[ST_ema].min(axis=1))  & data['EMA3'].notna() & data['EMA15'].notna()
    data.loc[condition, 'guppy_ShortTermTrend'] = -1
    data['guppy_LongTermTrend'] = 0
    # condition = (data['EMA30'] > data[LT_ema].max(axis=1))  & data['EMA30'].notna() & data['EMA60'].notna()
    condition = (data['EMA30']>data['EMA35']) &\
                (data['EMA35']>data['EMA40']) &\
                (data['EMA40']>data['EMA45']) &\
                (data['EMA45']>data['EMA50']) &\
                (data['EMA50']>data['EMA60'])
    data.loc[condition, 'guppy_LongTermTrend'] = 1
    condition = (data['EMA30']<data['EMA35']) &\
                (data['EMA35']<data['EMA40']) &\
                (data['EMA40']<data['EMA45']) &\
                (data['EMA45']<data['EMA50']) &\
                (data['EMA50']<data['EMA60'])
    # condition = (data['EMA30'] < data[LT_ema].min(axis=1)) & data['EMA30'].notna() & data['EMA60'].notna()
    data.loc[condition, 'guppy_LongTermTrend'] = -1
    data['guppy_LongTermTrend_simple'] = 0
    condition = (data['EMA30'] > data['EMA60']
                 ) & data['EMA30'].notna() & data['EMA60'].notna()
    data.loc[condition, 'guppy_LongTermTrend_simple'] = 1
    condition = (data['EMA30'] < data['EMA60']
                 ) & data['EMA30'].notna() & data['EMA60'].notna()
    data.loc[condition, 'guppy_LongTermTrend_simple'] = -1
    #
    data['guppy_LongTermBandWiden'] = False
    #
    window = 200
    chipavg = 'CHIP_AVG_{}'.format(window)
    chipscore = 'CHIP_SCORE_{}'.format(window)
    chipema = "EMA{}".format(window)
    data[chipavg], data[chipscore] = ta_chip(data['High'], data['Low'],
                                             data['Close'], data['Volume'],
                                             window)
    data[chipema] = TA.EMA(data["Close"], window)
    data['CHIP_CRAZY'] = abs(data[chipavg] - data[chipema])
    #
    window = 1000
    chipavg1 = 'CHIP_AVG_{}'.format(window)
    chipscore1 = 'CHIP_SCORE_{}'.format(window)
    data[chipavg1], data[chipscore1] = ta_chip(data['High'], data['Low'],
                                               data['Close'], data['Volume'],
                                               window)
    data['CHIP_TREND'] = data[chipavg] - data[chipavg1]
    #
    guppy_window = 5
    guppy_longterm = data['guppy_LongTermTrend']
    guppy_longterm_up = guppy_longterm.rolling(guppy_window).sum() == (
        guppy_window * 1)
    guppy_longterm_down = guppy_longterm.rolling(guppy_window).sum() == (
        guppy_window * -1)
    #
    for d in guppy_longterm_up[guppy_longterm_up].index:
        prev_longterm = data.loc[:d, 'guppy_LongTermTrend']
        last_diff_date = prev_longterm[prev_longterm != 1].tail(1).index[0]
        first_same_iloc = data.index.get_loc(last_diff_date) + 1
        first_same_loc = data.index[first_same_iloc]
        window_median = data.loc[first_same_loc:d, 'guppy_long_width'].median()
        data.loc[d, 'guppy_LongTermBandWiden'] = data.loc[
            d, 'guppy_long_width'] > window_median
    #
    for d in guppy_longterm_down[guppy_longterm_down].index:
        prev_longterm = data.loc[:d, 'guppy_LongTermTrend']
        last_diff_date = prev_longterm[prev_longterm != -1].tail(1).index[0]
        first_same_iloc = data.index.get_loc(last_diff_date) + 1
        first_same_loc = data.index[first_same_iloc]
        window_median = data.loc[first_same_loc:d, 'guppy_long_width'].median()
        data.loc[d, 'guppy_LongTermBandWiden'] = data.loc[
            d, 'guppy_long_width'] > window_median
    #
    data['slowk'], data['slowd'] = TA.STOCH(data['High'], data['Low'],
                                            data['Close'])
    # data = generic_peak_trough_projection_ampd(data, 'guppy_long_width', long_change)
    #
    data["RSI9"] = TA.RSI(data["Close"], 9)
    data["macd"], data["macdsignal"], data["macdhist"] = TA.MACD(
        data["Close"], fastperiod=12, slowperiod=26, signalperiod=9)
    #
    data["EMA5"] = TA.EMA(data["Close"], 5)
    data["BBupper"], data["BBmid"], data["BBlower"] = TA.BBANDS(data["Close"],
                                                                timeperiod=5,
                                                                nbdevup=2,
                                                                nbdevdn=2,
                                                                matype=0)
    data['RSI9-75'] = data['RSI9'].rolling(200).apply(
        lambda x: np.percentile(x, 75))
    data['RSI9-9'] = TA.EMA(data["RSI9"], 9)
    data['RSI9-19'] = TA.EMA(data["RSI9"], 19)
    data['RSI9-50'] = TA.EMA(data["RSI9"], 50)
    data['obv'] = TA.OBV(data['Close'], data['Volume'])
    data["obv9"] = TA.EMA(data["obv"], 9)
    data["obv19"] = TA.EMA(data["obv"], 19)
    data["obv50"] = TA.EMA(data["obv"], 50)
    data['ADOSC'] = TA.ADOSC(data["High"], data["Low"], data["Close"],
                             data["Volume"])
    data['MFI'] = TA.MFI(data["High"], data["Low"], data["Close"],
                         data["Volume"])
    data["chaikin"] = TA.ADOSC(data['High'],
                               data['Low'],
                               data['Close'],
                               data['Volume'],
                               fastperiod=3,
                               slowperiod=10)
    data["chaikin9"] = TA.EMA(data["chaikin"], 9)
    data["chaikin19"] = TA.EMA(data["chaikin"], 19)
    data["chaikin50"] = TA.EMA(data["chaikin"], 50)
    #
    price_diff = (data['Close'] - data['CHIP_AVG_200']).apply(pos_neg)
    data['Price_CHIP200_10'] = price_diff.rolling(window=10).sum()
    data['Price_CHIP200_20'] = price_diff.rolling(window=20).sum()
    data['guppy_LT_last5'] = data['guppy_LongTermTrend'].rolling(
        window=5).sum()
    #
    data_weekly["EMA9"] = TA.EMA(data_weekly["Close"], 9)
    data_weekly["EMA19"] = TA.EMA(data_weekly["Close"], 19)
    data_weekly["EMA50"] = TA.EMA(data_weekly["Close"], 50)
    #
    data['Date-simple'] = data['Date']
    data["Date"] = data["Date"].apply(mdates.date2num)
    #Construct filtered daily and weekly data for chart generation
    #
    return data
Exemple #30
0
            df['adx'] = adx
            dx = talib.DX(df.high.values, df.low.values, df.close.values, timeperiod=14)
            df['dx'] = dx
            cci = talib.CCI(df.high.values, df.low.values, df.close.values, timeperiod=14)
            df['cci'] = cci
            upperband, middleband, lowerband = talib.BBANDS(df.close.values, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)
            df['upperband'] = upperband
            df['middleband'] = middleband
            df['lowerband'] = lowerband
            sar = talib.SAR(df.high.values, df.low.values, acceleration=0, maximum=0)
            df['sar'] = sar
            ad = talib.ADOSC(df.high.values, df.low.values, df.close.values, df.volume.values, fastperiod=3, slowperiod=10)
            df['ad'] = ad
            obv = talib.OBV(df.close.values, df.volume.values)
            df['obv'] = obv
            atr = talib.ATR(df.high.values, df.low.values, df.close.values, timeperiod=14)
            df['atr'] = atr
            df['ma5'] = talib.MA(df.close.values, timeperiod=5)
            df['ma10'] = talib.MA(df.close.values, timeperiod=10)
            df['ma30'] = talib.MA(df.close.values, timeperiod=30)
            df['ma60'] = talib.MA(df.close.values, timeperiod=60)
            df['ma120'] = talib.MA(df.close.values, timeperiod=120)
=======
            try:
                macd, macdsignal, macdhist = talib.MACD(df.close.values, fastperiod=12, slowperiod=26, signalperiod=9)
                df['macd'] = macd
                df['macdsignal'] = macdsignal
                df['macdhist'] = macdhist
                k, d = talib.STOCH(df.high.values, df.low.values, df.close.values, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0)
                df['k'] = k
                df['d'] = d