def get_indicators(self):
     short_mavg = ti.sma(self.open,
                         int(self.strategy_value['short_window']))
     medium_mavg = ti.sma(self.open,
                          int(self.strategy_value['medium_window']))
     long = ti.sma(self.open, int(self.strategy_value['long_window']))
     return short_mavg, medium_mavg, long
Example #2
0
 def on_candle_update(self):
     ma1 = ti.sma(self.handler.close, period=10)
     ma2 = ti.sma(self.handler.close, period=20)
     if ti.crossover(ma1, ma2)[0]:
         self.handler.buy()
     elif ti.crossover(ma2, ma1)[0]:
         self.handler.sell()
    def get_moving_average_analysis(data, current_moving_average, time_period):

        time_period_unit_moving_average = tulipy.sma(data, time_period)

        # equalize array size
        min_len_arrays = min(len(time_period_unit_moving_average), len(current_moving_average))

        # compute difference between 1 unit values and others ( >0 means currently up the other one)
        values_difference = (current_moving_average[-min_len_arrays:] - time_period_unit_moving_average[-min_len_arrays:])
        values_difference = DataUtil.drop_nan(values_difference)

        if len(values_difference):
            # indexes where current_unit_moving_average crosses time_period_unit_moving_average
            crossing_indexes = TrendAnalysis.get_threshold_change_indexes(values_difference, 0)

            multiplier = 1 if values_difference[-1] > 0 else -1

            # check at least some data crossed 0
            if crossing_indexes:
                normalized_data = DataUtil.normalize_data(values_difference)
                current_value = min(abs(normalized_data[-1])*2, 1)
                if math.isnan(current_value):
                    return 0
                # check <= values_difference.count()-1if current value is max/min
                if current_value == 0 or current_value == 1:
                    chances_to_be_max = TrendAnalysis.get_estimation_of_move_state_relatively_to_previous_moves_length(
                                                                                                    crossing_indexes,
                                                                                                    values_difference)
                    return multiplier*current_value*chances_to_be_max
                # other case: maxima already reached => return distance to max
                else:
                    return multiplier*current_value

        # just crossed the average => neutral
        return 0
Example #4
0
 def sma(self, name='sma', period=5):
     if len(self.df_ohlc) > period:
         self._add_column_to_ohlc(
             name, ti.sma(self.df_ohlc.priceclose.values, period=period))
         return True
     else:
         return False
Example #5
0
def return_last_minimums_sell(stock):
    firstminim = 0
    firstindex = 0

    closing_price_list = stock['Close'].tolist()
    numpyclose = np.asarray(closing_price_list)
    sma = ti.sma(numpyclose, 26)
    list_of_sma = list(np.flip(sma))

    minimlist = [list_of_sma[0]]
    for index, value in enumerate(list_of_sma[1:-1]):
        if value < list_of_sma[index] and value < list_of_sma[index + 2]:
            if firstminim == 0:
                firstminim = value
                firstindex = index
                minimlist.append(firstminim)
                continue
            else:
                if abs((value - firstminim) /
                       firstminim) < 0.02 and (index - firstindex) < 10:
                    firstminim = value
                    firstindex = index
                    continue
                else:
                    firstminim = value
                    firstindex = index
                    minimlist.append(firstminim)

    return [minimlist, list_of_sma]
    def eval_impl(self):
        self.eval_note = 0
        close_values = self.last_candle_data[
            PriceIndexes.IND_PRICE_CLOSE.value]
        sma_values = tulipy.sma(close_values, 6)

        last_ma_value = sma_values[-1]

        if last_ma_value == 0:
            self.eval_note = 0
        else:
            last_price = close_values[-1]
            current_ratio = last_price / last_ma_value
            if current_ratio > 1:
                # last_price > last_ma_value => sell ? => eval_note > 0
                if current_ratio >= 2:
                    self.eval_note = 1
                else:
                    self.eval_note = current_ratio - 1
            elif current_ratio < 1:
                # last_price < last_ma_value => buy ? => eval_note < 0
                self.eval_note = -1 * (1 - current_ratio)
            else:
                self.eval_note = 0

        self.notify_evaluator_thread_managers(self.__class__.__name__)
Example #7
0
def draw_macd_buy(stock, name):
    closing_price_list = stock['Close'].tolist()
    date_list = list(stock.index)

    numpyclose = np.asarray(closing_price_list)
    macd1, macd2, macdhistogram = ti.macd(numpyclose, 8, 17, 9)  # for buy signals it should be 8,17,9
    sma = ti.sma(numpyclose, 17)

    plt.figure(figsize=(15, 8))
    ax1 = plt.subplot(212)
    ax2 = plt.subplot(211, sharex=ax1, title=name)
    numberofactivedays = len(date_list[16:])
    arrangeddates = np.arange(numberofactivedays)
    ax1.plot(arrangeddates, macd1, 'r')
    ax1.plot(arrangeddates, macd2, 'y')
    ax1.bar(arrangeddates, macdhistogram)
    ax1.plot(arrangeddates, [0] * len(date_list[16:]))
    ax2.plot(arrangeddates, closing_price_list[16:])
    ax2.plot(arrangeddates, sma, 'r')
    ax1.set_xticks(np.append(arrangeddates[0::20], arrangeddates[-1]))
    ax2.set_xticks(np.append(arrangeddates[0::20], arrangeddates[-1]))
    ax1.set_xticklabels([date.strftime("%Y-%m-%d") for date in date_list[16:]][0::20] +
                        [[date.strftime("%Y-%m-%d") for date in date_list[16:]][-1]])
    ax2.set_xticklabels([date.strftime("%Y-%m-%d") for date in date_list[16:]][0::20] +
                        [[date.strftime("%Y-%m-%d") for date in date_list[16:]][-1]])
    ax1.tick_params(rotation=30)
    ax2.tick_params(rotation=30)
    plt.show()
Example #8
0
    async def evaluate(self, cryptocurrency, symbol, time_frame, candle_data,
                       candle):
        self.eval_note = commons_constants.START_PENDING_EVAL_NOTE
        if len(candle_data) >= self.long_period_length:
            time_units = [5, self.long_period_length]
            current_moving_average = tulipy.sma(candle_data, 2)
            results = [
                self.get_moving_average_analysis(candle_data,
                                                 current_moving_average,
                                                 time_unit)
                for time_unit in time_units
            ]
            if len(results):
                self.eval_note = numpy.mean(results)
            else:
                self.eval_note = commons_constants.START_PENDING_EVAL_NOTE

            if self.eval_note == 0:
                self.eval_note = commons_constants.START_PENDING_EVAL_NOTE
        await self.evaluation_completed(
            cryptocurrency,
            symbol,
            time_frame,
            eval_time=evaluators_util.get_eval_time(full_candle=candle,
                                                    time_frame=time_frame))
    async def eval_impl(self):
        self.eval_note = 0
        period = 6
        close_values = self.last_candle_data[
            PriceIndexes.IND_PRICE_CLOSE.value]
        if len(close_values) > period:
            sma_values = tulipy.sma(close_values, period)

            last_ma_value = sma_values[-1]

            if last_ma_value == 0:
                self.eval_note = 0
            else:
                last_price = close_values[-1]
                current_ratio = last_price / last_ma_value
                if current_ratio > 1:
                    # last_price > last_ma_value => sell ? => eval_note > 0
                    if current_ratio >= 2:
                        self.eval_note = 1
                    else:
                        self.eval_note = current_ratio - 1
                elif current_ratio < 1:
                    # last_price < last_ma_value => buy ? => eval_note < 0
                    self.eval_note = -1 * (1 - current_ratio)
                else:
                    self.eval_note = 0

            await self.notify_evaluator_task_managers(self.get_name())
 def sma(self, data, period, ba, ohlc):
     series_arr = []
     for item in data[:period]:
         value = round(float(item[ba][ohlc]), 5)
         series_arr.append(value)
     DATA = np.array(series_arr)
     sma = ti.sma(DATA, period=period)
     return sma
Example #11
0
    def test_sma(self):
        expected = np.array([82.426, 82.738, 83.094, 83.318, 83.628,
                             83.778, 84.254, 84.994, 85.574, 86.218,
                             86.804]),

        actual = ti.sma(CLOSE, period=5)

        self.assertTrue(np.allclose(actual, expected))
Example #12
0
    def compute(self, data_dict):

        close = data_dict.get('close')

        open = data_dict.get('open')

        ret = np.log(close / open)

        return ti.sma(ret, self.lookback)
def test_sma(data):
    arr = data["close"].to_numpy(copy=True).astype(float)
    ti_sma = np.round(np.append([np.nan for i in range(9)],
                                ti.sma(arr, period=10)),
                      decimals=3)
    sma = indicator.Indicate(data["close"])\
        .smooth_moving_average(10)['close_sma_10']\
        .astype(float)
    assert np.allclose(ti_sma, sma, atol=1e-03, equal_nan=True)
Example #14
0
def sma_potential_sell(stock):
    closing_price_list = stock['Close'].tolist()
    numpyclose = np.asarray(closing_price_list)
    sma = ti.sma(numpyclose, 26)
    if sma[-50] > sma[-5] > sma[-1] > closing_price_list[
            -1] and closing_price_list[-2] > sma[-2]:
        return True
    else:
        return False
Example #15
0
def sma_potential_buy(stock):
    closing_price_list = stock['Close'].tolist()
    numpyclose = np.asarray(closing_price_list)
    sma = ti.sma(numpyclose, 17)
    if sma[-50] < sma[-5] < sma[-1] < closing_price_list[
            -1] and closing_price_list[-2] < sma[-2]:
        return True
    else:
        return False
 def get_indicators(self):
     short_window = int(self.strategy_value['short_window'])
     medium_window = int(self.strategy_value['medium_window'])
     long_window = int(self.strategy_value['long_window'])
     ma_window_short = int(self.strategy_value['ma_window_short'])
     ma_window_long = int(self.strategy_value['ma_window_long'])
     ultimate = ti.ultosc(self.high, self.low, self.close, short_window,
                          medium_window, long_window)
     ma_long = ti.sma(self.open, ma_window_long)
     ma_short = ti.sma(self.open, ma_window_short)
     min_size = min(ma_long.size, ma_short.size, ultimate.size)
     self.signal_shift = self.open.size - min_size
     cut_u = ultimate.size - min_size
     cut_l = ma_long.size - min_size
     cut_m = ma_short.size - min_size
     ultimate = ultimate[cut_u:]
     ma_long = ma_long[cut_l:]
     ma_short = ma_short[cut_m:]
     return ultimate, ma_short, ma_long
Example #17
0
def test_TA_basics():
    rsi_result = tulipy.rsi(DATA, period=9)
    assert all(74 < v < 86 for v in rsi_result)
    assert len(rsi_result) == 6
    sma_result = tulipy.sma(DATA, period=9)
    assert all(74 < v < 86 for v in sma_result)
    assert len(sma_result) == 7
    bands = tulipy.bbands(DATA, period=9, stddev=2)
    assert all(80 < v < 89 for band in bands for v in band)
    assert len(bands) == 3
Example #18
0
def start():
    while True:
        # [
        #     1499040000000,      // Open time
        #     "0.01634790",       // Open
        #     "0.80000000",       // High
        #     "0.01575800",       // Low
        #     "0.01577100",       // Close
        #     "148976.11427815",  // Volume
        #     1499644799999,      // Close time
        #     "2434.19055334",    // Quote asset volume
        #     308,                // Number of trades
        #     "1756.87402397",    // Taker buy base asset volume
        #     "28.46694368",      // Taker buy quote asset volume
        #     "17928899.62484339" // Ignore
        # ]
        try:
            now = datetime.datetime.now()
            is_close_position()
            if (now.minute == 0 and now.second == 0) or (now.minute == 30 and now.second == 10):
                print(now, 'UPDATE DATA OHLC')
                ohlc = client.futures_klines(symbol=MARKET, interval=Client.KLINE_INTERVAL_30MINUTE)
                close = []
                for row in ohlc:
                    close.append(float(row[4]))
                ma1 = ti.sma(np.array(close), period=10)
                ma2 = ti.sma(np.array(close), period=20)
                if POSITION['price'] == 0:
                    if ti.crossover(ma1, ma2)[0]:
                        create_position(price=float(row[4]), side=Client.SIDE_BUY, date=now)
                    elif ti.crossover(ma2, ma1)[0]:
                        create_position(price=float(row[4]), side=Client.SIDE_SELL, date=now)

            print(now, 'GET POSITION ENTRY_PRICE[{}] ROE[{}] AMOUNT[{}] SIDE[{}]'.format(POSITION['price'],
                                                                                         POSITION['roe'],
                                                                                         POSITION['amount'],
                                                                                         POSITION['side']))
            time.sleep(1)

        except:
            traceback.print_exc()
Example #19
0
def ti_supertrend(
    h: np.ndarray,
    l: np.ndarray,
    c: np.ndarray,
    period: int,
    factor: float,
) -> np.ndarray:

    f_atr = factor * ta.sma(ta.tr(h, l, c), period)

    out_size = len(f_atr)
    slicer = slice(-out_size, None)

    # IMPORTANT!
    h, l, c = h[slicer], l[slicer], c[slicer]

    hl2 = (h + l) / 2

    up = hl2 - f_atr
    dn = hl2 + f_atr

    st = np.empty(out_size)
    dt = np.empty(out_size)
    st[0] = up[0]
    dt[0] = 1

    for i in range(1, len(st)):
        up1 = up[i - 1]
        dn1 = dn[i - 1]
        dt1 = dt[i - 1]
        c1 = c[i - 1]

        if c1 > up1 > up[i]:
            up[i] = up1
        if c1 < dn1 < dn[i]:
            dn[i] = dn1

        if (dt1 < 0 and dn1 < c[i]) or (dt1 > 0 and up1 > c[i]):
            dt1 *= -1
        dt[i] = dt1

        if dt1 > 0:
            st[i] = up[i]
        else:
            st[i] = dn[i]

    ret = np.empty((out_size, 2))
    ret[:, 0] = st
    ret[:, 1] = dt
    return ret
Example #20
0
    def __call__(self, Coin):
        CloseValues = np.array(
            [c[3] for c in Coin.Candlesticks[-(self.slow_sma_period + 20):]])

        if CloseValues.shape[0] < self.slow_sma_period:
            return 0

        slow_SMA = ti.sma(CloseValues, period=self.slow_sma_period)[-1]
        fast_SMA = ti.sma(CloseValues, period=self.fast_sma_period)[-1]

        # BEAR TREND;
        if slow_SMA > fast_SMA:
            RSI_period = self.bear_rsi_period
            score_adjust = self.bear_score_adjust
        else:
            RSI_period = self.bull_rsi_period
            score_adjust = self.bull_score_adjust

        Period = max(1, min(RSI_period, CloseValues.shape[0] - 1))

        RSI = ti.rsi(CloseValues, period=Period)

        return max(min(100, RSI[-1] - score_adjust), -100)
    def eval_impl(self):
        self.eval_note = START_PENDING_EVAL_NOTE
        if len(self.data) > 1:
            time_units = [5, 10]
            current_moving_average = tulipy.sma(
                self.data[PriceIndexes.IND_PRICE_CLOSE.value], 2)
            results = [
                self.get_moving_average_analysis(
                    self.data[PriceIndexes.IND_PRICE_CLOSE.value],
                    current_moving_average, i) for i in time_units
            ]
            self.eval_note = numpy.mean(results)

            if self.eval_note == 0:
                self.eval_note = START_PENDING_EVAL_NOTE
 async def ohlcv_callback(self, exchange: str, exchange_id: str,
                          cryptocurrency: str, symbol: str, time_frame, candle):
     self.eval_note = 0
     new_data = self.get_symbol_candles(exchange, exchange_id, symbol, time_frame). \
         get_symbol_close_candles(20)
     should_eval = symbol not in self.last_candle_data or \
                   not self._compare_data(new_data, self.last_candle_data[symbol])
     self.last_candle_data[symbol] = new_data
     if should_eval:
         if len(self.last_candle_data[symbol]) > self.period:
             self.last_moving_average_values[symbol] = tulipy.sma(self.last_candle_data[symbol],
                                                                  self.period)
             await self._evaluate_current_price(self.last_candle_data[symbol][-1], cryptocurrency, symbol,
                                                evaluators_util.get_eval_time(full_candle=candle,
                                                                              time_frame=time_frame))
    def eval_impl(self):
        self.eval_note = START_PENDING_EVAL_NOTE
        long_period_length = 10
        if len(self.data[PriceIndexes.IND_PRICE_CLOSE.value]) > long_period_length:
            time_units = [5, long_period_length]
            current_moving_average = tulipy.sma(self.data[PriceIndexes.IND_PRICE_CLOSE.value], 2)
            results = [self.get_moving_average_analysis(self.data[PriceIndexes.IND_PRICE_CLOSE.value],
                                                        current_moving_average,
                                                        i)
                       for i in time_units]
            if len(results):
                self.eval_note = numpy.mean(results)
            else:
                self.eval_note = START_PENDING_EVAL_NOTE

            if self.eval_note == 0:
                self.eval_note = START_PENDING_EVAL_NOTE
Example #24
0
def test_sma():
    c = np.random.random(SIZE)
    length = 14

    sma = SMA(length)

    for i in range(sma.offset):
        nan = sma.next(c[i])
        assert np.isnan(nan)

    computed = ta.sma(c, length)

    for i in range(len(computed)):
        actual = sma.next(c[i + sma.offset])
        expected = computed[i]

        assert actual == approx(expected)
def save_macd_buy(stock_name):
    stock = yf.download(tickers=stock_name,
                        interval="1wk",
                        period="2y",
                        threads=True)
    stock.index = stock.index.where(~stock.index.duplicated(),
                                    stock.index + timedelta(1))
    # Remove all the NaN values
    for index, row in stock.iterrows():
        if math.isnan(row["Close"]) or math.isnan(row["Volume"]):
            stock = stock.drop([index])
    closing_price_list = stock['Close'].tolist()
    date_list = list(stock.index)

    numpyclose = np.asarray(closing_price_list)
    macd1, macd2, macdhistogram = ti.macd(
        numpyclose, 8, 17, 9)  # for buy signals it should be 8,17,9
    sma = ti.sma(numpyclose, 17)

    plt.figure(figsize=(15, 8))
    ax1 = plt.subplot(212)
    ax2 = plt.subplot(211, sharex=ax1, title=stock_name)
    numberofactivedays = len(date_list[16:])
    arrangeddates = np.arange(numberofactivedays)
    ax1.plot(arrangeddates, macd1, 'r')
    ax1.plot(arrangeddates, macd2, 'y')
    ax1.bar(arrangeddates, macdhistogram)
    ax1.plot(arrangeddates, [0] * len(date_list[16:]))
    ax1.set(ylabel='MACD')
    ax2.plot(arrangeddates, closing_price_list[16:])
    ax2.plot(arrangeddates, sma, 'r')
    ax2.set(ylabel="Price")

    ax1.set_xticks(np.append(arrangeddates[0::15], arrangeddates[-1]))
    ax2.set_xticks(np.append(arrangeddates[0::15], arrangeddates[-1]))
    ax1.set_xticklabels(
        [date.strftime("%Y-%m-%d") for date in date_list[16:]][0::15] +
        [[date.strftime("%Y-%m-%d") for date in date_list[16:]][-1]])
    ax2.set_xticklabels(
        [date.strftime("%Y-%m-%d") for date in date_list[16:]][0::15] +
        [[date.strftime("%Y-%m-%d") for date in date_list[16:]][-1]])
    ax1.tick_params(rotation=30)
    ax2.tick_params(rotation=30)
    plt.savefig("Support Files/" + stock_name + "-price" + ".png")
    plt.close()
Example #26
0
def test_atr():
    h, l, c = np.random.random((3, SIZE))
    period = 5

    atr = ATR(period)

    for i in range(atr.offset):
        nan = atr.next(h[i], l[i], c[i])
        assert np.isnan(nan)

    computed = ta.sma(ta.tr(h, l, c), period)

    for i in range(len(computed)):
        actual = atr.next(h[i + atr.offset], l[i + atr.offset],
                          c[i + atr.offset])
        expected = computed[i]

        assert actual == approx(expected)
Example #27
0
def calculate_financial_technical_data(comparision_type,comparision_value):
    logger.debug(comparision_value)
    data_list = []
    fin_res=[]
    for i in ohlcv_data2.keys():
        data_list.append(ohlcv_data2[i][str(comparision_value)])
    logger.debug(data_list)
    if comparision_type == 'sma':
        data = ( ti.sma(np.asarray(data_list), period=10) )
        return data
    elif comparision_type is 'stddev':
        #dataaa = ( ti.stddev(np.asarray(data_list), period=5) )
        #logger.debug(dataaa)
        #data = dataaa.tolist()
        fin_res = ti.stddev(np.asarray(data_list), period=5).tolist() 
        return fin_res
    elif comparision_type is 'wma':
        data = ( ti.wma(np.asarray(data_list), period=5) )
        return data
    elif comparision_type is 'zlema':
        data = ( ti.zlema(np.asarray(data_list), period=5) )
        return data
Example #28
0
def financial_technical_analysis():
    comparision_type = str(request.form.get('comparision'))
    comparision_value = str(request.form.get('comparision_data'))

    data_list = []

    for i in ohlcv_data2.keys():
        data_list.append(ohlcv_data2[i][str(comparision_value)])
    if comparision_type == 'sma':
        res = ( ti.sma(np.asarray(data_list), period=20) ).tolist()
        print(res[-1])
        return render_template('binance_tech_analysis_result.html', res = res[-1],comparision_type="Simple Moving Average",comparision_value=comparision_value.upper())
    elif comparision_type == 'stddev':
        res = ti.stddev(np.asarray(data_list), period=20).tolist()
        print(res[-1])
        return render_template('binance_tech_analysis_result.html', res = res[-1],comparision_type="Standard Deviation",comparision_value=comparision_value.upper())
    elif comparision_type == 'wma':
        res = ( ti.wma(np.asarray(data_list), period=20) ).tolist()
        return render_template('binance_tech_analysis_result.html', res = res[-1],comparision_type="Weighted Moving Average",comparision_value=comparision_value.upper())
    elif comparision_type == 'zlema':
        res = ( ti.zlema(np.asarray(data_list), period=20) ).tolist()
        return render_template('binance_tech_analysis_result.html', res = res[-1],comparision_type="Zero-Lag exponential moving average" ,comparision_value=comparision_value.upper())
Example #29
0
    def compute(self, data_dict):

        returns = self.returns.get_numpy()

        return ti.sma(returns, self.lookback)
Example #30
0

#
# for index, row in binance_data.iterrows():
#     CLOSE.append(row.Close)
#     print(row.Close)
#     ma1 = ti.sma(np.array(CLOSE), period=1)
#     ma2 = ti.sma(np.array(CLOSE), period=2)
#     print(ti.crossover(ma1, ma2))

for row in OHLC[::-1]:
    # print(row['close'])
    CLOSE.insert(0, row['close'])
    if len(CLOSE) < 50:
        continue
    ma1 = ti.sma(np.array(CLOSE), period=10)
    ma2 = ti.sma(np.array(CLOSE), period=20)
    # print(ti.crossover(ma1, ma2))
    is_close_position(row)
    if POSITION['price'] > 0:
        continue
    if ti.crossover(ma1, ma2)[0]:
        POSITION['price'] = row['close']
        POSITION['side'] = 'BUY'
        POSITION['date'] = row['date']
    elif ti.crossover(ma2, ma1)[0]:
        POSITION['price'] = row['close']
        POSITION['side'] = 'SELL'
        POSITION['date'] = row['date']

# print(TRADES)