Example #1
0
    def init(self):
        x = Indicator('./data/Equities_27.csv', limit_data)
        x.bollinger(2.5)
        #x.mean_reversion(0.09)
        x.macd(False, window=20, trend_ma=100)
        #x.ma()
        x.rsi(14, 20)
        x.kdj()
        #x2 = Indikeppar('./data/Equities_27.csv','./data/Equities_200.csv',limit_data)
        #x2.keppar(20, 10)

        # Input: array of the buy&sell signal
        # BOLLINGER
        self.buyS_boll = x.data['Bollinger_Buy'].to_numpy()
        self.sellS_boll = x.data['Bollinger_Sell'].to_numpy()
        self.s_boll = self.I(LOAD, self.sellS_boll, name='sellSIGNAL_BOLL')
        self.b_boll = self.I(LOAD, self.buyS_boll, name='buySIGNAL_BOLL')

        # MACD
        self.buyS_macd = x.data['MACD_Buy'].to_numpy()
        self.sellS_macd = x.data['MACD_Sell'].to_numpy()
        self.s_macd = self.I(LOAD, self.sellS_macd, name='sellSIGNAL_macd')
        self.b_macd = self.I(LOAD, self.buyS_macd, name='buySIGNAL_macd')

        # RSI
        self.buyS_rsi = x.data['RSI_Buy'].to_numpy()
        self.sellS_rsi = x.data['RSI_Sell'].to_numpy()
        self.s_rsi = self.I(LOAD, self.sellS_rsi, name='sellSIGNAL_rsi')
        self.b_rsi = self.I(LOAD, self.buyS_rsi, name='buySIGNAL_rsi')

        # KDJ
        self.buyS_kdj = x.data['KDJ_Buy'].to_numpy()
        self.sellS_kdj = x.data['KDJ_Sell'].to_numpy()
        self.s_kdj = self.I(LOAD, self.sellS_kdj, name='sellSIGNAL_kdj')
        self.b_kdj = self.I(LOAD, self.buyS_kdj, name='buySIGNAL_kdj')

        # keppar
        #self.buyS_keppar = x2.data['keppar_Buy'].to_numpy()
        #self.sellS_keppar = x2.data['keppar_Sell'].to_numpy()
        #self.s_keppar = self.I(LOAD, self.sellS_keppar, name='sellSIGNAL_keppar')
        #self.b_keppar = self.I(LOAD, self.buyS_keppar, name='buySIGNAL_keppar')

        # signal weighting
        self.s = 0
        self.b = 0
        self.s += 0 * self.s_boll + 0 * self.s_macd + 0 * self.s_rsi + 0 * self.s_kdj  # + 1 * self.s_keppar
        self.b += 0 * self.b_boll + 0 * self.b_macd + 0 * self.b_rsi + 0 * self.b_kdj  # + 1 * self.b_keppar
        new_reader = csv.reader(data)
    except FileNotFoundError as fnfe:
        continue

    listener = open("../txt_files/data.txt", "w")
    listener.close()

    candles = []
    for line in new_reader:
        candles.append(line)

    capital = 100
    private_client = AuthenticatedClient(Data.API_Public_Key, Data.API_Secret_Key, Data.Passphrase)
    new_order = Order(private_client)
    position = OpenPosition(new_order)
    indicator = Indicator()
    bands_1dev = BB(ndbevup=1, nbdevdn=1)

    indicator_list = [indicator, bands_1dev]
    for new_indicator in indicator_list:
        new_indicator.candles = candles[1:]
        new_indicator.get_data_set()
        new_indicator.reverse_data()
        new_indicator.get_dates()
        new_indicator.get_np_array()
        new_indicator.set_indicator()

    # verifies that the data and dates was extracted successfully
    h = 0
    y = -1
    while h < len(indicator.candles):
Example #3
0
                                                                           outputsize='full')
            ohlc_intraday_30_mins[tickers[i]] = massage_ohlv_data(
                ohlc_intraday_30_mins[tickers[i]], meta_data, tickers[i])
            drop.append(tickers[i])
        except:
            print("Couldn't fetch data for: ", tickers[i])
    attempt += 1

tickers = ohlc_intraday.keys(
)  # redefine tickers variable after removing any tickers with corrupted data

collated_data = {}
for ticker in tickers:

    # Get the trend line of the short term data
    ohlc_intraday[ticker]["price_slope"] = Indicator.slope(
        ohlc_intraday[ticker]["Adj Close"], 5)
    ohlc_intraday[ticker]["short_trend"] = np.where(ohlc_intraday[ticker]["price_slope"] > 0, 1, \
                                                        np.where(ohlc_intraday[ticker]["price_slope"] < 0, -1, 0))
    for i in range(1, len(ohlc_intraday[ticker]["short_trend"])):
        if ohlc_intraday[ticker]["short_trend"][i] > 0 and \
           ohlc_intraday[ticker]["short_trend"][i-1] > 0:
            ohlc_intraday[ticker]["short_trend"][i] += ohlc_intraday[ticker][
                "short_trend"][i - 1]
        elif ohlc_intraday[ticker]["short_trend"][i] < 0 and \
             ohlc_intraday[ticker]["short_trend"][i-1] < 0:
            ohlc_intraday[ticker]["short_trend"][i] += ohlc_intraday[ticker][
                "short_trend"][i - 1]

    # Get the trend line of the mid frame
    ohlc_intraday_30_mins[ticker]["price_slope"] = Indicator.slope(
        ohlc_intraday_30_mins[ticker]["Adj Close"], 5)
Example #4
0
    def frames():
        camera = cv2.VideoCapture(Camera.video_source)
        print('Starting camera ...')
        width = 640
        height = 480
        camera.set(cv2.CAP_PROP_FRAME_WIDTH, width)
        camera.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
        if not camera.isOpened():
            raise RuntimeError('Could not start camera.')

        indicator = Indicator()
        md = MotionDetection(threshold=2500, weight=0.08)
        fd = FaceDetection()
        PicDir = ''
        savePics = []
        isAlarm = False
        mailSent = False
        lastMove = lastAuth = lastAlarm = time.time()
        global MOTION_BUFFER
        global FACE_BUFFER
        global ALARM_DURATION

        while True:
            # read current frame
            _, img = camera.read()
            # img = cv2.resize(img, (320, 240))
            now = time.time()
            timestamp = datetime.now().strftime('%Y_%m_%d_%H_%M_%S_%f')

            # Motion Detection: not ( (now-lastAuth<FACE_BUFFER) or (lastMove>lastAuth))
            if now - lastAuth > AUTH_BUFFER and lastMove <= lastAuth:
                indicator.led([0, 0, 255], 1)
                print('[{0}] Detecting motion ...'.format(timestamp))
                img, motion = md.motionDetect(img)
                if motion:
                    print('[{0}] Motion detected !!'.format(timestamp))
                    lastMove = now
                    indicator.led([255, 255, 0], 2)
            else:
                md.updateFrame(img)

            # Face Detection: (now-lastAuth>FACE_BUFFER) and (lastMove > lastAuth)
            if now - lastAuth > AUTH_BUFFER and lastMove > lastAuth:
                img, names = fd.detect(img)
                print('[{0}] Detecting face ...'.format(timestamp))
                if 'Mike' in names:
                    print('[{0}] Authentication passed'.format(timestamp))
                    lastAuth = now
                    savePics.clear()
                    mailSent = False
                    indicator.led([0, 255, 0], 0)
                    if isAlarm:
                        indicator.beep(0)
                        isAlarm = False

            # Backup frame: lastMove>lastAuth and not mailSent
            if lastMove > lastAuth and not mailSent:
                savePics.append((timestamp, img))

            # Alarm: now-lastMove>ALARM_BUFFER and lastMove>lastAuth
            if now - lastMove > ALARM_BUFFER and lastMove > lastAuth:
                if not isAlarm:
                    indicator.led([255, 0, 0], 4)
                    indicator.beep(3)
                    isAlarm = True
                if not mailSent:
                    print('[{0}] Saving alarm pics ...'.format(timestamp),
                          end='')
                    os.mkdir(timestamp)
                    for tm, pic in savePics:
                        path = '{0}/{1}.JPG'.format(timestamp, tm)
                        cv2.imwrite(path, pic)
                    os.system('sh mail.sh {0}'.format(timestamp))
                    print('done')
                    mailSent = True
            if now - lastAlarm > ALARM_DURATION:
                lastAuth = lastMove = lastAlarm = now
                indicator.led([0, 255, 0], 0)
                indicator.beep(0)
                savePics.clear()
                isAlarm = False
                mailSent = False
                lastMove = lastAuth = lastAlarm = time.time()

            # encode as a jpeg image and return it
            yield cv2.imencode('.jpg', img)[1].tobytes()
Example #5
0
        if tim <= 60:
            file_name = f"../../data_{str(tim)}m/{token}_{str(tim)}m.csv"
        else:
            new_time = tim / 60
            file_name = f"../../data_{str(new_time)}h/{token}_{str(new_time)}h.csv"

        try:
            last_date = float(append_data(file_name, new_data)[0])
            diff = time.time() - last_date
            req = diff / gra
            max_requests = req / 300
        except FileNotFoundError:
            max_requests = ((60 / tim) * 17520) / 300

        indicator = Indicator()
        seconds = 300 * 60 * tim  # number of seconds in a request for 300 candles
        callback = seconds  # start requesting data from "seconds" seconds ago
        begin = 0  # stop requesting data at 0 seconds ago
        requests = 0  # number of request in the last second
        print(token)

        data = []
        index = 0
        # Requests data from coinbase
        while index < int(max_requests):

            try:
                indicator.set_candles(product=token,
                                      callback=get_time(callback),
                                      begin=get_time(begin),
Example #6
0
 def setup_indicators(self, rover):
     if self.board_type is 'navio2':
         rover.indicator = NAVIO2LED()
     else:
         rover.indicator = Indicator()
Example #7
0
 def __init__(self, green_pin_tuple, red_pin_tuple, high_is_on=True):
     self._green_indicator = Indicator(green_pin_tuple, high_is_on)
     self._red_indicator = Indicator(red_pin_tuple, high_is_on)
Example #8
0
class GreenRedIndicator:
    def __init__(self, green_pin_tuple, red_pin_tuple, high_is_on=True):
        self._green_indicator = Indicator(green_pin_tuple, high_is_on)
        self._red_indicator = Indicator(red_pin_tuple, high_is_on)

    def blink_amber(self, times):
        for _ in range(times):
            self.turn_on_amber()
            time.sleep(0.25)
            self.turn_off_amber()
            time.sleep(0.25)
        self.turn_off_amber()

    def blink_green(self, times):
        self._green_indicator.blink_times(times)

    def blink_red(self, times):
        self._red_indicator.blink_times(times)

    def turn_off(self):
        self.turn_off_amber()

    def turn_off_amber(self):
        self._green_indicator.turn_off()
        self._red_indicator.turn_off()

    def turn_off_green(self):
        self._green_indicator.turn_off()

    def turn_off_red(self):
        self._red_indicator.turn_off()

    def turn_on(self):
        self._turn_on_amber()

    def turn_on_amber(self):
        self._green_indicator.turn_on()
        self._red_indicator.turn_on()

    def turn_on_green(self):
        self._green_indicator.turn_on()

    def turn_on_red(self):
        self._red_indicator.turn_on()
Example #9
0
    def get_interday_collated_data(tickers, n, delta):
        attempt = 0
        drop = []
        ohlc_interday = {}
        while len(tickers) != 0 and attempt <= 1:
            tickers = [j for j in tickers if j not in drop]
            for i in range(len(tickers)):
                try:
                    # Taking the price of delta days back coz. of the conditon market is right now
                    ohlc_interday[tickers[i]] = pdr.get_data_yahoo(
                        tickers[i],
                        datetime.date.today() - datetime.timedelta(n),
                        datetime.date.today() - datetime.timedelta(delta))
                    ohlc_interday[tickers[i]] = ohlc_interday[
                        tickers[i]].iloc[:, [2, 0, 1, 5, 4]]
                    ohlc_interday[tickers[i]].index.names = ['date']
                except:
                    print("Couldn't fetch data for: ", tickers[i])
            attempt += 1

        # These are tickers for which we could fetch the data from yahoo finance
        tickers = ohlc_interday.keys()

        #Merging renko df with the ohlc table
        ohlc_renko = {}
        df = copy.deepcopy(ohlc_interday)
        collated_data = {}
        tickers_ret = {}
        tickers_state = {}
        tickers_signal = {}
        for ticker in tickers:
            renko = Indicator.renko_DF(df[ticker])
            renko.columns = [
                "Date", "open", "high", "low", "close", "uptrend", "bar_num"
            ]
            df[ticker]["Date"] = df[ticker].index
            ohlc_renko[ticker] = df[ticker].merge(
                renko.loc[:, ["Date", "bar_num"]], how="outer", on="Date")

            # RSI is for last 14 days
            # RSI > 70 : overbought
            # RSI < 30 : oversold
            rsi = Indicator.RSI(df[ticker], 14)
            rsi_frame = rsi.to_frame()
            rsi_frame.reset_index(inplace=True)
            rsi_frame.columns = ["Date", "RSI"]

            # ADX (trend) is also for last 14 days
            # 0-25: Weak
            # 25-50: Strong
            # > 50: Very strong
            adx = Indicator.ADX(df[ticker], 14)
            adx.index.names = ['Date']
            adx_frame = adx.to_frame()
            adx_frame.reset_index(inplace=True)
            adx_frame.column = ["Date", "ADX"]

            atr = Indicator.ATR(df[ticker], 14)
            atr.column = ["Date", "ATR"]

            # "bar_num" column is based on renko chart which has brick size based on ATR (see renko function above)
            ohlc_renko[ticker]["bar_num"].fillna(method='ffill', inplace=True)
            ohlc_renko[ticker]["obv"] = Indicator.OBV(ohlc_renko[ticker])

            # obv slope takes last 5 points into consideration
            ohlc_renko[ticker]["obv_slope"] = Indicator.slope(
                ohlc_renko[ticker]["obv"], 5)

            # Merging the RSI data
            ohlc_renko[ticker] = ohlc_renko[ticker].merge(
                rsi_frame.loc[:, ["Date", "RSI"]], how="outer", on="Date")

            # Merging the ADX data
            ohlc_renko[ticker] = ohlc_renko[ticker].merge(
                adx_frame.loc[:, ["Date", "ADX"]], how="outer", on="Date")

            # Merging the ATR data
            ohlc_renko[ticker] = ohlc_renko[ticker].merge(
                atr.loc[:, ["Date", "ATR"]], how="outer", on="Date")

            # Putting the MACD data into the ohlc_renko frame
            ohlc_renko[ticker]["macd"] = Indicator.MACD(
                ohlc_renko[ticker], 12, 26, 9)[0]
            ohlc_renko[ticker]["macd_sig"] = Indicator.MACD(
                ohlc_renko[ticker], 12, 26, 9)[1]
            ohlc_renko[ticker]["macd_slope"] = Indicator.slope(
                ohlc_renko[ticker]["macd"], 5)
            ohlc_renko[ticker]["macd_sig_slope"] = Indicator.slope(
                ohlc_renko[ticker]["macd_sig"], 5)

            #collated_data[ticker] = ohlc_renko[ticker].iloc[:, [3, 5, 6, 8, 9, 10]]
            collated_data[ticker] = Indicator.Fib_levels(ohlc_renko[ticker])
            #collated_data[ticker] = collated_data[ticker].iloc[:, [3, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]]
            #collated_data[ticker] = collated_data[ticker].iloc[:, [0, 5]]
            collated_data[ticker].set_index("Date", inplace=True)
            collated_data[ticker] = collated_data[ticker].iloc[:, [
                0, 1, 2, 3, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19
            ]]
            tickers_state[ticker] = []
            tickers_ret[ticker] = []
            tickers_signal[ticker] = []

        return interday_data(tickers, collated_data, ohlc_renko, tickers_ret,
                             tickers_state, tickers_signal)
Example #10
0
def application():

    if request.method == 'POST':

        new_request = request.get_json(force=True)
        new_ticker = get_ticker(new_request)

        private_client = AuthenticatedClient(Data.API_Public_Key,
                                             Data.API_Secret_Key,
                                             Data.Passphrase)

        new_order = Order(private_client)
        position = OpenPosition(new_order)
        funds = Capital(private_client)

        indicator = Indicator()
        macd = MACD()

        candle_ticker: str
        stop_time: int
        candle_gra = int

        if position.get_position() and last_instance():

            candle_ticker = new_order.get_key("product_id")
            stop_time = get_time(27976)
            candle_gra = 300

            writer = open(Data.Time, "w")
            writer.write(str(time.time() + 5.0))
            writer.close()

        elif position.get_position() is False:

            candle_ticker = new_ticker
            stop_time = get_time(83925)
            candle_gra = 900

        try:
            indicator.set_candles(product=candle_ticker,
                                  callback=stop_time,
                                  begin=get_time(0),
                                  granularity=candle_gra)
        except ValueError as ve:
            print(ve.with_traceback())
        except NameError as ne:
            print(ne.with_traceback())

        indicator_list = [indicator, macd]
        try:
            for value in indicator_list:
                value.candles = indicator.candles
                value.set_indicator()
                value.set_dates()
        except Exception as e:
            print(e.with_traceback())

        indicator_5m = Indicator()
        macd_5m = MACD()

        if position.get_position() is False:

            if macd.hist[-1] > macd.hist[-2]:
                try:
                    indicator_5m.set_candles(product=new_ticker,
                                             callback=get_time(27976),
                                             begin=get_time(0),
                                             granularity=900)
                except ValueError as ve:
                    print(ve.with_traceback())
        else:
            indicator_5m = indicator
            macd_5m = macd

        volume_5m = VolSMA(timeperiod=20)
        bands2dev_5m = BB()
        bands1dev_5m = BB(ndbevup=1, nbdevdn=1)
        rsi_5m = RSI()
        ema_5m = EMA()
        momentum_5m = Momentum()

        indicators = [
            indicator_5m, macd_5m, volume_5m, bands1dev_5m, bands2dev_5m,
            rsi_5m, ema_5m, momentum_5m
        ]

        try:
            for value in indicators:
                value.candles = indicator_5m.candles
                value.set_indicator()
                value.set_dates()
        except Exception as e:
            print(e.with_traceback())

        strategy_5m = Strategy(indicator_5m, macd_5m, bands1dev_5m,
                               bands2dev_5m, volume_5m, rsi_5m, ema_5m,
                               new_order)

        try:
            strategy_5m.strategy(-1)
        except Exception as e:
            print(e.with_traceback())

        trade_side: str
        trade_product: str
        trade_funds: str

        if (new_order.is_bottom()) and (position.get_position() is False):
            trade_side = "buy"
            trade_product = new_ticker
            trade_funds = funds.get_capital()
        elif (new_order.is_top()) and (position.get_position()):
            trade_side = "sell"
            trade_product = new_order.get_key("product_id")
            trade_funds = get_size(trade_product,
                                   new_order.get_key("filled_size"))

        try:
            new_trade = private_client.place_market_order(
                product_id=trade_product, side=trade_side, funds=trade_funds)
            writer = open(Data.Path, "w")
            writer.write(new_trade['id'])
            writer.close()
            writer = open(Data.Time, "w")
            writer.write(new_trade['done_at'])
            writer.close()
        except NameError as ne:
            print(ne.with_traceback())
        except KeyError as ke:
            print(ke.with_traceback())

        return 'success', 200

    elif request.method == 'GET':
        return redirect('http://3.218.228.129/login')

    else:
        abort(400)
Example #11
0
 def __init__(self, indicator=Indicator(), bol=BB(), order=Order()):
     super(Bollinger, self).__init__(indicator=indicator,
                                     bands_2dev=bol,
                                     order=order)
Example #12
0
 def setup_indicators(self, rover):
     try:
         rover.indicator = NAVIO2LED()
     except Exception:
         rover.indicator = Indicator()