Esempio n. 1
0
def market_in(context, bar_dict, security):
    hist = history_bars(security, context.period, '1d', ['high','low','close'])
    
    # 按照context.long_period计算每一天对应的
ATR(平均真实振幅)值,然后取最后一天的值返回
    N_long = ATR(hist['high'], hist['low'], hist['close'], timeperiod=context.long_period)[-1]
    # 按照context.short_period计算每一天对应的
ATR(平均真实振幅)值,然后取最后一天的值返回
    N_short = ATR(hist['high'], hist['low'], hist['close'], timeperiod=context.short_period)[-1]
    
    close = hist['close']
    # print('*************************************************************')
    # macd短期均线 
macdsignal是长期均线
    # 短穿长 为金叉
    macd,macdsignal,macdhist = talib.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9)
    # print('*************************************************************')
    
    # 买入手数
    amount_long = int(context.portfolio.cash*0.001/N_long)
    amount_short = int(context.portfolio.cash*0.001/N_short)
    # 最新价大于前20天的最高价
    if macd[-1] > macdsignal[-1] and amount_long >0 and bar_dict[security].last>max(hist['high'][-20:-1]):
        buy_open(security, amount_long)
        print("buy_open")
    # 最新价小于前40天的最高价
    if macd[-1] < macdsignal[-1] and amount_short >0 and bar_dict[security].last<min(hist['low'][-40:-1]):
        sell_open(security, amount_short)
        print("sell_open")
Esempio n. 2
0
    def calcAtr(self, tempDf, longOrShort, atrPeriod: int = 14):
        warnings.filterwarnings("ignore")
        tempDf2 = self.histTrades.loc[str(tempDf.index[-1]
                                          ):str(tempDf.index[-1] +
                                                datetime.timedelta(minutes=5))]

        try:
            if longOrShort == 'l':
                mask = (tempDf2.index > str(tempDf.index[-1])) & (
                    tempDf2.index <= str(tempDf2[tempDf2['price'].ge(
                        tempDf['close'][-1])].index[id]))
            else:
                mask = (tempDf2.index > str(tempDf.index[-1])) & (
                    tempDf2.index <= str(tempDf2[tempDf2['price'].le(
                        tempDf['close'][-1])].index[id]))

            atrRow = tempDf2.loc[mask].groupby(pd.Grouper(freq='5T')).agg({
                'price': ['first', max, min, 'last'],
                'amount':
                sum
            })  # TODO: Change Timeframe
            atrRow.columns = ['open', 'high', 'low', 'close', 'volume']

            atrDf = pd.concat([tempDf[:-1].copy(), atrRow])

        except IndexError:
            atrDf = tempDf.copy()

        atr = ATR(atrDf['high'], atrDf['low'], atrDf['close'], atrPeriod)

        return atr
Esempio n. 3
0
    def test_talib_ATR(self):
        #
        # code_name = ('300623', '捷捷微电')
        # code_name = ('600145', '*ST新亿')
        # code_name = ('601700', '风范股份')
        # code_name = ('000725', '京东方A')
        # code_name = ('002157', '正邦科技')
        code_name = ('300663', '科蓝软件')
        end = '2020-12-30'

        data = utils.read_data(code_name)
        print(data.head())
        result = enter.check_volume(code_name, data, end_date=end)
        print("\nlow atr check {0}'s result: {1}".format(code_name, result))

        rolling_window = 21
        moving_average = 20

        average_true_range = ATR(data.high.values[-rolling_window:],
                                 data.low.values[-rolling_window:],
                                 data.close.values[-rolling_window:],
                                 timeperiod=moving_average)
        print("*" * 50)
        print(data['high'].values)
        print("*" * 50)
        print(average_true_range)
        print("*" * 10)
Esempio n. 4
0
    def _calc_indicator(self, OHLCV_input):
        """
        Calculates the ATR - Average True Range using a wrapper for the TA-lib

        Args:
            :param OHLCV_input:  the dataframe with the Open, High, Low, Close and Volume values
            :type OHLCV_input: pandas DataFrame

        Returns:
            DataFrame with the indicators values.
        """
        try:
            high = OHLCV_input['high'].values[:, 0]
        except IndexError:
            high = OHLCV_input['high'].values

        try:
            low = OHLCV_input['low'].values[:, 0]
        except IndexError:
            low = OHLCV_input['low'].values

        try:
            close = OHLCV_input['close'].values[:, 0]
        except IndexError:
            close = OHLCV_input['close'].values

        output = DataFrame(ATR(high, low, close, self.__timeperiod))
        output.columns = ['ATR%d' % self.__timeperiod]
        return output
Esempio n. 5
0
def market_add(context, bar_dict, security):
    hist = history_bars(security, context.period, '1d', ['high','low','close'])
    N_long = ATR(hist['high'], hist['low'], hist['close'], timeperiod=context.long_period)[-1]
    N_short = ATR(hist['high'], hist['low'], hist['close'], timeperiod=context.short_period)[-1]
    close = hist['close']
    position = context.portfolio.positions[security]
    macd,macdsignal,macdhist = talib.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9)
    amount_long = int(context.portfolio.cash*0.001/N_long)
    amount_short = int(context.portfolio.cash*0.001/N_short)
    if amount_long>0 and macd[-1] > macdsignal[-1] and bar_dict[security].last > (position.buy_avg_holding_price + 2*N_long):
        buy_open(security, amount_long)
        print("buy_add")
            
    if amount_short>0 and macd[-1] < macdsignal[-1] and bar_dict[security].last < (position.sell_avg_holding_price - 2*N_short):
        sell_open(security, amount_short)
        print("sell_add")
Esempio n. 6
0
def WADDAH_ATTAR_EXPLOSION(close, high, low, sensitive = 150, fast_period=20, slow_period = 40, channel_period = 20, channel_mult = 2, dead_zone=30):
    
    from talib import MACD 
    from talib import BBANDS 
    from talib import ATR 
    from talib import WMA 
    macd, macdsignal, macdhist = MACD(close, fastperiod=fast_period, slowperiod=slow_period, signalperiod=9)
    upperband, middleband, lowerband = BBANDS(close, timeperiod=channel_period, nbdevup=channel_mult, nbdevdn=channel_mult, matype=0)

    ind_trend1 = np.full(len(close), np.nan)
    ind_itrend1 = np.full(len(close), np.nan)
    ind_explo1 = np.full(len(close), np.nan)
    tr = WMA(ATR(high, low, close, 20),3)
    ind_dead = tr*dead_zone / 10
    for i in range(0,len(close)):
        if(i<2):
            continue
        trend1 = (macd[i] - macd[i-1]) * sensitive;
        trend2 = (macd[i-1] - macd[i-2]) * sensitive;
        explo1 = (upperband[i] - lowerband[i])
        #explo2 = (upperband[i-1] - lowerband[i-1])
        
        if(trend1>=0):
            ind_trend1[i]=trend1
            ind_itrend1[i]=0
        if(trend1<0):
            ind_trend1[i]=0
            ind_itrend1[i]=(trend1*-1)
        ind_explo1[i] = explo1
        #print(str(i)+"\t "+str(close[i])+"\t "+str(close[i])+"\t "+str(ind_trend1[i])+"\t"+str(ind_itrend1[i]))
    return ind_trend1, ind_itrend1, ind_explo1, ind_dead
Esempio n. 7
0
def compute_average_true_ranges(context, data):
    # data is not used
    """
    Compute average true ranges, or N.
    """
    if context.is_timed:
        start_time = time()

    rolling_window = 21
    moving_average = 20

    for sym in context.tradable_symbols:
        context.average_true_range[sym] = ATR(
            context.prices.loc[sym, 'high'][-rolling_window:],
            context.prices.loc[sym, 'low'][-rolling_window:],
            context.prices.loc[sym, 'close'][-rolling_window:],
            timeperiod=moving_average)[-1]

    if context.is_test:
        assert (len(context.average_true_range) > 0)

    if context.is_timed:
        time_taken = (time() - start_time) * 1000
        log.debug('Executed in %f ms.' % time_taken)
        assert (time_taken < 1024)
Esempio n. 8
0
def stop_loss(context, bar_dict, security):
    hist = history_bars(security, context.period, '1d', ['high','low','close'])
    N_long = ATR(hist['high'], hist['low'], hist['close'], timeperiod=context.long_period)[-1]
    N_short = ATR(hist['high'], hist['low'], hist['close'], timeperiod=context.short_period)[-1]
    position = context.portfolio.positions[security]

    # buy_avg_holding_price	float	多头持仓均价
    if position.buy_quantity >0 and bar_dict[security].last < (position.buy_avg_holding_price - 0.5 *N_long):
        # 多单清仓
        sell_close(security,position.buy_quantity)
        print("long_stop_loss")
    
    # sell_avg_holding_price	float	空头持仓均价
    if position.sell_quantity >0 and bar_dict[security].last > (position.sell_avg_holding_price + 0.5*N_short):
        # 空单清仓
        buy_close(security,position.sell_quantity)
        print("short_stop_loss")
Esempio n. 9
0
def atr(high,
        low,
        close,
        length=None,
        mamode=None,
        talib=None,
        drift=None,
        offset=None,
        **kwargs):
    """Indicator: Average True Range (ATR)"""
    # Validate arguments
    length = int(length) if length and length > 0 else 14
    mamode = mamode.lower() if mamode and isinstance(mamode, str) else "rma"
    high = verify_series(high, length)
    low = verify_series(low, length)
    close = verify_series(close, length)
    drift = get_drift(drift)
    offset = get_offset(offset)
    mode_tal = bool(talib) if isinstance(talib, bool) else True

    if high is None or low is None or close is None: return

    # Calculate Result
    if Imports["talib"] and mode_tal:
        from talib import ATR
        atr = ATR(high, low, close, length)
    else:
        tr = true_range(high=high, low=low, close=close, drift=drift)
        atr = ma(mamode, tr, length=length)

    percentage = kwargs.pop("percent", False)
    if percentage:
        atr *= 100 / close

    # Offset
    if offset != 0:
        atr = atr.shift(offset)

    # Handle fills
    if "fillna" in kwargs:
        atr.fillna(kwargs["fillna"], inplace=True)
    if "fill_method" in kwargs:
        atr.fillna(method=kwargs["fill_method"], inplace=True)

    # Name and Categorize it
    atr.name = f"ATR{mamode[0]}_{length}{'p' if percentage else ''}"
    atr.category = "volatility"

    return atr
Esempio n. 10
0
def ATRcalc(df):
    df = df.dropna()
    ##d. ATR
    priceaction = df.head(15)
    pricehigh = priceaction['high'].values
    pricelow = priceaction['low'].values
    priceclose = priceaction['close'].values
    atr = ATR(pricehigh, pricelow, priceclose, timeperiod=14)
    # print("ATR\n", atr[-1])
    return atr[-1]
def sell_signal(context, data):
    cash_freed = 0.0
    s = ""
    context.stop = {}

    for stock in context.portfolio.positions:
        position = context.portfolio.positions[stock]
        cash_worth = position.amount * position.last_sale_price
        # anything not in the pool of allowed stocks is immediately sold

        cost_basis = position.cost_basis
        highs = data.history(stock, 'high', 25, '1d').ffill().bfill()
        lows = data.history(stock, 'low', 25, '1d').ffill().bfill()
        closes = data.history(stock, 'close', 25, '1d').ffill().bfill()
        #front fill the values vs bfill() which back fills the values

        current_price = data.current(stock, 'price')
        if np.all(np.isnan(highs)):
            continue

        if np.all(np.isnan(lows)):
            continue

        if np.all(np.isnan(closes)):
            continue
#             atr_stop=0.90
        atr_stop = ATR(highs, lows, closes, timeperiod=10)[-1] * 2
        # if the stock is in the context stop then it is the previous price
        if stock in context.stop:
            stop = context.stop[stock]
# if it is not in context.stop then we will calculate the new stop price

        else:
            stop = cost_basis - atr_stop

# move up the stock if the current price is still greater than the stop
        if (current_price) >= stop:
            stop = current_price - atr_stop
            context.stop[stock] = stop


# if the stop price is higher then sell the position
        elif (current_price) < stop:
            position = context.portfolio.positions[sid]
            cash_worth = position.amount * position.last_sale_price
            # anything not in the pool of allowed stocks is immediately sold
            s = s + "%s, " % stock.symbol
            if get_open_orders(stock):
                continue
            if data.can_trade(stock):
                order_target_percent(stock, 0)
                # log.info("Sell: Hit Stop " +str(stock))
                cash_freed = cash_freed + cash_worth
    log.info(s)
    return cash_freed
Esempio n. 12
0
def compute_average_true_ranges(context, data):
    """
    Compute ATR, aka N
    """

    rolling_window = context.strat_one_breakout+1
    moving_average = context.strat_one_breakout

    for sym in context.tradable_symbols:
        context.MT[sym]['ATR'] = ATR(
            context.prices.loc[sym, 'high'][-rolling_window:],
            context.prices.loc[sym, 'low'][-rolling_window:],
            context.prices.loc[sym, 'close'][-rolling_window:],
            timeperiod=moving_average
        )[-1]
Esempio n. 13
0
def handle_data_csv(context):
    long_range_slopes = []
    try:
        liq = context.performance.get_latest_performance()['portfolio_value']
    except:
        liq = 0
    new_pos_sizes = []
    isbull = []
    symbols = context.data.items
    for symbol in symbols:
        hist = get_history(context, symbol, '500D', 'four')
        MA = mean(hist)
        isbull.append(get_current_price(context, symbol) > MA)
        try:
            lr = stats.linregress(range(len(hist)), hist)
            atr = ATR(asarray(get_history(context, symbol, '500D', 'two')),
                      asarray(get_history(context, symbol, '500D', 'three')),
                      asarray(get_history(context, symbol, '500D', 'four')),
                      context.atr_lkbk)[-1]
            new_pos_sizes.append(floor(liq * context.risk_factor / atr))
            long_range_slopes.append(lr[0] * abs(lr[2]) *
                                     context.long_range_slope_lkbk)
        except:
            new_pos_sizes.append(np.nan)
            long_range_slopes.append(np.nan)
            print traceback.format_exc()

    tradable_symbols = argsort(long_range_slopes[::-1])[:context.max_items]
    for i, symbol in enumerate(symbols):
        if isnan(new_pos_sizes[i]) or isnan(long_range_slopes[i]): continue
        if symbol in context.portfolio.positions:
            order_size = new_pos_sizes[i] - sum(
                context.portfolio.positions[symbol])
            if isbull[i] and (i in tradable_symbols) and order_size:
                order(context, symbol, order_size)
            elif not isbull[i] and sum(context.portfolio.positions[symbol]):
                order(context, symbol,
                      -sum(context.portfolio.positions[symbol]))
        else:
            order_size = new_pos_sizes[i]
            if isbull[i] and (i in tradable_symbols) and order_size:
                order(context, symbol, order_size)
Esempio n. 14
0
def compute_average_true_ranges(context):
    """
    Compute average true ranges, or N.
    """
    if context.is_debug:
        start_time = time()

    rolling_window = 21
    moving_average = 20

    for market in context.prices.items:
        context.average_true_range[market] = ATR(
            context.prices[market].high[-rolling_window:],
            context.prices[market].low[-rolling_window:],
            context.prices[market].close[-rolling_window:],
            timeperiod=moving_average)[-1]

    if context.is_test:
        assert (len(context.average_true_range) > 0)

    if context.is_debug:
        time_taken = (time() - start_time) * 1000
        log.debug('Executed in %f ms.' % time_taken)
        assert (time_taken < 1024)
                          2).shift(26)
 high_52 = DATA['h_1'].rolling(window=52).max()
 low_52 = DATA['l_1'].rolling(window=52).min()
 DATA['senkou_span_b'] = ((high_52 + low_52) / 2).shift(26)
 DATA['chikou_span'] = DATA['c_1'].shift(-26)  # sometimes -22
 DATA.loc[DATA.tenkan_sen > DATA.kijun_sen, 'cross'] = 1
 DATA.loc[DATA.tenkan_sen < DATA.kijun_sen, 'cross'] = -1
 DATA.loc[DATA.tenkan_sen == DATA.kijun_sen, 'cross'] = 0
 DATA['cross_2'] = DATA.cross.shift(2)
 DATA['sygnal'] = 0
 DATA.loc[DATA.senkou_span_a > DATA.senkou_span_b, 'kumo'] = 1
 DATA.loc[DATA.senkou_span_a < DATA.senkou_span_b, 'kumo'] = -1
 DATA.loc[DATA.senkou_span_a == DATA.senkou_span_b, 'kumo'] = 0
 DATA['kumo26'] = DATA.kumo.shift(-26)
 DATA['c26'] = DATA.c_1.shift(26)
 DATA['atr26'] = ATR(DATA.c_1, DATA.l_1, DATA.h_1, timeperiod=26)
 DATA['atr_sl'] = DATA.atr26 * ATR_RATIO
 data = DATA.tail(SAMPLES)
 '''
 kolumny = ['close', 'kijun_sen', 'tenkan_sen', 'senkou_span_a',
             'senkou_span_b', 'chikou_span']#, 'sygnal']
 '''
 data['signal'] = data.apply(ALGO[0], axis=1)
 man_close_date = get_prev_workday_datestring()
 if TRANS.in_transaction:
     try:
         TRANS.close_transaction(data['close'].loc[man_close_date],
                                 date_close=man_close_date,
                                 be_verbose=BE_VERBOSE)
     except KeyError:
         print('przy tej spolce {} KeyError'.format(STOCK))
Esempio n. 16
0
def compute_atr(stock_data):
    df = ATR(stock_data.high, stock_data.low, stock_data.close, timeperiod=14)
    return df.sub(df.mean()).div(df.std())
Esempio n. 17
0
def getTechnicalInd(data, window=10):
    close = data['Close']
    high = data['High']
    low = data['Low']
    volume = data['Volume']
    #madev = roc = willr=rsi=apo=atr=obv=adosc=slowk=fastk=slowd=fastd=vpos=vneg={}
    window = 10
    for i in range(0, window):

        # momentum indicators
        # rate of change: (price/prevPrice - 1)*100
        data["roc{0}".format(i)] = ROC(close.shift(i), timeperiod=10)
        # williams oscillator
        data["willr{0}".format(i)] = WILLR(high.shift(i),
                                           low.shift(i),
                                           close.shift(i),
                                           timeperiod=14)

        # relative strength index
        data["rsi{0}".format(i)] = RSI(close.shift(i), timeperiod=14)

        # absolute price oscillator: slowMA(price) - fastMA(price)
        data["apo{0}".format(i)] = APO(close.shift(i),
                                       fastperiod=12,
                                       slowperiod=26,
                                       matype=0)
        # volatility indicator

        data["atr{0}".format(i)] = ATR(high.shift(i),
                                       low.shift(i),
                                       close.shift(i),
                                       timeperiod=14)  # average true range
        # Volume indicator
        # on balance volume
        data["obv{0}".format(i)] = OBV(close.shift(i), volume.shift(i))
        # chaikin A/D oscillator
        data["adosc{0}".format(i)] = ADOSC(high.shift(i),
                                           low.shift(i),
                                           close.shift(i),
                                           volume.shift(i),
                                           fastperiod=3,
                                           slowperiod=10)

        # Stochastic Oscillator Slow %k: (C-L)/(H-L)*100
        data["slowk{0}".format(i)], data["slowd{0}".format(i)] = STOCH(
            high.shift(i),
            low.shift(i),
            close.shift(i),
            fastk_period=5,
            slowk_period=3,
            slowk_matype=0,
            slowd_period=3,
            slowd_matype=0)

        # STOCHF - Stochastic Fast
        data["fastk{0}".format(i)], data["fastd{0}".format(i)] = STOCHF(
            high.shift(i),
            low.shift(i),
            close.shift(i),
            fastk_period=5,
            fastd_period=3,
            fastd_matype=0)

        #vortex
        data["vortex_indicator_pos{0}".format(i)] = vortex_indicator_pos(
            high.shift(i), low.shift(i), close.shift(i), n=14, fillna=False)
        data["vortex_indicator_neg{0}".format(i)] = vortex_indicator_neg(
            high.shift(i), low.shift(i), close.shift(i), n=14, fillna=False)

        # returns
    for i in range(1, window):
        # overlap studies
        data["madev{0}".format(i)] = close - close.shift(1).rolling(
            window=i).mean()
        data["return{0}".format(i)] = close - close.shift(i)
    # std
    for i in range(2, window):
        data["std{0}".format(i)] = close.rolling(
            i).std()  #Standard deviation for a period of 5 days

    return data  #madev, roc,willr,rsi,apo,atr,obv,adosc,slowk,slowd,fastk,fastd,vpos, vneg, returns, stds
Esempio n. 18
0
def rebalance(context, data):

    # Return the 20-day 'high', 'low', and 'close' for True Range calculation
    price_history = data.history(context.my_futures,
                                 ['high', 'low', 'close', 'price'], 21, '1d')

    # Return the 10-day 'price' history of our futures
    recent_prices = data.history(context.my_futures, ['high', 'low', 'price'],
                                 10, '1d')

    # Return the current contract of each of our futures
    contracts = data.current(context.my_futures, 'contract')

    # TRADE LOGIC
    #-------------
    for future in context.my_futures:

        # Position size constraints
        starting_cash = context.portfolio.starting_cash
        position_size = starting_cash * 0.01

        future_contract = contracts[future]

        # N CALCULATION (VOLATILITY METRIC)
        #---------------------------------
        highs = price_history['high'][future]
        lows = price_history['low'][future]
        closes = price_history['close'][future]

        # N is the 20-Day Average True Range
        N = ATR(highs, lows, closes, timeperiod=20)[-1]

        if np.isnan(N):
            continue

        # DOLLAR VOLATILITY ADJUSTMENT
        #------------------------------
        # Dollar Volatility
        dV = N * future_contract.multiplier

        # Unit Calculation
        unit = math.floor(position_size / dV)

        price = data.current(future, 'price')

        # Logs to see the price and unit data every time the function is called
        # log.info("Today's price of %s is: " % (future_contract.asset_name) + str(price))
        # log.info("The 20-day high of %s is: " % (future_contract.asset_name) + str(max(price_history['high'][future]))
        # log.info("The 20-day low of %s is: " % (future_contract.asset_name) + str(min(price_history['low'][future]))
        # log.info("Current unit of %s is: " % (future_contract.asset_name) + str(unit))

        high_20 = True if price >= max(
            price_history['high'][future]) else False
        low_20 = True if price <= min(price_history['low'][future]) else False

        high_10 = True if price >= max(
            recent_prices['high'][future]) else False
        low_10 = True if price <= min(recent_prices['low'][future]) else False

        # ENTRY STRATEGY
        #----------------
        # Long Entry
        if high_20:
            log.info("Entering long position in %s at $" %
                     (future_contract.asset_name) + str(price))
            order(future_contract, unit)

        # Short Entry
        elif low_20:
            log.info("Entering short position in %s at $" %
                     (future_contract.asset_name) + str(price))
            order(future_contract, -unit)

        # EXIT STRATEGY
        #---------------
        # Long Exit
        elif low_10:
            log.info("Exiting long position in %s at $" %
                     (future_contract.asset_name) + str(price))
            order_target_percent(future_contract, 0)

        # Short Exit
        elif high_10:
            log.info("Exiting short position in %s at $" %
                     (future_contract.asset_name) + str(price))
            order_target_percent(future_contract, 0)

        else:
            pass

        # CHECK POSITIONS
        #-----------------
        current_position = context.portfolio.positions[data.current(
            context.my_futures, 'contract')[future]]
        current_contract = current_position.asset

        if current_contract in context.portfolio.positions and data.can_trade(
                current_contract) and not get_open_orders(current_contract):

            # Positon details
            cost_basis = context.portfolio.positions[
                current_contract].cost_basis
            price = data.current(current_contract, 'price')
            holding = context.portfolio.positions[current_contract].amount

            long_position = True if holding > 0 else False
            short_position = True if holding < 0 else False

            # Log details for each position
            log.info("=================================")
            log.info("Position details for %s" %
                     str(current_contract.asset_name))
            log.info("The price is $ %s" % str(price))
            log.info("We are holding %s shares" % str(holding))
            log.info("Our cost basis is $ %s" % str(cost_basis))
            log.info(
                "Dollar value is $ %s" %
                str(abs((cost_basis * holding) * current_contract.multiplier)))
            log.info("=================================")

            # ADDING UNITS (Units are added at N/2 intervals)
            #---------------------------------------------------
            # Additional Long Unit
            if price >= (cost_basis + (N / 2)) and long_position:
                log.info("Purchased additional unit of %s at $" %
                         (future_contract.asset_name) + str(price))
                log.info("N is %s" % str(N))
                order(current_contract, unit)

            # Additional Short Unit
            if price <= (cost_basis - (N / 2)) and short_position:
                log.info("Shorted additional unit of %s at $" %
                         (future_contract.asset_name) + str(price))
                log.info("N is %s" % str(N))
                order(current_contract, -unit)

            # STOP LOSSES (We stop out at +/-1.05 * our cost_basis)
            #-------------------------------------------
            # Long Loss
            if price <= (cost_basis * -1.05) and long_position:
                log.info("Stopped out of long in %s at $" %
                         (future_contract.asset_name) + str(price))
                order_target_percent(current_contract, 0)

            # Short Loss
            if price >= (cost_basis * 1.05) and short_position:
                log.info("Stopped out of short in %s at $" %
                         (future_contract.asset_name) + str(price))
                order_target_percent(current_contract, 0)
Esempio n. 19
0
def Volatility_Indicator(open, high, low, close, volume):
    #Volatility Indicator Functions
    df["atr"] = ATR(high, low, close, timeperiod=14)  #Average True Range
    df["natr"] = NATR(high, low, close,
                      timeperiod=14)  #Normalized Average True Range
    df["tr"] = TRANGE(high, low, close)
Esempio n. 20
0
def rebalance(context, data):
    context.total_price = 0  # to be used later as a sort of benchmark

    # for each security in the list
    context.total_price = sum(data.current(context.security_list, 'price'))
    hist = data.history(context.security_list, ['high', 'low', 'close'], 30,
                        '1d')
    for security in context.security_list:
        highs = hist['high'][security][:-1]
        lows = hist['low'][security][:-1]
        closes = hist['close'][security][:-1]
        N = ATR(highs, lows, closes, timeperiod=20)[-1]
        if np.isnan(N):
            continue

        # count how many shares we have in open orders and own
        shares = 0
        for o in get_open_orders(security):
            shares += o.amount
        shares += context.portfolio.positions[security].amount

        # determine account size
        current_value = context.portfolio.cash + context.portfolio.positions_value
        if current_value < context.portfolio.starting_cash:
            account_size = -context.portfolio.starting_cash + 2 * current_value
        else:
            account_size = current_value

        # compute how many units to buy or sell
        trade_amt = math.floor(account_size * .01 / N)

        # 20-day high?
        h_20 = True if data.current(
            security, 'price') > context.past_high_max[security] else False

        # 20-day low?
        l_20 = True if data.current(
            security, 'price') < context.past_low_min[security] else False

        goal_shares = shares
        if h_20:
            # long
            goal_shares = trade_amt
        elif l_20:
            # sell or short
            if context.long_only:
                goal_shares = 0
            else:
                goal_shares = -trade_amt

        # goal_shares = shares + (amount to buy or sell)
        amt_to_buy = goal_shares - shares
        if amt_to_buy != 0:
            if amt_to_buy > 0:
                log.info("buying %s shares of %s" %
                         (amt_to_buy, security.symbol))
            if amt_to_buy < 0:
                log.info("selling %s shares of %s" %
                         (-amt_to_buy, security.symbol))
            order(security, amt_to_buy)

        # keep deques updated
        context.past_high_max[security] = max(context.past_high_max[security],
                                              data.current(security, 'high'))
        context.past_low_min[security] = min(context.past_low_min[security],
                                             data.current(security, 'low'))
Esempio n. 21
0
    def calculate_signals(self):
        for symbol in self.symbol_list:
            print('Searching for {1} signals ...'.format(symbol))

            last_price = self.data_handler.current_price(symbol)[0]

            h1_highs = self.data_handler.get_latest_bars_values(
                symbol, 'high', timeframe='H1', N=self.bars_window)

            h1_lows = self.data_handler.get_latest_bars_values(
                symbol, 'low', timeframe='H1', N=self.bars_window)

            h1_closes = self.data_handler.get_latest_bars_values(
                symbol, 'close', timeframe='H1', N=self.bars_window)

            h1_hlc3 = (h1_highs + h1_lows + h1_closes) / 3

            h1_ema_50 = EMA(h1_hlc3, timeperiod=50)
            h1_ema_100 = EMA(h1_hlc3, timeperiod=100)
            h1_ema_200 = EMA(h1_hlc3, timeperiod=200)

            m15_highs = self.data_handler.get_latest_bars_values(
                symbol, 'high', timeframe='m15', N=self.bars_window)

            m15_lows = self.data_handler.get_latest_bars_values(
                symbol, 'low', timeframe='m15', N=self.bars_window)

            m15_closes = self.data_handler.get_latest_bars_values(
                symbol, 'close', timeframe='m15', N=self.bars_window)

            m15_hlc3 = (m15_highs + m15_lows + m15_closes) / 3

            m15_ema_50 = EMA(m15_hlc3, timeperiod=50)
            m15_ema_100 = EMA(m15_hlc3, timeperiod=100)
            m15_ema_200 = EMA(m15_hlc3, timeperiod=200)

            m15_price_bb_up, m15_price_bb_mid, m15_price_bb_low = BBANDS(
                m15_hlc3, timeperiod=20, nbdevup=2, nbdevdn=2)

            m15_price_bb_low_dist = (m15_price_bb_mid + m15_price_bb_low) / 2
            m15_price_bb_up_dist = (m15_price_bb_up + m15_price_bb_mid) / 2

            m15_rsi = RSI(m15_closes, timeperiod=14)
            m15_rsi_bb_up, m15_rsi_bb_mid, m15_rsi_bb_low = BBANDS(
                m15_rsi, timeperiod=20, nbdevup=2, nbdevdn=2)

            m15_stochrsi = STOCHRSI(pd.Series(m15_closes), timeperiod=14)

            m15_atr = ATR(m15_highs, m15_lows, m15_closes, timeperiod=14)

            datetime = self.data_handler.get_latest_bar_datetime(symbol)[0]

            direction = None
            status = None
            position = 'Not yet'

            print(datetime)

            if last_price > h1_ema_50[-1] and last_price > h1_ema_100[
                    -1] and last_price > h1_ema_200[-1]:
                print('Uprend detected')

                if last_price > m15_ema_50[-1] and last_price > m15_ema_100[
                        -1] and last_price > m15_ema_200[-1]:
                    print('Uprend confirmed')
                    direction = 'LONG'

                    if m15_rsi[-1] < m15_rsi_bb_low[-1]:
                        print('Reversal Detected')
                        status = 'Reversal detected'

                        if last_price < m15_price_bb_low_dist[-1]:
                            print('Reversal confirmed')
                            status = 'Reversal confirmed'

                            if m15_stochrsi[-1] < 25:
                                print('Go LONG')
                                position = 'Go ahead'

            elif last_price < h1_ema_50[-1] and last_price < h1_ema_100[
                    -1] and last_price < h1_ema_200[-1]:
                print('Downrend detected')

                if last_price < m15_ema_50[-1] and last_price < m15_ema_100[
                        -1] and last_price < m15_ema_200[-1]:
                    print('Downrend confirmed')
                    direction = 'SHORT'

                    if m15_rsi[-1] > m15_rsi_bb_up[-1]:
                        print('Reversal Detected')
                        status = 'Reversal detected'

                        if last_price > m15_price_bb_up_dist[-1]:
                            print('Reversal confirmed')
                            status = 'Reversal confirmed'

                            if m15_stochrsi[-1] > 75:
                                print('Go SHORT')
                                position = 'Go ahead'

            else:
                pass

            print(symbol, direction, status, position, datetime)

            if status is not None:
                self.telegram.send_text({
                    'symbol':
                    symbol,
                    'direction':
                    direction,
                    'status':
                    status,
                    'position':
                    position,
                    'atr':
                    np.around(m15_atr[-1], decimals=5),
                    'datetime':
                    datetime
                })
Esempio n. 22
0
                                 2).shift(26)
        high_52 = DATA['high'].rolling(window=52).max()
        low_52 = DATA['low'].rolling(window=52).min()
        DATA['senkou_span_b'] = ((high_52 + low_52) / 2).shift(26)
        DATA['chikou_span'] = DATA['close'].shift(-26)  # sometimes -22
        DATA.loc[DATA.tenkan_sen > DATA.kijun_sen, 'cross'] = 1
        DATA.loc[DATA.tenkan_sen < DATA.kijun_sen, 'cross'] = -1
        DATA.loc[DATA.tenkan_sen == DATA.kijun_sen, 'cross'] = 0
        DATA['cross_2'] = DATA.cross.shift(2)
        DATA['sygnal'] = 0
        DATA.loc[DATA.senkou_span_a > DATA.senkou_span_b, 'kumo'] = 1
        DATA.loc[DATA.senkou_span_a < DATA.senkou_span_b, 'kumo'] = -1
        DATA.loc[DATA.senkou_span_a == DATA.senkou_span_b, 'kumo'] = 0
        DATA['kumo26'] = DATA.kumo.shift(-26)
        DATA['c26'] = DATA.close.shift(26)
        DATA['atr26'] = ATR(DATA.close, DATA.low, DATA.high, timeperiod=26)
        DATA['atr_sl'] = DATA.atr26 * ATR_RATIO
        data = DATA.tail(SAMPLES)
        data['signal'] = data.apply(ALGO[0], axis=1)
        man_close_date = get_prev_workday_datestring()

if SAVE_RESULTS:
    try:
        F_N = 'Results/' + str(ALGO[0]).split(' ')[1] + '-'
        F_N = F_N + str(NOW.year) + '-' + str(NOW.month) + '-' + str(NOW.day)
        F_N = F_N + '_' + str(NOW.hour) + '_' + str(NOW.minute) + '_'
        F_N = F_N + str(NOW.second)
        ALL_TRANS_DETAILS = F_N + '-d-atr-' + str(ATR_RATIO) + '-' \
                            + str(YEARS) + '-years.xlsx'
        ALL_TRANS_SUMMARY = F_N + '-s-atr-' + str(ATR_RATIO) + '-' \
                            + str(YEARS) + '-years.xlsx'
Esempio n. 23
0
def ATR_STOPLOSS(close, high, low, times=3, period=14, early_stop_profit=0.02, stop_early_times=3, repaint = False, median=False, average_high_low=False):
    starting_close = close[period]
    from talib import ATR
    if(average_high_low == False):
        if(median==False):
            atr= ATR(high,low, close ,timeperiod=period)
        else:
            atr=MATR(high,low, close ,timeperiod=period)
    else:
        atr=CLOSE_ATR(high,low, close ,timeperiod=period)
    first = 1
    import math
    atr_trailing_stoploss = np.full(len(close)+1, np.nan)
    for i in range(0,len(close)):
        if(i>0 and math.isnan(atr[i])==False and repaint==True):
            if((close[i-1]<atr_trailing_stoploss[i-1] and close[i]>atr_trailing_stoploss[i])
              or (close[i-1]>atr_trailing_stoploss[i-1] and close[i]<atr_trailing_stoploss[i])):
                starting_close = close[i]
        multiplier = times
        if(i>0 and math.isnan(atr[i])==False):
            if(close[i-1]>atr_trailing_stoploss[i] and close[i]<atr_trailing_stoploss[i]):
                loss = atr[i]*multiplier
                atr_trailing_stoploss[i+1]=close[i]+loss  
                continue
        if(i>0 and math.isnan(atr[i])==False):
            if(close[i-1]<atr_trailing_stoploss[i] and close[i]>atr_trailing_stoploss[i]):
                loss = atr[i]*multiplier
                atr_trailing_stoploss[i+1]=close[i]-loss  
                continue
        if(math.isnan(atr[i])==False):
            loss = atr[i]*multiplier
            atr_trailing_stoploss[i+1]=close[i]-loss
            if(close[i]<atr_trailing_stoploss[i]):
                if(atr_trailing_stoploss[i]>close[i]+loss):
                    '''
                    ratio_to_target = ((close[i]-starting_close)/(starting_close))/early_stop_profit
                    if(((close[i]-starting_close)/(starting_close))<-early_stop_profit):
                        loss = atr[i]*stop_early_times
                    else:
                        if(ratio_to_target<0):
                            loss = atr[i]*(times-((times - stop_early_times)*(-ratio_to_target)))
                        else:
                            loss = atr[i]*multiplier
                    '''
                    atr_trailing_stoploss[i+1]=close[i]+loss
                else:
                    if(math.isnan(atr_trailing_stoploss[i])==False):
                        atr_trailing_stoploss[i+1]=atr_trailing_stoploss[i]
            else:
                if(atr_trailing_stoploss[i]<close[i]-loss):
                    ratio_to_target = ((close[i]-starting_close)/(starting_close))/early_stop_profit
                    if(((close[i]-starting_close)/(starting_close))>early_stop_profit):
                        loss = atr[i]*stop_early_times
                    else:
                        if(ratio_to_target>0):
                            loss = atr[i]*(times-((times - stop_early_times)*ratio_to_target))
                        else:
                            loss = atr[i]*multiplier
                    
                    atr_trailing_stoploss[i+1]=close[i]-loss
                else:
                    if(math.isnan(atr_trailing_stoploss[i])==False):
                        atr_trailing_stoploss[i+1]=atr_trailing_stoploss[i]
    return atr_trailing_stoploss[:-1], atr_trailing_stoploss[-1:]
Esempio n. 24
0
def process_col(data, col="", *argv):
    params = '_'.join(str(x) for x in argv)
    if(col+"_"+params in data.columns):
        return
    
    if(col=="zero"):
        data['zero'] = np.full(len(data), 0)
       
    if(col=="atr_risk"):
        from talib import ATR
        data["atr_risk_"+params]= ATR(data['high'].values, data['low'].values, data['close'].values ,timeperiod=argv[0])
    
    if(col=="macd"):
        from talib import MACD
        data['macd_'+params], data['macd_signal_'+params], data['macd_hist_'+params] = MACD(data['close'], fastperiod=argv[0], slowperiod=argv[1], signalperiod=argv[2])

    if(col=="rsi"):
        from talib import RSI
        data['rsi_'+params] = RSI(data['close'].values, timeperiod=argv[0])

    if(col=="adx"):
        from talib import ADX
        data['adx_'+params] =  ADX(data['high'].values, data['low'].values, data['close'].values, timeperiod=argv[0])

    if(col=="kijunsen"):
        data['kijunsen_'+params] = KIJUNSEN(data['high'],data['low'], timeperiod=argv[0])
        
    if(col=="ema"):
        from talib import EMA
        data['ema_'+params] = EMA(data[argv[0]], timeperiod=argv[1])
        
    if(col=="sma"):
        from talib import SMA
        data['sma_'+params] = SMA(data[argv[0]], timeperiod=argv[1])
        
    if(col=="hma"):
        data['hma_'+params] = HMA(data[argv[0]], timeperiod=argv[1])
        
    if(col=="linearreg"):
        from talib import LINEARREG_ANGLE
        data['linearreg_'+params] = LINEARREG_ANGLE(data[argv[0]], timeperiod=argv[1])
        
    if(col=="linearreg"):
        from talib import LINEARREG_ANGLE
        data['linearreg_'+params] = LINEARREG_ANGLE(data[argv[0]], timeperiod=argv[1])
    
    if(col=="atr_stoploss"):
        from talib import LINEARREG_ANGLE
        data['atr_stoploss_'+params] = ATR_STOPLOSS(close = data.close.values, 
                                                   high = data.high.values, 
                                                   low = data.low.values, 
                                 times=argv[0], stop_early_times=argv[1], early_stop_profit=argv[2], period=argv[3], repaint=True)[0]

    if(col=="atr"):
        from talib import ATR
        data['atr_'+params] = ATR(data['high'].values, data['low'].values, data['close'].values ,timeperiod=argv[0])
    
    
    if(col=="ssl"):
        data["ssl_up_"+params],data["ssl_down_"+params]= SSL(data['high'].values, data['low'].values, data['close'].values ,timeperiod=argv[0])
    
    
    if(col=="ha"):
        data["ha_open"],data["ha_high"],data["ha_low"],data["ha_close"] = HEIKIN_ASHI(data['open'].values, data['high'].values, data['low'].values, data['close'].values)

    if(col=="rvi"):
        data["rvi_"+params],data["rvi_signal_"+params]= RVI(data['high'].values, data['low'].values, data['close'].values, data['open'].values,timeperiod=argv[0])

    if(col=="waddah"):
        data["waddah_bull_"+params],data["waddah_bear_"+params],data["waddah_explo_"+params],data["waddah_dead_"+params]= WADDAH_ATTAR_EXPLOSION(data['close'].values,data['high'].values,data['low'].values, sensitive = argv[0] , fast_period= argv[1], slow_period =  argv[2], channel_period =  argv[3], channel_mult =  argv[4], dead_zone= argv[5])
    
    if(col=="ash"):
        data["ASH_bull_"+params],data["ASH_bear_"+params]= ASH(data['close'].values, timerperiod=argv[0], smooth =argv[1])