Exemplo n.º 1
0
    def _load(self):
        self._times = self._feeder.get_times()

        # Default Params
        ma_fast_period = 23  # MACD Fast Length
        ma_slow_period = 50  # MACD Slow Length
        cycle_length = 10  # Cycle Length
        d1_length = 3  # 1st %D Length
        d2_length = 3  # 2nd %D Length

        # close
        prices_close = self._feeder.get_prices(200, AppliedPrice.CLOSE)

        # macd
        ema_fast = talib.EMA(prices_close, ma_fast_period)
        ema_slow = talib.EMA(prices_close, ma_slow_period)
        macd = ema_fast - ema_slow

        # stocastic from the macd
        k1 = stochastic.percent_k(macd, cycle_length)
        d1 = talib.EMA(k1, d1_length)

        # stocastic from the macd
        k2 = stochastic.percent_k(d1, cycle_length)
        d2 = talib.EMA(k2, d2_length)

        self._prices = d2[-self._feeder.bar_count:].tolist()
Exemplo n.º 2
0
 def next_calculation(self, candle):
     if self.get_datawindow() is not None:
         self.value['stochastic_percent_k'] = indicator.percent_k(
             self.get_close(), self.params['period'])[-1]
     if self.get_datawindow() is not None:
         self.value['stochastic_percent_d'] = indicator.percent_k(
             self.get_close(), self.params['period'])[-1]
def prepare_data(symbol):

    coin = symbol
    coin_1 = crypto_data(coin)
    df = coin_1

    df['SMA_20'] = sma(df['Close'], 20)
    df['SMA_50'] = sma(df['Close'], 50)

    df['EMA_20'] = ema(df['Close'], 20)
    df['EMA_50'] = ema(df['Close'], 50)

    df['MACD'] = macd(df['Close'], 26, 12)

    df['per_k_stoch_10'] = percent_k(df['Close'], 10)
    df['per_d_stoch_10'] = percent_d(df['Close'], 10)

    df['OBV'] = obv(df['Close'], df['Volume'])

    fp = []
    for price in df['Close']:
        fp.append(price)

    fp.pop(0)
    fp.append(df['Close'].mean())
    df['FP'] = fp

    df_predict = df.tail(1)
    df.drop(df.tail(1).index, inplace=True)

    label = []
    for i in range(len(df)):
        if df['FP'][i] > df['Close'][i]:
            label.append(1)
        else:
            label.append(0)

    df['goes_up'] = label
    df = df.drop(['FP'], axis=1)
    df = df.fillna(df.mean())
    df_predict = df_predict.drop(['FP'], axis=1)

    return df, df_predict
Exemplo n.º 4
0
import matplotlib.pyplot as plt
# %matplotlib inline
from matplotlib import style

style.use('ggplot')
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)

socket = fxcmpy.fxcmpy(config_file='fxcm.cfg')

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

data['percent_k'] = percent_k(data['askclose'], 20)
data['percent_d'] = percent_d(data['askclose'], 20)

fig = plt.figure(figsize=(12, 8))
ax1 = fig.add_subplot(111, xlabel='Date', ylabel='Close')
data['askclose'].plot(ax=ax1, color='r', lw=1)

ss_plot = plt.figure(figsize=(12, 8))
ax3 = ss_plot.add_subplot(111, ylabel='Percent')
data['percent_k'].plot(ax=ax3, color='r')
data['percent_d'].plot(ax=ax3, color='g')
data['ovr'] = .80
data['ovr'].plot(
    ax=ax3,
    color='b',
)
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
Exemplo n.º 6
0
 def test_percent_k_invalid_period(self):
     period = 128
     with self.assertRaises(Exception):
         stochastic.percent_k(self.high_data, self.low_data, self.close_data, period)
Exemplo n.º 7
0
 def test_percent_k_period_10(self):
     period = 10
     percent_k = stochastic.percent_k(self.high_data, self.low_data, self.close_data, period)
     np.testing.assert_array_equal(percent_k, self.percent_k_period_10_expected)
Exemplo n.º 8
0
 def test_percent_k_period_8(self):
     period = 8
     percent_k = stochastic.percent_k(self.data, period)
     np.testing.assert_array_equal(percent_k, self.percent_k_period_8_expected)