Beispiel #1
0
    def macd200(self, df):
        #1. Calculate ATR for potential trade
        atr = atrcalc.ATRcalc(df)
        #####PLACEHOLDER
        # df = pd.read_csv('./database/AAPL.csv')
        #####END_PLACEHOLDER
        df = df.dropna()

        ###1. Getting Parameters

        ##b. MACD
        macdInput = df.head(34)
        macdInput = macdInput.iloc[::-1]
        MACDclose = macdInput['close'].values
        macd, macdsignal, macdhist = MACDFIX(MACDclose, signalperiod=9)
        # print("MACD\n", macd[-1])
        # print("Signal\n", macdsignal[-1])

        ##c. DelayedMACD
        delayedmacdInput = df.iloc[1:].head(34)
        delayedmacdInput = delayedmacdInput.iloc[::-1]
        delayedMACDclose = delayedmacdInput['close'].values
        delayedmacd, delayedmacdsignal, delayedmacdhist = MACDFIX(
            delayedMACDclose, signalperiod=9)

        ##c. 200EMA
        emaInput = df.head(200)
        emaInput = emaInput.iloc[::-1]
        EMAclose = emaInput['close'].values
        ema = EMA(EMAclose, timeperiod=200)

        # print("EMA\n", ema[-1])

        ##d. current price action
        priceaction = df.head(1)
        pricehigh = priceaction['high'].values[0]
        pricelow = priceaction['low'].values[0]
        priceclose = priceaction['close'].values[0]
        # print("pricehigh\n", pricehigh)
        # print("pricelow\n", pricelow)

        ###2. Analysing using the data provided

        ##macd-signal crossover type
        ## -1 means negative crossover
        ## 1 means positive crossover
        ## 0 means both
        if delayedmacd[-1] < delayedmacdsignal[-1] and macd[-1] > macdsignal[
                -1]:
            crossover = 1
        elif delayedmacd[-1] > delayedmacdsignal[-1] and macd[-1] < macdsignal[
                -1]:
            crossover = -1
        else:
            crossover = 0
        ##market-ema type
        ## 1 means low > 200EMA
        ## -1 means high < 200EMA
        ## 0 means otherwise

        if pricelow > ema[-1]: marketEMA = 1
        elif pricehigh < ema[-1]: marketEMA = -1
        else: marketEMA = 0

        ##OUTPUT
        if marketEMA == 1 and crossover > 0 and macd[-1] < 0: position = 1
        elif marketEMA == -1 and crossover < 0 and macd[-1] > 0: position = -1
        else: position = 0
        amount = 50
        confidence = 0
        if position == 1:
            stoploss = priceclose - 1.05 * atr
            takeprofit = priceclose + 1.45 * atr
            # amount = priceclose / (priceclose - stoploss)
            if (priceclose - stoploss) * amount < 0.1:
                position = 0
                amount = 0
                stoploss = 0
                takeprofit = 0
            else:
                pattern, patterntype = check(df.head(20))
                if position * pattern > 0:
                    confidence = abs(pattern)
                elif position * pattern < 0:
                    confidence = abs(1 / pattern)
                else:
                    confidence = 1

        elif position == -1:
            stoploss = priceclose + 1.05 * atr
            takeprofit = priceclose - 1.45 * atr
            # amount = priceclose / (stoploss - priceclose)
            if (stoploss - priceclose) * amount < 0.1:
                position = 0
                amount = 0
                stoploss = 0
                takeprofit = 0
            else:
                pattern, patterntype = check(df.head(20))
                if position * pattern > 0:
                    confidence = abs(pattern)
                elif position * pattern < 0:
                    confidence = abs(1 / pattern)
                else:
                    confidence = 1
        else:
            stoploss = 0
            takeprofit = 0
            amount = 0

        ##For test
        # position = 1

        # ##FOR TEST
        # position = 1
        return [position, amount, priceclose, stoploss, takeprofit, confidence]
Beispiel #2
0
    def trix200(self, df):
        df = df.dropna()

        #1. Calculate ATR for potential trade
        atr = atrcalc.ATRcalc(df)

        trixInput = df.head(60)
        trixInput = trixInput.iloc[::-1]
        trixOutput = TRIX(trixInput['close'].values, timeperiod=14)

        ##c. 200EMA
        emaInput = df.head(200)
        emaInput = emaInput.iloc[::-1]
        EMAclose = emaInput['close'].values
        ema = EMA(EMAclose, timeperiod=200)

        # print("EMA\n", ema[-1])

        ##d. current price action
        priceaction = df.head(1)
        pricehigh = priceaction['high'].values[0]
        pricelow = priceaction['low'].values[0]
        priceclose = priceaction['close'].values[0]
        # print("pricehigh\n", pricehigh)
        # print("pricelow\n", pricelow)

        if trixOutput[-2] < 0 and trixOutput[-1] > 0:
            crossover = 1
        elif trixOutput[-2] > 0 and trixOutput[-1] < 0:
            crossover = -1
        else:
            crossover = 0

        if pricelow > ema[-1]: marketEMA = 1
        elif pricehigh < ema[-1]: marketEMA = -1
        else: marketEMA = 0

        ##OUTPUT
        if marketEMA == 1 and crossover > 0: position = 1
        elif marketEMA == -1 and crossover < 0: position = -1
        else: position = 0
        amount = 50
        confidence = 0
        if position == 1:
            stoploss = priceclose - 1.05 * atr
            takeprofit = priceclose + 1.45 * atr
            # amount = priceclose / (priceclose - stoploss)
            if (priceclose - stoploss) * amount < 0.1:
                position = 0
                amount = 0
                stoploss = 0
                takeprofit = 0
            else:
                pattern, patterntype = check(df.head(20))
                if position * pattern > 0:
                    confidence = abs(pattern)
                elif position * pattern < 0:
                    confidence = abs(1 / pattern)
                else:
                    confidence = 1

        elif position == -1:
            stoploss = priceclose + 1.05 * atr
            takeprofit = priceclose - 1.45 * atr
            # amount = priceclose / (stoploss - priceclose)
            if (stoploss - priceclose) * amount < 0.1:
                position = 0
                amount = 0
                stoploss = 0
                takeprofit = 0
            else:
                pattern, patterntype = check(df.head(20))
                if position * pattern > 0:
                    confidence = abs(pattern)
                elif position * pattern < 0:
                    confidence = abs(1 / pattern)
                else:
                    confidence = 1
        else:
            stoploss = 0
            takeprofit = 0
            amount = 0

        # ##FOR TEST
        # position = 1
        return [position, amount, priceclose, stoploss, takeprofit, confidence]
Beispiel #3
0
    def SMA200(self, df):
        df = df.dropna()

        ###1. Getting Parameters
        ##a. current price action
        priceaction = df.head(1)
        pricehigh = priceaction['high'].values[0]
        pricelow = priceaction['low'].values[0]
        priceclose = priceaction['close'].values[0]

        ##b. previous price action
        prevaction = df.iloc[1:].head(1)
        prevhigh = prevaction['high'].values[0]
        prevlow = prevaction['low'].values[0]
        prevclose = prevaction['close'].values[0]

        ##d. current SMAs
        smaCurrentInput = df.head(20)
        sma20Current = SMA(smaCurrentInput['close'].values, timeperiod=20)
        smaCurrentInput = smaCurrentInput.head(10)
        sma10Current = SMA(smaCurrentInput['close'].values, timeperiod=10)

        ##e. previous SMAs
        smaPreviousInput = df.iloc[1:].head(20)
        sma20Previous = SMA(smaPreviousInput['close'].values, timeperiod=20)
        smaPreviousInput = smaPreviousInput.head(10)
        sma10Previous = SMA(smaPreviousInput['close'].values, timeperiod=10)

        ##f. 200EMA
        emaInput = df.head(200)
        emaInput = emaInput.iloc[::-1]
        EMAclose = emaInput['close'].values
        ema = EMA(EMAclose, timeperiod=200)

        ##trade conditions

        if sma10Previous[-1] < sma20Previous[-1] and sma10Current[
                -1] > sma20Current[-1]:
            crossover = 1
        elif sma10Previous[-1] > sma20Previous[-1] and sma10Current[
                -1] < sma20Current[-1]:
            crossover = -1
        else:
            crossover = 0

        ## 200EMA filtering false signal
        if pricelow > ema[-1]: marketEMA = 1
        elif pricehigh < ema[-1]: marketEMA = -1
        else: marketEMA = 0

        if crossover == 1 and marketEMA == 1:
            position = 1
        elif crossover == -1 and marketEMA == -1:
            position = -1
        else:
            position = 0

        atr = atrcalc.ATRcalc(df)
        amount = 50
        confidence = 0
        if position == 1:
            stoploss = priceclose - 1.05 * atr
            takeprofit = priceclose + 1.45 * atr
            # amount = priceclose / (priceclose - stoploss)
            if (priceclose - stoploss) * amount < 0.1:
                position = 0
                amount = 0
                stoploss = 0
                takeprofit = 0
            else:
                pattern, patterntype = check(df.head(20))
                if position * pattern > 0:
                    confidence = abs(pattern)
                elif position * pattern < 0:
                    confidence = abs(1 / pattern)
                else:
                    confidence = 1
        elif position == -1:
            stoploss = priceclose + 1.05 * atr
            takeprofit = priceclose - 1.45 * atr
            # amount = priceclose / (stoploss - priceclose)
            if (stoploss - priceclose) * amount < 0.1:
                position = 0
                amount = 0
                stoploss = 0
                takeprofit = 0
            else:
                pattern, patterntype = check(df.head(20))
                if position * pattern > 0:
                    confidence = abs(pattern)
                elif position * pattern < 0:
                    confidence = abs(1 / pattern)
                else:
                    confidence = 1
        else:
            stoploss = 0
            takeprofit = 0
            amount = 0

        # ##FOR TEST
        # position = 1
        return [position, amount, priceclose, stoploss, takeprofit, confidence]
Beispiel #4
0
    def ichimoku200(self, df):
        ## Step 1:
        #####PLACEHOLDER
        # df = pd.read_csv('./database/TSLA/temp2.csv')
        #####END_PLACEHOLDER
        df = df.dropna()
        ###1. Getting Parameters

        ##a. Senkou Span B Ahead
        Currentfifty_two = df.head(52)
        Currentfifty_two_high = Currentfifty_two['high'].max()
        Currentfifty_two_low = Currentfifty_two['low'].min()
        AheadSenkouB = (Currentfifty_two_high + Currentfifty_two_low) / 2
        # print("SenkouBAhead\n", AheadSenkouB)

        ##b. Current Kijun-Sen
        Currenttwenty_six = Currentfifty_two.head(26)
        Currenttwenty_six_high = Currenttwenty_six['high'].max()
        Currenttwenty_six_low = Currenttwenty_six['low'].min()
        CurrentKijun = (Currenttwenty_six_high + Currenttwenty_six_low) / 2
        # print("Kijun-Sen\n" , CurrentKijun)

        ##c. Current Tenkan-Sen
        Currentnine = Currenttwenty_six.head(9)
        Currentnine_high = Currentnine['high'].max()
        Currentnine_low = Currentnine['low'].min()
        CurrentTenkan = (Currentnine_high + Currentnine_low) / 2

        # print("Tenkan-Sen\n", CurrentTenkan)

        ##d. Senkou Span A Ahead
        AheadSenkouA = (CurrentKijun + CurrentTenkan) / 2
        # print("SenkouAAhead\n", AheadSenkouA)

        ##e. Senkou Span B Current
        Pastfifty_two = df.iloc[26:].head(52)
        Pastfifty_two_high = Pastfifty_two['high'].max()
        Pastfifty_two_low = Pastfifty_two['low'].min()
        CurrentSenkouB = (Pastfifty_two_high + Pastfifty_two_low) / 2
        # print("SenkouBCurrent\n", CurrentSenkouB)

        ##f. Past Kijun-Sen
        Pasttwenty_six = Pastfifty_two.head(26)
        Pasttwenty_six_high = Pasttwenty_six['high'].max()
        Pasttwenty_six_low = Pasttwenty_six['low'].min()
        PastKijun = (Pasttwenty_six_low + Pasttwenty_six_high) / 2
        # print("PastKijun-Sen\n",PastKijun)

        ##g. Past Tenkan-Sen
        Pastnine = Pasttwenty_six.head(9)
        Pastnine_high = Pastnine['high'].max()
        Pastnine_low = Pastnine['low'].min()
        PastTenkan = (Pastnine_high + Pastnine_low) / 2
        # print("PastTenkan-Sen\n", PastTenkan)

        ##h. Senkou Span A Current
        CurrentSenkouA = (PastKijun + PastTenkan) / 2
        # print("SenkouACurrent\n", CurrentSenkouA)

        ##i. Senkou Span B Past
        PastPastfifty_two = df.iloc[52:].head(52)
        PastPastfifty_two_high = PastPastfifty_two['high'].max()
        PastPastfifty_two_low = PastPastfifty_two['low'].min()
        PastSenkouB = (PastPastfifty_two_high + PastPastfifty_two_low) / 2

        ##j. Past Past Kijun - Sen
        PastPasttwenty_six = PastPastfifty_two.head(26)
        PastPasttwenty_six_high = PastPasttwenty_six['high'].max()
        PastPasttwenty_six_low = PastPasttwenty_six['low'].min()
        PastPastKijun = (PastPasttwenty_six_low + PastPasttwenty_six_high) / 2

        ##k. Past Past Tenkan-Sen
        PastPastnine = PastPasttwenty_six.head(9)
        PastPastnine_high = PastPastnine['high'].max()
        PastPastnine_low = PastPastnine['low'].min()
        PastPastTenkan = (PastPastnine_high + PastPastnine_low) / 2

        ##l. Senkou Span A Past
        PastSenkouA = (PastPastKijun + PastPastTenkan) / 2

        ##m. 200EMA
        emaInput = df.head(200)
        emaInput = emaInput.iloc[::-1]
        EMAclose = emaInput['close'].values
        ema = EMA(EMAclose, timeperiod=200)
        # print("EMA\n", ema[-1])

        ##n. current price action
        priceaction = df.head(1)
        pricehigh = priceaction['high'].values[0]
        pricelow = priceaction['low'].values[0]
        priceclose = priceaction['close'].values[0]
        ### IMPT CHIKOU SPAN = PRICE CLOSE

        # print("pricehigh\n", pricehigh)
        # print("pricelow\n", pricelow)

        ### 2. Analysing using Data Provided
        ##tenkan-kijun crossover type
        ## -1 means negative crossover
        ## 1 means positive crossover
        ## 0 means both

        delayOnePeriod = df.iloc[1:]

        ##b. Current Kijun-Sen
        Delaytwenty_six = delayOnePeriod.head(26)
        Delaytwenty_six_high = Delaytwenty_six['high'].max()
        Delaytwenty_six_low = Delaytwenty_six['low'].min()
        DelayKijun = (Delaytwenty_six_high + Delaytwenty_six_low) / 2
        # print("Delay Kijun-Sen\n" , DelayKijun)

        ##c. Current Tenkan-Sen
        Delaynine = Delaytwenty_six.head(9)
        Delaynine_high = Delaynine['high'].max()
        Delaynine_low = Delaynine['low'].min()
        DelayTenkan = (Delaynine_high + Delaynine_low) / 2

        # print("Tenkan-Sen\n", DelayTenkan)

        if DelayTenkan <= DelayKijun and CurrentTenkan >= CurrentKijun and pricelow > CurrentTenkan:
            crossover = 1
        elif DelayTenkan >= DelayKijun and CurrentTenkan <= CurrentKijun and pricehigh < CurrentTenkan:
            crossover = -1

        else:
            crossover = 0

        ##ahead cloud colour
        ## -1 means red cloud
        ## 1 means green cloud
        ## 0 means both

        if AheadSenkouA > AheadSenkouB: AheadCloud = 1
        elif AheadSenkouA < AheadSenkouB: AheadCloud = -1
        else: AheadCloud = 0

        ##market-ema type
        ## 1 means low > 200EMA
        ## -1 means high < 200EMA
        ## 0 means otherwise

        if pricelow > ema[-1]: marketEMA = 1
        elif pricehigh < ema[-1]: marketEMA = -1
        else: marketEMA = 0

        ##market-cloud type
        ## 1 means close is above current cloud, and close (lagging span) above the past cloud too
        ## -1 means close is below current cloud, and close (lagging span) below the past cloud too
        ## 0 means otherwise (absolutely no trading)

        if pricelow > max(CurrentSenkouA, CurrentSenkouB) and pricelow > max(
                PastSenkouB, PastSenkouA):
            marketCloud = 1
        elif pricehigh < min(CurrentSenkouB,
                             CurrentSenkouA) and pricehigh < min(
                                 PastSenkouA, PastSenkouB):
            marketCloud = -1
        else:
            marketCloud = 0

        if marketCloud == 1 and marketEMA > 0 and AheadCloud >= 0 and crossover > 0:
            position = 1  ##long
        elif marketCloud == -1 and marketEMA < 0 and AheadCloud <= 0 and crossover < 0:
            position = -1  ##short
        else:
            position = 0  ## no position
        amount = 50
        confidence = 0
        if position == 1:
            closeKijunDistance = priceclose - CurrentKijun
            adjustedDistance = 1.05 * closeKijunDistance
            stoploss = priceclose - adjustedDistance
            # amount = priceclose / (priceclose-stoploss)
            takeprofit = priceclose + 1.45 * (priceclose - stoploss)
            if (takeprofit - priceclose) * amount < 0.1:
                amount = 0
                position = 0
                stoploss = 0
                takeprofit = 0
            else:
                pattern, patterntype = check(df.head(20))
                if position * pattern > 0:
                    confidence = abs(pattern)
                elif position * pattern < 0:
                    confidence = abs(1 / pattern)
                else:
                    confidence = 1

        elif position == -1:
            closeKijunDistance = CurrentKijun - priceclose
            adjustedDistance = 1.05 * closeKijunDistance
            stoploss = priceclose + adjustedDistance
            # amount = priceclose / (stoploss - priceclose)
            takeprofit = priceclose - 1.45 * (stoploss - priceclose)
            if (priceclose - takeprofit) * amount < 0.1:
                amount = 0
                position = 0
                stoploss = 0
                takeprofit = 0
            else:
                pattern, patterntype = check(df.head(20))
                if position * pattern > 0:
                    confidence = abs(pattern)
                elif position * pattern < 0:
                    confidence = abs(1 / pattern)
                else:
                    confidence = 1
        else:
            amount = 0
            stoploss = 0
            takeprofit = 0

        # ##FOR TEST
        # position = 1
        return [position, amount, priceclose, stoploss, takeprofit, confidence]
Beispiel #5
0
def getEMA(volume, mov_date):
    real = EMA(volume, mov_date)
    return real
Beispiel #6
0
    def parabolic200(self, df):
        df = df.dropna()

        ###1. Getting Parameters
        ##a. current price action
        priceaction = df.head(1)
        pricehigh = priceaction['high'].values[0]
        pricelow = priceaction['low'].values[0]
        priceclose = priceaction['close'].values[0]
        ##b. SAR current

        sarCurrentInput = df.head(2)
        sarCurrentInput = sarCurrentInput.iloc[::-1]
        sarCurrentInputHigh = sarCurrentInput['high'].values
        sarCurrentInputLow = sarCurrentInput['low'].values
        sarCurrent = SAR(sarCurrentInputHigh,
                         sarCurrentInputLow,
                         acceleration=0,
                         maximum=0)

        ##c. previous price action
        prevaction = df.iloc[1:].head(1)
        prevhigh = prevaction['high'].values[0]
        prevlow = prevaction['low'].values[0]
        prevclose = prevaction['close'].values[0]

        ##d. previous SAR
        sarPreviousInput = df.iloc[1:].head(2)
        sarPreviousInput = sarPreviousInput.iloc[::-1]
        sarPreviousInputHigh = sarPreviousInput['high'].values
        sarPreviousInputLow = sarPreviousInput['low'].values
        sarPrevious = SAR(sarPreviousInputHigh,
                          sarPreviousInputLow,
                          acceleration=0,
                          maximum=0)

        ##b. 200EMA
        emaInput = df.head(200)
        emaInput = emaInput.iloc[::-1]
        EMAclose = emaInput['close'].values
        ema = EMA(EMAclose, timeperiod=200)

        ## SAR reversal
        ## 1 if from -ve become +ve
        ## -1 if from +ve become -ve
        ## 0 otherwise

        if prevclose < sarPrevious[-1] and priceclose > sarCurrent[-1]:
            change = 1
        elif prevclose > sarPrevious[-1] and priceclose < sarCurrent[-1]:
            change = -1
        else:
            change = 0

        ## 200EMA filtering false signal
        if pricelow > ema[-1]: marketEMA = 1
        elif pricehigh < ema[-1]: marketEMA = -1
        else: marketEMA = 0

        ##OUTPUT
        if marketEMA == 1 and change == 1: position = 1
        elif marketEMA == -1 and change == -1: position = -1
        else: position = 0

        amount = 50

        confidence = 0

        if position == 1:
            stoploss = sarCurrent[-1]
            takeprofit = priceclose + 1.45 * (priceclose - sarCurrent[-1])
            # amount = priceclose / (priceclose - stoploss)
            if (priceclose - stoploss) * amount < 0.1:
                position = 0
                amount = 0
                stoploss = 0
                takeprofit = 0
            else:
                pattern, patterntype = check(df.head(20))
                if position * pattern > 0:
                    confidence = abs(pattern)
                elif position * pattern < 0:
                    confidence = abs(1 / pattern)
                else:
                    confidence = 1
        elif position == -1:
            stoploss = sarCurrent[-1]
            takeprofit = priceclose - 1.45 * (sarCurrent[-1] - priceclose)
            # amount = priceclose / (stoploss - priceclose)
            if (stoploss - priceclose) * amount < 0.1:
                position = 0
                amount = 0
                stoploss = 0
                takeprofit = 0
            else:
                pattern, patterntype = check(df.head(20))
                if position * pattern > 0:
                    confidence = abs(pattern)
                elif position * pattern < 0:
                    confidence = abs(1 / pattern)
                else:
                    confidence = 1
        else:
            stoploss = 0
            takeprofit = 0
            amount = 0

        ##For test
        # position = 1

        # ##FOR TEST
        # position = 1
        return [position, amount, priceclose, stoploss, takeprofit, confidence]
Beispiel #7
0
    def process(self):
        logging.info('process')

        # Open positions
        response = API.position.list_open(ACCOUNT_ID)
        if response.status != 200:
            print(response.body)
        positions = set([p.instrument for p in response.body['positions']])

        # Pending orders
        response = API.order.list_pending(ACCOUNT_ID)
        if response.status != 200:
            print(response.body)
        orders = [o for o in filter(
            lambda o: o.type in ['STOP', 'LIMIT'], response.body['orders'])]
        for o in orders:
            positions.add(o.instrument)

        # Prices
        response = API.pricing.get(ACCOUNT_ID, instruments=','.join(SYMBOLS))
        prices = response.body['prices']

        # Order
        for i, instrument in enumerate(self.instruments):
            symbol = instrument.symbol
            if symbol in positions:
                continue
            data = instrument.data
            t = data['time'].values[-1]
            close = data['close'].values
            ema6 = EMA(close, timeperiod=6)
            ema18 = EMA(close, timeperiod=18)
            units = SIZE
            buy = False
            ask = prices[i].asks[0].price
            bid = prices[i].bids[0].price
            price = ask

            logging.info('symbol=%s, time=%s, ask=%.5f, bid=%.5f', symbol, t, ask, bid)

            if cross_up(ema6, ema18):
                logging.info('buy %s', symbol)
                buy = True
            elif cross_down(ema6, ema18):
                logging.info('sell %s', symbol)
                price = bid
                units = -units
            else:
                continue

            response = API.order.stop(
                ACCOUNT_ID,
                instrument=symbol,
                units=units,
                price=instrument.price_value(
                    price + instrument.pips_value(DELTA, buy)),
                takeProfitOnFill=transaction.TakeProfitDetails(
                    price=instrument.price_value(price + instrument.pips_value(PROFIT, buy))),
                stopLossOnFill=transaction.StopLossDetails(
                    price=instrument.price_value(price - instrument.pips_value(LOSS, buy))),
                timeInForce='GTD',
                gtdTime=str(time.time() + 60)
            )
            if response.status != 201:
                print(response.body)
Beispiel #8
0
    pattern = -1
else:
    pattern = 0

##b. get BBands
upperband, middleband, lowerband = BBANDS(ad,
                                          timeperiod=20,
                                          nbdevup=2,
                                          nbdevdn=2,
                                          matype=0)

##c. 200EMA
emaInput = df.head(200)
emaInput = emaInput.iloc[::-1]
EMAclose = emaInput['close'].values
ema = EMA(EMAclose, timeperiod=200)

##d. current price action
priceaction = df.head(1)
pricehigh = priceaction['high'].values[0]
pricelow = priceaction['low'].values[0]
priceclose = priceaction['close'].values[0]

if pricehigh > upperband[-1]: breakBand = -1
elif pricelow < lowerband[-1]: breakBand = 1
else: breakBand = 0

if pricelow > ema[-1]: marketEMA = 1
elif pricehigh < ema[-1]: marketEMA = -1
else: marketEMA = 0
Beispiel #9
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])
##Overlap Studies
brsr6CSV = pd.read_csv("data/brsr6_ponto.csv")
abertura = brsr6CSV['ABERTURA'].values
fechamento = brsr6CSV['FECHAMENTO'].values
abertura = brsr6CSV['ABERTURA'].values
minimo = brsr6CSV['MINIMO'].values
maximo = brsr6CSV['MAXIMO'].values
variacao = brsr6CSV['VARIACAO'].values
volume = brsr6CSV['VOLUME'].values

upBR, midBR, lowBR = BBANDS(fechamento,
                            timeperiod=20,
                            nbdevup=2,
                            nbdevdn=2,
                            matype=0)
ema = EMA(fechamento,
          timeperiod=30)  #curto prazo 21. Medio prazo 24. Longo prazo 89
wma = WMA(fechamento, timeperiod=30)

# Momentum Indicators
macd, macdsignal, macdhist = MACD(fechamento,
                                  fastperiod=12,
                                  slowperiod=26,
                                  signalperiod=9)
# print('-----------------------------------MACD-----------------------------------')
# print(macd[34:37])
# print(macdsignal[34:37])
# print(macdhist[34:37])
#
rsi = RSI(fechamento, timeperiod=14)
# print('-----------------------------------RSI-----------------------------------')
# print(rsi[34:37])
def handler(event, context):
    print(sys.version)

    # def main():
    #     print(sys.version)

    # stock = input('Stock to plot: ')
    outputDf = pd.DataFrame()

    # symbolList = ['^NSEI','^NSEBANK']
    symbolList = [
        '3MINDIA.NS', 'ACC.NS', 'AIAENG.NS', 'APLAPOLLO.NS', 'AUBANK.NS',
        'AARTIIND.NS', 'AAVAS.NS', 'ABBOTINDIA.NS', 'ADANIGAS.NS',
        'ADANIGREEN.NS', 'ADANIPORTS.NS', 'ADANIPOWER.NS', 'ADANITRANS.NS',
        'ABCAPITAL.NS', 'ABFRL.NS', 'ADVENZYMES.NS', 'AEGISCHEM.NS',
        'AJANTPHARM.NS', 'AKZOINDIA.NS', 'APLLTD.NS', 'ALKEM.NS',
        'ALLCARGO.NS', 'AMARAJABAT.NS', 'AMBER.NS', 'AMBUJACEM.NS',
        'APOLLOHOSP.NS', 'APOLLOTYRE.NS', 'ARVINDFASN.NS', 'ASAHIINDIA.NS',
        'ASHOKLEY.NS', 'ASHOKA.NS', 'ASIANPAINT.NS', 'ASTERDM.NS',
        'ASTRAZEN.NS', 'ASTRAL.NS', 'ATUL.NS', 'AUROPHARMA.NS',
        'AVANTIFEED.NS', 'DMART.NS', 'AXISBANK.NS', 'BASF.NS', 'BEML.NS',
        'BSE.NS', 'BAJAJ-AUTO.NS', 'BAJAJCON.NS', 'BAJAJELEC.NS',
        'BAJFINANCE.NS', 'BAJAJFINSV.NS', 'BAJAJHLDNG.NS', 'BALKRISIND.NS',
        'BALMLAWRIE.NS', 'BALRAMCHIN.NS', 'BANDHANBNK.NS', 'BANKBARODA.NS',
        'BANKINDIA.NS', 'MAHABANK.NS', 'BATAINDIA.NS', 'BAYERCROP.NS',
        'BERGEPAINT.NS', 'BDL.NS', 'BEL.NS', 'BHARATFORG.NS', 'BHEL.NS',
        'BPCL.NS', 'BHARTIARTL.NS', 'INFRATEL.NS', 'BIOCON.NS',
        'BIRLACORPN.NS', 'BSOFT.NS', 'BLISSGVS.NS', 'BLUEDART.NS',
        'BLUESTARCO.NS', 'BBTC.NS', 'BOMDYEING.NS', 'BOSCHLTD.NS',
        'BRIGADE.NS', 'BRITANNIA.NS', 'CARERATING.NS', 'CCL.NS', 'CESC.NS',
        'CRISIL.NS', 'CADILAHC.NS', 'CANFINHOME.NS', 'CANBK.NS',
        'CAPLIPOINT.NS', 'CGCL.NS', 'CARBORUNIV.NS', 'CASTROLIND.NS',
        'CEATLTD.NS', 'CENTRALBK.NS', 'CDSL.NS', 'CENTURYPLY.NS', 'CERA.NS',
        'CHALET.NS', 'CHAMBLFERT.NS', 'CHENNPETRO.NS', 'CHOLAHLDNG.NS',
        'CHOLAFIN.NS', 'CIPLA.NS', 'CUB.NS', 'COALINDIA.NS', 'COCHINSHIP.NS',
        'COLPAL.NS', 'CONCOR.NS', 'COROMANDEL.NS', 'CREDITACC.NS',
        'CROMPTON.NS', 'CUMMINSIND.NS', 'CYIENT.NS', 'DBCORP.NS', 'DCBBANK.NS',
        'DCMSHRIRAM.NS', 'DLF.NS', 'DABUR.NS', 'DALBHARAT.NS', 'DEEPAKNTR.NS',
        'DELTACORP.NS', 'DHFL.NS', 'DBL.NS', 'DISHTV.NS', 'DCAL.NS',
        'DIVISLAB.NS', 'DIXON.NS', 'LALPATHLAB.NS', 'DRREDDY.NS',
        'EIDPARRY.NS', 'EIHOTEL.NS', 'EDELWEISS.NS', 'EICHERMOT.NS',
        'ELGIEQUIP.NS', 'EMAMILTD.NS', 'ENDURANCE.NS', 'ENGINERSIN.NS',
        'EQUITAS.NS', 'ERIS.NS', 'ESCORTS.NS', 'ESSELPACK.NS', 'EXIDEIND.NS',
        'FDC.NS', 'FEDERALBNK.NS', 'FMGOETZE.NS', 'FINEORG.NS', 'FINCABLES.NS',
        'FINPIPE.NS', 'FSL.NS', 'FORTIS.NS', 'FCONSUMER.NS', 'FLFL.NS',
        'FRETAIL.NS', 'GAIL.NS', 'GEPIL.NS', 'GET&D.NS', 'GHCL.NS',
        'GMRINFRA.NS', 'GALAXYSURF.NS', 'GARFIBRES.NS', 'GAYAPROJ.NS',
        'GICRE.NS', 'GILLETTE.NS', 'GLAXO.NS', 'GLENMARK.NS', 'GODFRYPHLP.NS',
        'GODREJAGRO.NS', 'GODREJCP.NS', 'GODREJIND.NS', 'GODREJPROP.NS',
        'GRANULES.NS', 'GRAPHITE.NS', 'GRASIM.NS', 'GESHIP.NS',
        'GREAVESCOT.NS', 'GRINDWELL.NS', 'GUJALKALI.NS', 'GUJGASLTD.NS',
        'GMDCLTD.NS', 'GNFC.NS', 'GPPL.NS', 'GSFC.NS', 'GSPL.NS',
        'GULFOILLUB.NS', 'HEG.NS', 'HCLTECH.NS', 'HDFCAMC.NS', 'HDFCBANK.NS',
        'HDFCLIFE.NS', 'HFCL.NS', 'HATSUN.NS', 'HAVELLS.NS', 'HEIDELBERG.NS',
        'HERITGFOOD.NS', 'HEROMOTOCO.NS', 'HEXAWARE.NS', 'HSCL.NS',
        'HIMATSEIDE.NS', 'HINDALCO.NS', 'HAL.NS', 'HINDCOPPER.NS',
        'HINDPETRO.NS', 'HINDUNILVR.NS', 'HINDZINC.NS', 'HONAUT.NS',
        'HUDCO.NS', 'HDFC.NS', 'ICICIBANK.NS', 'ICICIGI.NS', 'ICICIPRULI.NS',
        'ISEC.NS', 'ICRA.NS', 'IDBI.NS', 'IDFCFIRSTB.NS', 'IDFC.NS',
        'IFBIND.NS', 'IFCI.NS', 'IIFL.NS', 'IRB.NS', 'IRCON.NS', 'ITC.NS',
        'ITDCEM.NS', 'ITI.NS', 'INDIACEM.NS', 'ITDC.NS', 'IBULHSGFIN.NS',
        'IBULISL.NS', 'IBREALEST.NS', 'IBVENTURES.NS', 'INDIANB.NS', 'IEX.NS',
        'INDHOTEL.NS', 'IOC.NS', 'IOB.NS', 'INDOSTAR.NS', 'IGL.NS',
        'INDUSINDBK.NS', 'INFIBEAM.NS', 'NAUKRI.NS', 'INFY.NS',
        'INOXLEISUR.NS', 'INTELLECT.NS', 'INDIGO.NS', 'IPCALAB.NS',
        'JBCHEPHARM.NS', 'JKCEMENT.NS', 'JKLAKSHMI.NS', 'JKPAPER.NS',
        'JKTYRE.NS', 'JMFINANCIL.NS', 'JSWENERGY.NS', 'JSWSTEEL.NS',
        'JAGRAN.NS', 'JAICORPLTD.NS', 'JISLJALEQS.NS', 'J&KBANK.NS',
        'JAMNAAUTO.NS', 'JINDALSAW.NS', 'JSLHISAR.NS', 'JSL.NS',
        'JINDALSTEL.NS', 'JCHAC.NS', 'JUBLFOOD.NS', 'JUBILANT.NS',
        'JUSTDIAL.NS', 'JYOTHYLAB.NS', 'KPRMILL.NS', 'KEI.NS', 'KNRCON.NS',
        'KPITTECH.NS', 'KRBL.NS', 'KAJARIACER.NS', 'KALPATPOWR.NS',
        'KANSAINER.NS', 'KTKBANK.NS', 'KARURVYSYA.NS', 'KSCL.NS', 'KEC.NS',
        'KIRLOSENG.NS', 'KOLTEPATIL.NS', 'KOTAKBANK.NS', 'L&TFH.NS', 'LTTS.NS',
        'LICHSGFIN.NS', 'LAXMIMACH.NS', 'LAKSHVILAS.NS', 'LTI.NS', 'LT.NS',
        'LAURUSLABS.NS', 'LEMONTREE.NS', 'LINDEINDIA.NS', 'LUPIN.NS',
        'LUXIND.NS', 'MASFIN.NS', 'MMTC.NS', 'MOIL.NS', 'MRF.NS', 'MAGMA.NS',
        'MGL.NS', 'MAHSCOOTER.NS', 'MAHSEAMLES.NS', 'M&MFIN.NS', 'M&M.NS',
        'MAHINDCIE.NS', 'MHRIL.NS', 'MAHLOG.NS', 'MANAPPURAM.NS', 'MRPL.NS',
        'MARICO.NS', 'MARUTI.NS', 'MFSL.NS', 'METROPOLIS.NS', 'MINDTREE.NS',
        'MINDACORP.NS', 'MINDAIND.NS', 'MIDHANI.NS', 'MOTHERSUMI.NS',
        'MOTILALOFS.NS', 'MPHASIS.NS', 'MCX.NS', 'MUTHOOTFIN.NS',
        'NATCOPHARM.NS', 'NBCC.NS', 'NCC.NS', 'NESCO.NS', 'NHPC.NS',
        'NIITTECH.NS', 'NLCINDIA.NS', 'NMDC.NS', 'NTPC.NS', 'NH.NS',
        'NATIONALUM.NS', 'NFL.NS', 'NBVENTURES.NS', 'NAVINFLUOR.NS',
        'NESTLEIND.NS', 'NETWORK18.NS', 'NILKAMAL.NS', 'NAM-INDIA.NS',
        'OBEROIRLTY.NS', 'ONGC.NS', 'OIL.NS', 'OMAXE.NS', 'OFSS.NS',
        'ORIENTCEM.NS', 'ORIENTELEC.NS', 'ORIENTREF.NS', 'PCJEWELLER.NS',
        'PIIND.NS', 'PNBHOUSING.NS', 'PNCINFRA.NS', 'PTC.NS', 'PVR.NS',
        'PAGEIND.NS', 'PARAGMILK.NS', 'PERSISTENT.NS', 'PETRONET.NS',
        'PFIZER.NS', 'PHILIPCARB.NS', 'PHOENIXLTD.NS', 'PIDILITIND.NS',
        'PEL.NS', 'POLYCAB.NS', 'PFC.NS', 'POWERGRID.NS', 'PRAJIND.NS',
        'PRESTIGE.NS', 'PRSMJOHNSN.NS', 'PGHL.NS', 'PGHH.NS', 'PNB.NS',
        'QUESS.NS', 'RBLBANK.NS', 'RECLTD.NS', 'RITES.NS', 'RADICO.NS',
        'RVNL.NS', 'RAIN.NS', 'RAJESHEXPO.NS', 'RALLIS.NS', 'RCF.NS',
        'RATNAMANI.NS', 'RAYMOND.NS', 'REDINGTON.NS', 'RELAXO.NS',
        'RELCAPITAL.NS', 'RELIANCE.NS', 'RELINFRA.NS', 'RPOWER.NS',
        'REPCOHOME.NS', 'RESPONIND.NS', 'SHK.NS', 'SBILIFE.NS', 'SJVN.NS',
        'SKFINDIA.NS', 'SRF.NS', 'SADBHAV.NS', 'SANOFI.NS', 'SCHAEFFLER.NS',
        'SIS.NS', 'SFL.NS', 'SHILPAMED.NS', 'SHOPERSTOP.NS', 'SHREECEM.NS',
        'RENUKA.NS', 'SHRIRAMCIT.NS', 'SRTRANSFIN.NS', 'SIEMENS.NS',
        'SOBHA.NS', 'SOLARINDS.NS', 'SONATSOFTW.NS', 'SOUTHBANK.NS',
        'STARCEMENT.NS', 'SBIN.NS', 'SAIL.NS', 'STRTECH.NS', 'STAR.NS',
        'SUDARSCHEM.NS', 'SPARC.NS', 'SUNPHARMA.NS', 'SUNTV.NS',
        'SUNCLAYLTD.NS', 'SUNDARMFIN.NS', 'SUNDRMFAST.NS', 'SUNTECK.NS',
        'SUPRAJIT.NS', 'SUPREMEIND.NS', 'SUZLON.NS', 'SWANENERGY.NS',
        'SYMPHONY.NS', 'SYNGENE.NS', 'TCIEXP.NS', 'TCNSBRANDS.NS',
        'TTKPRESTIG.NS', 'TVTODAY.NS', 'TV18BRDCST.NS', 'TVSMOTOR.NS',
        'TAKE.NS', 'TASTYBITE.NS', 'TCS.NS', 'TATAELXSI.NS', 'TATAINVEST.NS',
        'TATAMTRDVR.NS', 'TATAMOTORS.NS', 'TATAPOWER.NS', 'TATASTLBSL.NS',
        'TATASTEEL.NS', 'TEAMLEASE.NS', 'TECHM.NS', 'TECHNOE.NS', 'NIACL.NS',
        'RAMCOCEM.NS', 'THERMAX.NS', 'THYROCARE.NS', 'TIMETECHNO.NS',
        'TIMKEN.NS', 'TITAN.NS', 'TORNTPHARM.NS', 'TORNTPOWER.NS', 'TRENT.NS',
        'TRIDENT.NS', 'TRITURBINE.NS', 'TIINDIA.NS', 'UCOBANK.NS', 'UFLEX.NS',
        'UPL.NS', 'UJJIVAN.NS', 'ULTRACEMCO.NS', 'UNIONBANK.NS', 'UBL.NS',
        'MCDOWELL-N.NS', 'VGUARD.NS', 'VMART.NS', 'VIPIND.NS', 'VRLLOG.NS',
        'VSTIND.NS', 'WABAG.NS', 'VAIBHAVGBL.NS', 'VAKRANGEE.NS', 'VTL.NS',
        'VARROC.NS', 'VBL.NS', 'VEDL.NS', 'VENKEYS.NS', 'VINATIORGA.NS',
        'IDEA.NS', 'VOLTAS.NS', 'WABCOINDIA.NS', 'WELCORP.NS', 'WELSPUNIND.NS',
        'WHIRLPOOL.NS', 'WIPRO.NS', 'WOCKPHARMA.NS', 'YESBANK.NS', 'ZEEL.NS',
        'ZENSARTECH.NS', 'ZYDUSWELL.NS', 'ECLERX.NS'
    ]
    for symbol in symbolList:
        print(symbol)
        period = '2y'
        pd.options.display.max_rows = 2000
        # period = '6mo'

        # fetching 2 year 1h data as that is the limiit for 1 hr
        content = fetch_data(symbol, period, '1d')

        content = content.tz_localize(tz='Etc/UTC')
        content = content.tz_convert(tz='Asia/Kolkata')
        content.reset_index(inplace=True)
        content.rename(columns={'index': 'startTime'}, inplace=True)
        # hma = myHMACalc(content, 21)
        # content['21HMA'] = hma.values
        # ohlc = content["close"].resample("1h").ohlc()
        # print("Dummy")
        content['Symbol'] = symbol

        close = content['Close'].values
        # up, mid, low = BBANDS(close, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0)
        for hmaperiod in [5, 8, 15, 21, 50, 100, 200]:
            hma = myHMACalc(close, hmaperiod)
            hma = np.round(hma, 2)

            se = pd.Series(hma)
            content["{0}HMA".format(hmaperiod)] = se.values

        for emaperiod in [5, 8, 15, 22, 50, 100, 200]:
            ema = EMA(close, timeperiod=emaperiod)
            ema = np.round(ema, 2)

            se = pd.Series(ema)
            content["{0}EMA".format(emaperiod)] = se.values

        for smaperiod in [5, 8, 15, 22, 50, 100, 200]:
            sma = SMA(close, timeperiod=smaperiod)
            sma = np.round(sma, 2)

            se = pd.Series(sma)
            content["{0}SMA".format(smaperiod)] = se.values

        # populating a column if it is index or stock
        if symbol in ['^NSEI', '^NSEBANK']:
            content['Type'] = "Index"
        else:
            content['Type'] = "Stock"

        # GEt just the last 2 lines
        content = content.tail(2)

        # The last 2 lines is the data we operate on
        # Create multiple lists based on the criteria, like close to 200, crossed etc
        # then consolidate each to its own output
        # then alert mail or SNS or what not

        # Based on the columnval create a new column and populate all B
        # cloumnval-ARB - meaning above or below the columnval with the diff percent
        # however dilemma is if diffpercent  non 0 then it can neither be above or below
        # for now default 0 and can address later
        columnval = "200SMA"
        diffPercent = 0.0
        ARBcolumnval = 'ARB-{}'.format(columnval)
        content[ARBcolumnval] = 'B'

        # If condition is above set A for the rows

        content[ARBcolumnval][
            content[content['Close'] >= (1.0 + (0.01 * diffPercent)) *
                    content[columnval]].index] = 'A'

        # if content[columnval] >= (1.0 + (0.01 * diffPercent)) * content['Close']:
        #     content['{}-ARB'.format(columnval)] = 'A'
        # else:
        #     content['{}-ARB'.format(columnval)] = 'B'

        # Below block gets prev N rows val of a column and create a column
        # It will create column for the chose columnval and also the close
        nrowsback = 1
        columnvalback = ARBcolumnval

        # Create empty columns equal to n previos rows
        for itervar in range(1, nrowsback + 1, 1):
            content["{0}prev{1}".format(columnvalback, itervar)] = ''

        # Populating the above created columns
        for indexval, row in content.iterrows():
            for itervar in range(1, nrowsback + 1, 1):
                content["{0}prev{1}".format(
                    columnvalback, itervar)] = content.tail(itervar + 1).head(
                        1)[columnvalback].values[0]

        # tail the last line and append to the outputDf
        # Then from that filter 4 lists as per criteria
        # essential idea is one row with all data for all stocks and then filer and mail
        # That is the model for additional criteria
        content = content.tail(1)

        # Iterating through the list of index/stock and then appending the processed data to outputDf
        outputDf = outputDf.append(content, ignore_index=True)

    india_tz = tz.gettz('Asia/Kolkata')
    dtString = datetime.datetime.now(tz=india_tz).strftime("%d-%m-%Y")
    # print(outputDf)
    tmpPath = '/tmp/daily_MA_HMA_{}.csv'.format(dtString)
    uploadBucket = 'dart-analytics-dnd'
    outputDf.to_csv(tmpPath)

    s3_client = boto3.client('s3')
    s3_client.upload_file(tmpPath, uploadBucket,
                          'daily/daily_MA_HMA_{}.csv'.format(dtString))

    above2002percentNoCross = outputDf[
        (outputDf['Close'] >= outputDf['200SMA'])
        & (outputDf['Close'] <= 1.02 * outputDf['200SMA']) &
        (outputDf['ARB-200SMA'] == outputDf['ARB-200SMAprev1'])]
    below2002percentNoCross = outputDf[
        (outputDf['Close'] < outputDf['200SMA'])
        & (outputDf['Close'] >= 0.98 * outputDf['200SMA']) &
        (outputDf['ARB-200SMA'] == outputDf['ARB-200SMAprev1'])]
    above2002percentCross = outputDf[
        (outputDf['Close'] >= outputDf['200SMA'])
        & (outputDf['Close'] <= 1.02 * outputDf['200SMA']) &
        (outputDf['ARB-200SMA'] != outputDf['ARB-200SMAprev1'])]
    below2002percentCross = outputDf[
        (outputDf['Close'] < outputDf['200SMA'])
        & (outputDf['Close'] >= 0.98 * outputDf['200SMA']) &
        (outputDf['ARB-200SMA'] != outputDf['ARB-200SMAprev1'])]

    # print(above2002percentNoCross['Symbol'].tolist())
    # print("\n".join(above2002percentNoCross['Symbol'].tolist()[0:]))

    numberofStocksAbove200SMA = len(
        outputDf[(outputDf['Close'] >= outputDf['200SMA'])].index)
    numberofStocksBelow200SMA = len(
        outputDf[(outputDf['Close'] < outputDf['200SMA'])].index)

    print(numberofStocksAbove200SMA)
    print(numberofStocksBelow200SMA)

    SUBJECT = "Daily stock tracker"
    # The email body for recipients with non-HTML email clients.
    BODY_TEXT = "Number of stocks above 200 SMA"
    BODY_TEXT = BODY_TEXT + "\n\n" + str(numberofStocksAbove200SMA)
    BODY_TEXT = BODY_TEXT + "\n\n" + "Number of stocks below 200 SMA"
    BODY_TEXT = BODY_TEXT + "\n\n" + str(numberofStocksBelow200SMA)
    BODY_TEXT = BODY_TEXT + "\n\n" + "List of stocks aobve 200 SMA - within 2 percent"
    BODY_TEXT = BODY_TEXT + "\n\n" + "\n".join(
        above2002percentNoCross['Symbol'].tolist()[0:])
    BODY_TEXT = BODY_TEXT + "\n\n" + "List of stocks below 200 SMA - within 2 percent"
    BODY_TEXT = BODY_TEXT + "\n\n" + "\n".join(
        below2002percentNoCross['Symbol'].tolist()[0:])
    BODY_TEXT = BODY_TEXT + "\n\n" + "List of stocks aobve 200 SMA and corssed 200 SMA"
    BODY_TEXT = BODY_TEXT + "\n\n" + "\n".join(
        above2002percentCross['Symbol'].tolist()[0:])
    BODY_TEXT = BODY_TEXT + "\n\n" + "List of stocks below 200 SMA and crossed 200 SMA"
    BODY_TEXT = BODY_TEXT + "\n\n" + "\n".join(
        below2002percentCross['Symbol'].tolist()[0:])
    # print(BODY_TEXT)
    sendAWSMailAttachment('*****@*****.**', SUBJECT, BODY_TEXT,
                          tmpPath)
    # sendAWSMail(SUBJECT, BODY_TEXT)

    # above2002percentNoCross['Symbol'].series.to_csv('/home/ec2-user/environment/dart-stock-scan-lambda/above2002percentNoCross')
    # below2002percentNoCross['Symbol'].series.to_csv('/home/ec2-user/environment/dart-stock-scan-lambda/below2002percentNoCross')
    # above2002percentCross['Symbol'].series.to_csv('/home/ec2-user/environment/dart-stock-scan-lambda/above2002percentCross')
    # below2002percentCross['Symbol'].series.to_csv('/home/ec2-user/environment/dart-stock-scan-lambda/below2002percentCross')

    # print(above2002percent)
    # print(below2002percent)

    data = {
        'output': 'Hello World 11',
        'timestamp': datetime.datetime.utcnow().isoformat()
    }
    return {
        'statusCode': 200,
        'body': json.dumps(data),
        'headers': {
            'Content-Type': 'application/json'
        }
    }

    print("Hello")
def priceTechnicalIndicator(value, tot_lags, prefix):
    lags = np.array(tot_lags)
    lags = lags[lags >= 2]

    data_result = pd.DataFrame([])
    # MA series
    for lag in lags:
        # SMA
        sma = pd.Series(SMA(value, timeperiod=lag), name='%sMA_%dD' % (prefix, lag))
        data_result = pd.concat([data_result, sma], axis=1)

        # SMA derivatives
        tmp = ma_derivative_indicator(value, sma, 'MA', lag, prefix)
        data_result = data_result.join(tmp)

        # EMA
        ema = pd.Series(EMA(value, lag), name='%sEMA_%dD' % (prefix, lag))
        data_result = data_result.join(ema)

        # EMA derivatives
        tmp = ma_derivative_indicator(value, ema, 'EMA', lag, prefix)
        data_result = data_result.join(tmp)

        # WMA
        wma = pd.Series(WMA(value, lag), name='%sWMA_%dD' % (prefix, lag))
        data_result = data_result.join(wma)

        # WMA derivatives
        tmp = ma_derivative_indicator(value, wma, 'WMA', lag, prefix)
        data_result = data_result.join(tmp)

    # change percent
    lags = tot_lags
    for lag in lags:
        tmp = pd.Series(value.diff(lag) / value.shift(lag), name='%sRET_%dD' % (prefix, lag))
        data_result = data_result.join(tmp)

    # volatility
    lags = np.array(tot_lags)
    lags = lags[lags >= 5]
    for lag in lags:
        tmp = pd.Series(value.rolling(window=lag).std(), name='%sSTD_%dD' % (prefix, lag))
        data_result = data_result.join(tmp)

    # technical indicators
    lags = [7, 14, 21, 28]  # ****** 待修改,技术指标的参数只用最常用的一套
    for lag in lags:
        # bollinger brands
        tmp_upper, tmp_middle, tmp_lower = BBANDS(value, lag, 2, 2)
        tmp_upper.name = '%sBBANDS_UPPER_%dD' % (prefix, lag)
        tmp_lower.name = '%sBBANDS_LOWER_%dD' % (prefix, lag)
        data_result = data_result.join(tmp_upper)
        data_result = data_result.join(tmp_lower)

        # MACD
        tmp, tmp_signal, tmp_hist = MACD(value, 12, 26, lag)
        tmp.name = '%sMACD_DIF_12_26D' % prefix  # macd 对应 macd_dif 线
        tmp_signal.name = '%sMACD_DEA_12_26_%dD' % (prefix, lag)  # macd_signal 对应 macd_dea 线
        tmp_hist = 2 * tmp_hist
        tmp_hist.name = '%sMACD_12_26_%dD' % (prefix, lag)  # 2 * macd_hist 对应 macd 线
        if tmp.name not in data_result.columns:  # macd_dif is the same for all lags
            data_result = data_result.join(tmp)
        data_result = data_result.join(tmp_signal)
        data_result = data_result.join(tmp_hist)


    return data_result
Beispiel #13
0
    # Do MinMax normalization
    maxValue = train_df.to_numpy().max()
    minValue = train_df.to_numpy().min()
    diff = maxValue - minValue
    train = train_df.transform(lambda x: (x - minValue) / diff)
    # test = test_df.transform(lambda x: (x - minValue) / diff)

    # Use technical analysis to expand the data
    train["upperband"], train["middleband"], train["lowerband"] = BBANDS(
        train.close.to_numpy())
    train["sar"] = SAR(train.high.to_numpy(), train.low.to_numpy())
    train["rsi"] = RSI(train.close.to_numpy(), timeperiod=5)
    train["slowk"], train["slowd"] = STOCH(train.high.to_numpy(),
                                           train.low.to_numpy(),
                                           train.close.to_numpy())
    train["ema"] = EMA(train.close.to_numpy(), timeperiod=5)
    train["willr"] = WILLR(train.high.to_numpy(),
                           train.low.to_numpy(),
                           train.close.to_numpy(),
                           timeperiod=5)

    train_data = train.dropna()
    train_data = train_data.reset_index(drop=True)
    """
    test["upperband"], test["middleband"], test["lowerband"] = BBANDS(test.close.to_numpy())
    test["sar"] = SAR(test.high.to_numpy(), test.low.to_numpy())
    test["rsi"] = RSI(test.close.to_numpy(), timeperiod=5)
    test["slowk"], test["slowd"] = STOCH(test.high.to_numpy(), test.low.to_numpy(), test.close.to_numpy())
    """
    # 2->bullish, 0->bearish, 1->do nothing
    y = list()
Beispiel #14
0
    def bbands200(self, df):
        df = df.dropna()

        #1. Calculate ATR for potential trade
        atr = atrcalc.ATRcalc(df)

        pattern, patterntype = check(df.head(20))

        ##b. get BBands
        bband = df.head(21)
        bband = bband.iloc[1:]
        bband = bband.iloc[::-1]
        bbandInput = bband['close'].values
        upperband, middleband, lowerband = BBANDS(bbandInput,
                                                  timeperiod=20,
                                                  nbdevup=2,
                                                  nbdevdn=2,
                                                  matype=0)

        ##c. 200EMA
        emaInput = df.head(200)
        emaInput = emaInput.iloc[::-1]
        EMAclose = emaInput['close'].values
        ema = EMA(EMAclose, timeperiod=200)

        ##d. current price action
        priceaction = df.head(1)
        pricehigh = priceaction['high'].values[0]
        pricelow = priceaction['low'].values[0]
        priceclose = priceaction['close'].values[0]

        if pricehigh > upperband[-1]: breakBand = -1
        elif pricelow < lowerband[-1]: breakBand = 1
        else: breakBand = 0

        if pricelow > ema[-1]: marketEMA = 1
        elif pricehigh < ema[-1]: marketEMA = -1
        else: marketEMA = 0

        ##OUTPUT
        if marketEMA == 1 and pattern > 0 and patterntype == -1 and breakBand == 1:
            position = 1
        elif marketEMA == -1 and pattern < 0 and patterntype == -1 and breakBand == -1:
            position = -1
        else:
            position = 0
        amount = 50
        confidence = 0
        if position == 1:
            stoploss = priceclose - (1.05 * atr)
            takeprofit = priceclose + (1.45 * atr)
            # amount = priceclose / (priceclose - stoploss)
            if (stoploss - priceclose) * amount < 0.1:
                position = 0
                amount = 0
                stoploss = 0
                takeprofit = 0
            else:
                if position * pattern > 0:
                    confidence = abs(pattern)
                elif position * pattern < 0:
                    confidence = abs(1 / pattern)
                else:
                    confidence = 1

        elif position == -1:
            stoploss = priceclose + (1.05 * atr)
            takeprofit = priceclose - (1.45 * atr)
            # amount = priceclose / (stoploss - priceclose)
            if (stoploss - priceclose) * amount < 0.1:
                position = 0
                amount = 0
                stoploss = 0
                takeprofit = 0
            else:
                if position * pattern > 0:
                    confidence = abs(pattern)
                elif position * pattern < 0:
                    confidence = abs(1 / pattern)
                else:
                    confidence = 1

        else:
            stoploss = 0
            takeprofit = 0
            amount = 0

        # ##FOR TEST
        # position = 1
        return [position, amount, priceclose, stoploss, takeprofit, confidence]
Beispiel #15
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
                })
Beispiel #16
0
 def calcEMA(self, dates, volume, mov_date):
     real = EMA(volume, mov_date)
     EMA_, isExist = self.createDateFrame(dates, real, ['timestamp', 'EMA'])
     return real, EMA_, isExist
Beispiel #17
0
    def fetch(self,
              symbol: str,
              interval: Interval = Interval.DAY,
              window: Window = Window.YEAR,
              indicators: Indicators = [],
              verbose=False) -> pd.DataFrame:
        """
        Fetch symbol stock OHLCV from Yahoo Finance API

        Args:
            symbol (str): Symbol to fetch
            interval (Interval, optional): Interval (hour, day, week, ...) of data. Defaults to Interval.DAY.
            window (Window, optional): Length (day, week, month, year) of interval. Defaults to Window.YEAR.
            indicators (Indicators, optional): Array of indicators to include in the result. Defaults to empty array.

        Returns:
            pd.DataFrame: OHLCV pandas DataFrame with interval on window length and indicators if specified
        """
        try:
            if verbose:
                print(
                    f"Fetching OHLCV {symbol} stock data on {interval.name} interval and {window.name} window"
                )

            # Generic url to fetch
            url = f"https://query1.finance.yahoo.com/v8/finance/chart/{symbol}?region=FR&lang=fr-FR&includePrePost=false&interval={interval.value}&range={window.value}&corsDomain=fr.finance.yahoo.com&.tsrc=finance"

            req = requests.get(url)

            # Testing request status code
            if req.status_code == 200:

                # Extracting data as json
                data = req.json()

                # Creating new DataFrame
                df = pd.DataFrame()

                # Extract date from object
                if interval in [
                        Interval.MINUTE, Interval.TWO_MINUTE,
                        Interval.FIVE_MINUTE, Interval.FIFTEEN_MINUTE,
                        Interval.THIRTY_MINUTE, Interval.HOUR
                ]:
                    dateFromUnix = [
                        datetime.utcfromtimestamp(dt).strftime(
                            "%Y-%m-%d %H:%M:%S")
                        for dt in data["chart"]["result"][0]["timestamp"]
                    ]
                else:
                    dateFromUnix = [
                        datetime.utcfromtimestamp(dt).strftime("%Y-%m-%d")
                        for dt in data["chart"]["result"][0]["timestamp"]
                    ]

                # Date & OHLCV to DataFrame
                df["date"] = pd.to_datetime(dateFromUnix)
                df["open"] = data["chart"]["result"][0]["indicators"]["quote"][
                    0]["open"]
                df["high"] = data["chart"]["result"][0]["indicators"]["quote"][
                    0]["high"]
                df["low"] = data["chart"]["result"][0]["indicators"]["quote"][
                    0]["low"]
                df["close"] = data["chart"]["result"][0]["indicators"][
                    "quote"][0]["close"]
                df["volume"] = data["chart"]["result"][0]["indicators"][
                    "quote"][0]["volume"]

                # Drop NaN on close col
                df.dropna(subset=["close"], inplace=True)

                # Divide volume column by a 1 000
                df["volume"] = df["volume"].div(1000)

                # Set date column as index
                df.set_index("date", inplace=True)

                for indicator in indicators:
                    # ADX
                    if indicator == Indicators.ADX:
                        df[indicator.value] = ADX(df["high"], df["low"],
                                                  df["close"])
                    # BBANDS
                    elif indicator == Indicators.BBANDS:
                        df[Indicators.BBANDS.value[0]], df[
                            Indicators.BBANDS.value[1]], df[
                                Indicators.BBANDS.value[2]] = BBANDS(
                                    df["close"])
                        df["p_band"] = 100 - \
                            (df["l_band"] / df["u_band"] * 100)
                        df["p_band_ma_5"] = MA(df["p_band"], timeperiod=5)
                    # EMA
                    elif indicator == Indicators.EMA:
                        for ema in Indicators.EMA.value:
                            df[ema] = EMA(df["close"],
                                          timeperiod=int(ema.split("_")[1]))
                    # MA
                    elif indicator == Indicators.MA:
                        for ma in Indicators.MA.value:
                            df[ma] = MA(df["close"],
                                        timeperiod=int(ma.split("_")[1]))

                    # OBV
                    elif indicator == Indicators.OBV:
                        df[indicator.value] = OBV(df["close"], df["volume"])
                        df[indicator.value] = df[indicator.value].div(1000)
                    # PSAR
                    elif indicator == Indicators.PSAR:
                        df[indicator.value] = SAR(df["high"], df["low"])
                    # PERCENT CHANGE
                    elif indicator == Indicators.P_CHANGE:
                        for p_change in Indicators.P_CHANGE.value:
                            df[p_change] = df["close"].pct_change(
                                int(p_change.split(" ")[1])) * 100
                    # RSI
                    elif indicator == Indicators.RSI:
                        df[indicator.value] = RSI(df["close"])

                return df.round(decimals=2)

        except Exception as e:
            print(e)