Example #1
0
 def get_analysis(self, data, bollinger_function):
     if bollinger_function == 'upper':
         return bollinger_bands.upper_bollinger_band(
             data, self.params['period'])
     if bollinger_function == 'middle':
         return bollinger_bands.middle_bollinger_band(
             data, self.params['period'])
     if bollinger_function == 'lower':
         return bollinger_bands.lower_bollinger_band(
             data, self.params['period'])
     if bollinger_function == 'bandwidth':
         return bollinger_bands.bandwidth(data, self.params['period'])
     if bollinger_function == 'range':
         return bollinger_bands.bb_range(data, self.params['period'])
     if bollinger_function == 'percent_bandwidth':
         return bollinger_bands.percent_bandwidth(data,
                                                  self.params['period'])
     if bollinger_function == 'percent_b':
         return bollinger_bands.percent_b(data, self.params['period'])
def _get_ta_features(high, low, close, volume, desc):
    """
	Returns a dict containing the technical analysis indicators calculated on the given
	high, low, close and volumes.
	"""
    ta = {}

    # Set numpy to ignore division error and invalid values (since not all features are complete)
    old_settings = np.seterr(divide='ignore', invalid='ignore')
    record_count = len(close)

    # Determine relative moving averages
    for _short, _long in desc['rsma']:
        if record_count < _short or record_count < _long:
            logging.error(
                "get_ta_features: not enough records for rsma (short={}, long={}, records={})"
                .format(_short, _long, record_count))
            continue
        ta['rsma_{}_{}'.format(_short,
                               _long)] = relative_sma(close, _short, _long)
    for _short, _long in desc['rema']:
        if record_count < _short or record_count < _long:
            logging.error(
                "get_ta_features: not enough records for rema (short={}, long={}, records={})"
                .format(_short, _long, record_count))
            continue
        ta['rema_{}_{}'.format(_short,
                               _long)] = relative_ema(close, _short, _long)

    # MACD Indicator
    if 'macd' in desc:
        for _short, _long in desc['macd']:
            if record_count < _short or record_count < _long:
                logging.error(
                    "get_ta_features: not enough records for rema (short={}, long={}, records={})"
                    .format(_short, _long, record_count))
                continue
            ta['macd_{}_{}'.format(
                _short, _long)] = moving_average_convergence_divergence(
                    close, _short, _long)

    # Aroon Indicator
    if 'ao' in desc:
        for _period in desc['ao']:
            if record_count < _period:
                logging.error(
                    "get_ta_features: not enough records for ao (period={}, records={})"
                    .format(_period, record_count))
                continue
            ta['ao_{}'.format(_period)] = aroon_oscillator(close, _period)

    # Average Directional Movement Index (ADX)
    if 'adx' in desc:
        for _period in desc['adx']:
            if record_count < _period:
                logging.error(
                    "get_ta_features: not enough records for adx (period={}, records={})"
                    .format(_period, record_count))
                continue
            ta['adx_{}'.format(_period)] = average_directional_index(
                close, high, low, _period)

    # Difference between Positive Directional Index(DI+) and Negative Directional Index(DI-)
    if 'wd' in desc:
        for _period in desc['wd']:
            if record_count < _period:
                logging.error(
                    "get_ta_features: not enough records for wd (period={}, records={})"
                    .format(_period, record_count))
                continue
            ta['wd_{}'.format(_period)] = \
             positive_directional_index(close, high, low, _period) \
             - negative_directional_index(close, high, low, _period)

    # Percentage Price Oscillator
    if 'ppo' in desc:
        for _short, _long in desc['ppo']:
            if record_count < _short or record_count < _long:
                logging.error(
                    "get_ta_features: not enough records for ppo (short={}, long={}, records={})"
                    .format(_short, _long, record_count))
                continue
            ta['ppo_{}_{}'.format(_short, _long)] = price_oscillator(
                close, _short, _long)

    # Relative Strength Index
    if 'rsi' in desc:
        for _period in desc['rsi']:
            if record_count < _period:
                logging.error(
                    "get_ta_features: not enough records for rsi (period={}, records={})"
                    .format(_period, record_count))
                continue
            ta['rsi_{}'.format(_period)] = relative_strength_index(
                close, _period)

    # Money Flow Index
    if 'mfi' in desc:
        for _period in desc['mfi']:
            if record_count < _period:
                logging.error(
                    "get_ta_features: not enough records for mfi (period={}, records={})"
                    .format(_period, record_count))
                continue
            ta['mfi_{}'.format(_period)] = money_flow_index(
                close, high, low, volume, _period)

    # True Strength Index
    if 'tsi' in desc and len(close) >= 40:
        if record_count < 40:
            logging.error(
                "get_ta_features: not enough records for tsi (period={}, records={})"
                .format(40, record_count))
        else:
            ta['tsi'] = true_strength_index(close)

    if 'boll' in desc:
        for _period in desc['stoch']:
            if record_count < _period:
                logging.error(
                    "get_ta_features: not enough records for boll (period={}, records={})"
                    .format(_period, record_count))
                continue
            ta['boll_{}'.format(_period)] = percent_b(close, _period)

    # Stochastic Oscillator
    if 'stoch' in desc:
        for _period in desc['stoch']:
            if record_count < _period:
                logging.error(
                    "get_ta_features: not enough records for stoch (period={}, records={})"
                    .format(_period, record_count))
                continue
            ta['stoch_{}'.format(_period)] = percent_k(close, _period)
    # ta.py['stoch'] = percent_k(high, low, close, 14)

    # Chande Momentum Oscillator
    ## Not available in ta.py
    if 'cmo' in desc:
        for _period in desc['cmo']:
            if record_count < _period:
                logging.error(
                    "get_ta_features: not enough records for cmo (period={}, records={})"
                    .format(_period, record_count))
                continue
            ta['cmo_{}'.format(_period)] = chande_momentum_oscillator(
                close, _period)

    # Average True Range Percentage
    if 'atrp' in desc:
        for _period in desc['atrp']:
            if record_count < _period:
                logging.error(
                    "get_ta_features: not enough records for atrp (period={}, records={})"
                    .format(_period, record_count))
                continue
            ta['atrp_{}'.format(_period)] = average_true_range_percent(
                close, _period)

    # Percentage Volume Oscillator
    if 'pvo' in desc:
        for _short, _long in desc['pvo']:
            if record_count < _short or record_count < _long:
                logging.error(
                    "get_ta_features: not enough records for pvo (short={}, long={}, records={})"
                    .format(_short, _long, record_count))
                continue
            ta['pvo_{}_{}'.format(_short, _long)] = volume_oscillator(
                volume, _short, _long)

    # Force Index
    if 'fi' in desc:
        fi = force_index(close, volume)
        for _period in desc['fi']:
            if record_count < _period:
                logging.error(
                    "get_ta_features: not enough records for atrp (period={}, records={})"
                    .format(_period, record_count))
                continue
            ta['fi_{}'.format(_period)] = exponential_moving_average(
                fi, _period)

    # Accumulation Distribution Line
    if 'adi' in desc:
        ta['adi'] = accumulation_distribution(close, high, low, volume)

    # On Balance Volume
    if 'obv' in desc:
        ta['obv'] = on_balance_volume(close, volume)

    # Restore numpy error settings
    np.seterr(**old_settings)

    return ta
Example #3
0
count = 10  # count in days in the past
gran = '1h'
symbol = 'BTC/USD'
price_prom = 0.15
params = {"count": count, "granularity": gran}
if __name__ == "__main__":
    df = hlp.get_bitmex(symbol, gran, count, m15=False)
    # dfdt = pd.Series(df['close'].values, index=pd.DatetimeIndex(
    #    start='2017-01-1', periods=len(df['close']), freq='1d'))
    # dfseas = seasonal_decompose(dfdt)
    # finding BB%
    dfflist = df['close'].tolist()
    dfreturns = hlp.returns(df['close'])
    hlp.plot_histogram(dfreturns, 20)
    print(df.head())
    bbl = bollinger_bands.percent_b(dfflist, 70, 2.0)
    bbdivs_bear, bbdivs_bull, bpf, pbf = hlp.divergence2(bbl,
                                                         df,
                                                         prominence=5,
                                                         hei=20)
    # SRSI and its peaks/bottoms
    K, D = hlp.StochRSI(df, price='close')
    kdivs_bear, kdivs_bull, kbf, kpf = hlp.divergence2(K,
                                                       df,
                                                       prominence=5,
                                                       hei=20)

    # peaks of close : resistance and support levels
    dfflist2 = df['close'].values
    prom = price_prom * (np.max(dfflist2) - np.min(dfflist2))
    print(prom)
Example #4
0
 def test_percent_b_invalid_period(self):
     period = 128
     with self.assertRaises(Exception) as cm:
         bollinger_bands.percent_b(self.data, period)
     expected = "Error: data_len < period"
     self.assertEqual(str(cm.exception), expected)
Example #5
0
 def test_percent_b_period_6(self):
     period = 6
     percent_b = bollinger_bands.percent_b(self.data, period)
     np.testing.assert_array_equal(percent_b,
                                   self.percent_b_period_6_expected)
Example #6
0
# In[5]:


data = socket.get_candles(instrument = 'GBP/USD', period = 'D1', start = dt.datetime(2016,1,1), end = dt.datetime(2018, 6, 10))


# In[6]:


#Define useful variables


data['upper_band'] = ubb(data['askclose'], period = 20)
data['mid_band'] = mbb(data['askclose'], period = 20 )
data['lower_band'] = lbb(data['askclose'], period = 20 )
data['percent_b'] = percent_b(data['askclose'], period =20)
data


# In[7]:


fig = plt.figure(figsize=(12,8))

ax1 = fig.add_subplot(111,  xlabel = 'Date',ylabel='Close')


data['askclose'].plot(ax=ax1, color='r', lw=1)
data['upper_band'].plot(ax=ax1, color = 'b', lw= 1)
data['mid_band'].plot(ax=ax1, color = 'g', lw= 1)
data['lower_band'].plot(ax=ax1, color = 'y', lw= 1)