Exemplo n.º 1
0
def get_data(symbol):
    print 'Getting data'
    # Technical Indicators
    ti = TechIndicators(key='4BTFICZGTPWZRRQS', output_format='pandas')
    sma, _ = ti.get_sma(symbol=symbol, interval='daily')
    wma, _ = ti.get_wma(symbol='SPX', interval='daily')
    ema, _ = ti.get_ema(symbol=symbol, interval='daily')
    macd, _ = ti.get_macd(symbol=symbol, interval='daily')
    stoch, _ = ti.get_stoch(symbol=symbol, interval='daily')
    rsi, _ = ti.get_rsi(symbol=symbol, interval='daily')
    adx, _ = ti.get_adx(symbol=symbol, interval='daily')
    cci, _ = ti.get_cci(symbol=symbol, interval='daily')
    aroon, _ = ti.get_aroon(symbol=symbol, interval='daily')
    bbands, _ = ti.get_bbands(symbol='SPX', interval='daily')
    ad, _ = ti.get_ad(symbol='SPX', interval='daily')
    obv, _ = ti.get_obv(symbol='SPX', interval='daily')
    mom, _ = ti.get_mom(symbol='SPX', interval='daily')
    willr, _ = ti.get_willr(symbol='SPX', interval='daily')
    tech_ind = pd.concat([sma, ema, macd, stoch, rsi, adx, cci, aroon, bbands, ad, obv, wma, mom, willr], axis=1)

    print 'Getting time series'
    ts = TimeSeries(key='4BTFICZGTPWZRRQS', output_format='pandas')
    close = ts.get_daily(symbol=symbol, outputsize='full')[0].rename(columns={'4. close': 'close'})['close']
    direction = (close > close.shift()).astype(int)
    target = direction.shift(-1).fillna(0).astype(int)
    target.name = 'target'

    data = pd.concat([tech_ind, close, target], axis=1)

    return data
Exemplo n.º 2
0
def get_daily_technical(stock, indicator, API_key, period=-1):
    ti = TechIndicators(key=API_key, output_format='pandas')
    if indicator == "bband":
        if (period <= 0):
            period = 20
        data, meta_data = ti.get_bbands(symbol=stock, interval='daily', time_period=period)
    elif indicator == "macd":
        data, meta_data = ti.get_macd(symbol=stock, interval='daily')
    elif indicator == "rsi":
        if (period <= 0):
            period = 14
        data, meta_data = ti.get_rsi(symbol=stock, interval='daily', time_period=period)
    elif indicator == "cci":
        if (period <= 0):
            period = 20
        data, meta_data = ti.get_cci(symbol=stock, interval='daily', time_period=period)
    elif indicator == "aroon":
        if (period <= 0):
            period = 14
        data, meta_data = ti.get_aroon(symbol=stock, interval='daily', time_period=period)
    elif indicator == "ad":
        data, meta_data = ti.get_ad(symbol=stock, interval='daily')
    elif indicator == "adx":
        if (period <= 0):
            period = 20
        data, meta_data = ti.get_adx(symbol=stock, interval='daily', time_period=period)
    elif indicator == "sma":
        if (period <= 0):
            period = 40
        data, meta_data = ti.get_sma(symbol=stock, interval='daily', time_period=period)
    else:
        sys.exit('Failed to input a valid indicator')

    return data, meta_data
Exemplo n.º 3
0
def get_data(symbol):

    # Technical Indicators
    ti = TechIndicators(key='YOUR_API_KEY', output_format='pandas')
    sma, _ = ti.get_sma(symbol=symbol, interval='daily')
    wma, _ = ti.get_wma(symbol=symbol, interval='daily')
    ema, _ = ti.get_ema(symbol=symbol, interval='daily')
    macd, _ = ti.get_macd(symbol=symbol, interval='daily')
    stoch, _ = ti.get_stoch(symbol=symbol, interval='daily')
    rsi, _ = ti.get_rsi(symbol=symbol, interval='daily')
    adx, _ = ti.get_adx(symbol=symbol, interval='daily')
    cci, _ = ti.get_cci(symbol=symbol, interval='daily')
    aroon, _ = ti.get_aroon(symbol=symbol, interval='daily')
    bbands, _ = ti.get_bbands(symbol=symbol, interval='daily')
    ad, _ = ti.get_ad(symbol=symbol, interval='daily')
    obv, _ = ti.get_obv(symbol=symbol, interval='daily')
    mom, _ = ti.get_mom(symbol=symbol, interval='daily')
    willr, _ = ti.get_willr(symbol=symbol, interval='daily')
    tech_ind = pd.concat([sma, ema, macd, stoch, rsi, adx, cci, aroon, bbands, ad, obv, wma, mom, willr], axis=1)

    ts = TimeSeries(key='YOUR_API_KEY', output_format='pandas')
    close = ts.get_daily(symbol=symbol, outputsize='full')[0]['close']   # compact/full
    direction = (close > close.shift()).astype(int)
    target = direction.shift(-1).fillna(0).astype(int)
    target.name = 'target'

    data = pd.concat([tech_ind, close, target], axis=1)

    return data
def get_data(symbol):

    # API KEY: 51N1JMO66W56AYA3
    ti = TechIndicators(key='51N1JMO66W56AYA3', output_format='pandas')
    sma, _ = ti.get_sma(symbol=symbol, interval='daily')
    wma, _ = ti.get_wma(symbol=symbol, interval='daily')
    ema, _ = ti.get_ema(symbol=symbol, interval='daily')
    macd, _ = ti.get_macd(symbol=symbol, interval='daily')
    stoch, _ = ti.get_stoch(symbol=symbol, interval='daily')
    #  Alpha Vantage Times out for more than 5 request
    time.sleep(65)
    rsi, _ = ti.get_rsi(symbol=symbol, interval='daily')
    adx, _ = ti.get_adx(symbol=symbol, interval='daily')
    cci, _ = ti.get_cci(symbol=symbol, interval='daily')
    aroon, _ = ti.get_aroon(symbol=symbol, interval='daily')
    bbands, _ = ti.get_bbands(symbol=symbol, interval='daily')
    time.sleep(65)
    ad, _ = ti.get_ad(symbol=symbol, interval='daily')
    obv, _ = ti.get_obv(symbol=symbol, interval='daily')
    mom, _ = ti.get_mom(symbol=symbol, interval='daily')
    willr, _ = ti.get_willr(symbol=symbol, interval='daily')
    time.sleep(65)
    tech_ind = pd.concat([
        sma, ema, macd, rsi, adx, cci, aroon, bbands, ad, obv, wma, mom, willr,
        stoch
    ],
                         axis=1)

    ts = TimeSeries(key='51N1JMO66W56AYA3', output_format='pandas')
    close2 = ts.get_daily(symbol=symbol, outputsize='full')
    close = ts.get_daily(symbol=symbol, outputsize='full')[0]['4. close']
    direction = (close > close.shift()).astype(int)
    target = direction.shift(-1).fillna(0).astype(int)
    target.name = 'target'

    data = pd.concat([tech_ind, close, target], axis=1)

    return data
Exemplo n.º 5
0
    def stockIndicators(self):
        ti = TechIndicators(key=self.apiKey, output_format='pandas')

        if (self.stockIndi == "sma"):
            ts = TimeSeries(key=self.apiKey, output_format='pandas')
            data, meta_data = ts.get_monthly(symbol=self.stockName)
            dataIndi, meta_dataIndi = ti.get_sma(symbol=self.stockName,
                                                 time_period=30)

        elif (self.stockIndi == "ema"):
            ts = TimeSeries(key=self.apiKey, output_format='pandas')
            data, meta_data = ts.get_monthly(symbol=self.stockName)
            dataIndi, meta_dataIndi = ti.get_ema(symbol=self.stockName,
                                                 time_period=30)

        elif (self.stockIndi == "vwap"):
            ts = TimeSeries(key=self.apiKey, output_format='pandas')
            data, meta_data = ts.get_monthly(symbol=self.stockName)
            dataIndi, meta_dataIndi = ti.get_vwap(symbol=self.stockName,
                                                  time_period=30)

        elif (self.stockIndi == "macd"):
            ts = TimeSeries(key=self.apiKey, output_format='pandas')
            data, meta_data = ts.get_monthly(symbol=self.stockName)
            dataIndi, meta_dataIndi = ti.get_macd(symbol=self.stockName,
                                                  time_period=30)

        elif (self.stockIndi == "obv"):
            ts = TimeSeries(key=self.apiKey, output_format='pandas')
            data, meta_data = ts.get_monthly(symbol=self.stockName)
            dataIndi, meta_dataIndi = ti.get_obv(symbol=self.stockName,
                                                 time_period=30)

        elif (self.stockIndi == "ad"):
            ts = TimeSeries(key=self.apiKey, output_format='pandas')
            data, meta_data = ts.get_monthly(symbol=self.stockName)
            dataIndi, meta_dataIndi = ti.get_ad(symbol=self.stockName,
                                                time_period=30)

        elif (self.stockIndi == "bbands"):
            ts = TimeSeries(key=self.apiKey, output_format='pandas')
            data, meta_data = ts.get_monthly(symbol=self.stockName)
            dataIndi, meta_dataIndi = ti.get_bbands(symbol=self.stockName,
                                                    time_period=30)

        elif (self.stockIndi == "aroon"):
            ts = TimeSeries(key=self.apiKey, output_format='pandas')
            data, meta_data = ts.get_monthly(symbol=self.stockName)
            dataIndi, meta_dataIndi = ti.get_aroon(symbol=self.stockName,
                                                   time_period=30)

        elif (self.stockIndi == "cci"):
            ts = TimeSeries(key=self.apiKey, output_format='pandas')
            data, meta_data = ts.get_monthly(symbol=self.stockName)
            dataIndi, meta_dataIndi = ti.get_cci(symbol=self.stockName,
                                                 time_period=30)

        elif (self.stockIndi == "adx"):
            ts = TimeSeries(key=self.apiKey, output_format='pandas')
            data, meta_data = ts.get_monthly(symbol=self.stockName)
            dataIndi, meta_dataIndi = ti.get_adx(symbol=self.stockName,
                                                 time_period=30)

        elif (self.stockIndi == "rsi"):
            ts = TimeSeries(key=self.apiKey, output_format='pandas')
            data, meta_data = ts.get_monthly(symbol=self.stockName)
            dataIndi, meta_dataIndi = ti.get_rsi(symbol=self.stockName,
                                                 time_period=30)

        elif (self.stockIndi == "stoch"):
            ts = TimeSeries(key=self.apiKey, output_format='pandas')
            data, meta_data = ts.get_monthly(symbol=self.stockName)
            dataIndi, meta_dataIndi = ti.get_stoch(symbol=self.stockName,
                                                   time_period=30)

        return data, dataIndi
Exemplo n.º 6
0
macd, meta_data_macd = ti.get_macd(symbol=stock,interval=t_period, series_type= series_type)
print macd.shape
#7
stoch, meta_data_stoch = ti.get_stoch(symbol=stock, interval=t_period)
print stoch.shape
#8
adx, meta_data_adx = ti.get_adx(symbol=stock, interval=t_period)
print adx.shape
#9
cci, meta_data_cci = ti.get_cci(symbol=stock, interval=t_period)
print cci.shape
#10
aroon, meta_data_aroon = ti.get_aroon(symbol=stock, interval=t_period, series_type=series_type)
print aroon.shape
#11
ad, meta_data_ad = ti.get_ad(symbol=stock, interval=t_period)
print ad.shape
#12
obv, meta_data_obv = ti.get_obv(symbol=stock, interval=t_period)
print obv.shape
#13
mom, meta_data_mom = ti.get_mom(symbol=stock, interval=t_period, series_type= series_type)
#14
willr, meta_data_willr = ti.get_willr(symbol=stock, interval=t_period)


result = data.join(bbands, how='left').join(ema , how='left').join( wma, how='left').join(sma , how='left').join(rsi , how='left').join(macd , how='left').join(stoch , how='left').join( adx, how='left').join(cci , how='left').join(aroon , how='left').join(ad, how='left').join(obv,how='left').join(mom,how='left').join(willr,how='left')   # join at the end
result['label'] = np.where(result['trend']>= 0, 1, 0) # 1 price-up and 0 price-down
del result["trend"]
#print result
print result.columns.values
Exemplo n.º 7
0
def get_technical(symbol, is_save=False):
    """
    Esta función es para descargar todos los indicadores técnicos.
    Si usamos una API_KEY gratuita de ALPHA VANTAGE tenemos que
    descomentar los time.sleep() de la función para que no de un
    problema de peticiones; en el caso de una API_KEY premium no haría
    falta descomentarlo.

    Parámetros:
    ----------
        symbol str:
            Nombre de la acción en bolsa.
        is_save bool:
            Booleano para decidir si guardar o no los datos
            descargados. Por defecto False no guarda los
            datos descargados
    """
    try:
        # Comprueba si ya existe o no el archivo y en el caso de que
        # si exista guarda solo los días que no estén descargados
        if os.path.isfile(f"{c.PATH_SAVE_TECH}{symbol}.csv"):
            df = pd.read_csv(f"{c.PATH_SAVE_TECH}{symbol}.csv",
                             names=c.COLUMNS)
            df = df[df['symbol'] == symbol]
            df['date'] = pd.to_datetime(df['date'])
            ld = df['date'].tail(1)
            last = datetime(ld.dt.year, ld.dt.month, ld.dt.day)
        else:
            last = None

        techindc = list()

        # Descarga los datos de indicadores técnicos.
        ti = TechIndicators(key=c.ALPHA_VAN_KEY, output_format='pandas')
        init = time.time()
        macd = ti.get_macd(symbol, interval='daily')[0]
        techindc.append(macd)

        stoch = ti.get_stoch(symbol, interval='daily')[0]
        techindc.append(stoch)

        ad = ti.get_ad(symbol, interval='daily')[0]
        techindc.append(ad)

        obv = ti.get_obv(symbol, interval='daily')[0]
        techindc.append(obv)

        #    time.sleep(60)

        sma = ti.get_sma(symbol, interval='daily', time_period=50)[0]
        sma.columns = [f"{c}50" for c in sma.columns]
        techindc.append(sma)

        bbands = ti.get_bbands(symbol, interval='daily', time_period=28)[0]
        bbands.columns = [f"{c}28" for c in bbands.columns]
        techindc.append(bbands)

        for tp in c.TIME_PERIOD:

            rsi = ti.get_rsi(symbol, interval='daily', time_period=tp)[0]
            rsi.columns = [f"{c}{tp}" for c in rsi.columns]
            techindc.append(rsi)

            adx = ti.get_adx(symbol, interval='daily', time_period=tp)[0]
            adx.columns = [f"{c}{tp}" for c in adx.columns]
            techindc.append(adx)

            #        time.sleep(60)

            cci = ti.get_cci(symbol, interval='daily', time_period=tp)[0]
            cci.columns = [f"{c}{tp}" for c in cci.columns]
            techindc.append(cci)

            aroon = ti.get_aroon(symbol, interval='daily', time_period=tp)[0]
            aroon.columns = [f"{c}{tp}" for c in aroon.columns]
            techindc.append(aroon)

        df_techindc = pd.concat(techindc, axis=1, join='inner')
        df_techindc.reset_index(inplace=True)
        df_techindc['symbol'] = symbol

        if last is not None:
            df_techindc = df_techindc[df_techindc['date'] > last]

        # Guardar los datos
        if is_save:
            df_techindc[c.COLUMNS_TECH].to_csv(
                f"{c.PATH_SAVE_TECH}{symbol}.csv",
                mode='a',
                index=False,
                header=False)
    except:
        LOGGER.warning(f"Ticker {symbol} ha fallado.")
Exemplo n.º 8
0
def technicalIndicators(API_key,ticker):
  from alpha_vantage.techindicators import TechIndicators
  import matplotlib.pyplot as plt
  import mplfinance as mpf

  ti=TechIndicators(key=API_key, output_format='pandas')
  option=input('1. SMA\n2. EMA\n3. VWAP\n4. MACD\n5. STOCH\n6. RSI\n7. ADX\n8. CCI\n9. AROON\n10. BBANDS\n11. AD\n12. OBV\n').lower()

  if option=='sma' or option=='1':
    interval=int(input("Enter the interval:\n\t1. 1 minute\n\t2. 5 minutes\n\t3. 15 minutes\n\t4. 30 minutes\n\t5. 60 minutes\n\t6. daily \n\t7. weekly\n\t8. monthly\n"))
    intervalList=['','1min','5min','15min','30min','60min','daily','weekly','monthly']
    timeperiod=int(input('Enter Time Period\n'))
    ser=int(input('Enter the series:\n\t1. close\n\t2. open\n\t3. low\n\t4. high\n'))
    series=['','close','open','low','high']
    data=ti.get_sma(symbol=ticker, interval=intervalList[interval], time_period=timeperiod, series_type=series[ser])[0]
    data.columns = ['SMA']
    data.index.name ="Date"
    mpf.plot(data,
             type='candle', 
             title=f'SMA for the {ticker} stock',
             mav=(20), 
             volume=True, 
             tight_layout=True,
             style='yahoo')
    mpf.plot(data,type='line', volume=True)
    return data
    
  elif option=='ema' or option=='2':
    interval=int(input("Enter the interval:\n\t1. 1 minute\n\t2. 5 minutes\n\t3. 15 minutes\n\t4. 30 minutes\n\t5. 60 minutes\n\t6. daily \n\t7. weekly\n\t8. monthly\n"))
    intervalList=['','1min','5min','15min','30min','60min','daily','weekly','monthly']
    timeperiod=int(input('Enter Time Period\n'))
    ser=int(input('Enter the series:\n\t1. close\n\t2. open\n\t3. low\n\t4. high\n'))
    series=['','close','open','low','high']
    data=ti.get_ema(symbol=ticker, interval=intervalList[interval], time_period=timeperiod, series_type=series[ser])[0]
    data.plot()
    plt.title(f'EMA for the {ticker} stock')
    plt.tight_layout()
    plt.grid()
    plt.show()
    return data

  elif option=='vwap' or option=='3':
    interval=int(input("Enter the interval:\n\t1. 1 minute\n\t2. 5 minutes\n\t3. 15 minutes\n\t4. 30 minutes\n\t5. 60 minutes\n"))
    intervalList=['','1min','5min','15min','30min','60min']
    data=ti.get_vwap(symbol=ticker, interval=intervalList[interval])[0]
    data.plot()
    plt.title(f'VWAP for the {ticker} stock')
    plt.tight_layout()
    plt.grid()
    plt.show()
    return data

  elif option=='macd' or option=='4':
    interval=int(input("Enter the interval:\n\t1. 1 minute\n\t2. 5 minutes\n\t3. 15 minutes\n\t4. 30 minutes\n\t5. 60 minutes\n\t6. daily \n\t7. weekly\n\t8. monthly\n"))
    intervalList=['','1min','5min','15min','30min','60min','daily','weekly','monthly']
    ser=int(input('Enter the series:\n\t1. close\n\t2. open\n\t3. low\n\t4. high\n'))
    series=['','close','open','low','high']
    data=ti.get_macd(symbol=ticker, interval=intervalList[interval], series_type=series[ser])[0]
    data.plot()
    plt.title(f'MACD for the {ticker} stock')
    plt.tight_layout()
    plt.grid()
    plt.show()
    return data

  elif option=='stoch' or option=='5':
    interval=int(input("Enter the interval:\n\t1. 1 minute\n\t2. 5 minutes\n\t3. 15 minutes\n\t4. 30 minutes\n\t5. 60 minutes\n\t6. daily \n\t7. weekly\n\t8. monthly\n"))
    intervalList=['','1min','5min','15min','30min','60min','daily','weekly','monthly']
    data=ti.get_stoch(symbol=ticker, interval=intervalList[interval])[0]
    data.plot()
    plt.title(f'STOCH for the {ticker} stock')
    plt.tight_layout()
    plt.grid()
    plt.show()
    return data

  elif option=='rsi' or option=='6':
    interval=int(input("Enter the interval:\n\t1. 1 minute\n\t2. 5 minutes\n\t3. 15 minutes\n\t4. 30 minutes\n\t5. 60 minutes\n\t6. daily \n\t7. weekly\n\t8. monthly\n"))
    intervalList=['','1min','5min','15min','30min','60min','daily','weekly','monthly']
    timeperiod=int(input('Enter Time Period\n'))
    ser=int(input('Enter the series:\n\t1. close\n\t2. open\n\t3. low\n\t4. high\n'))
    series=['','close','open','low','high']
    data=ti.get_rsi(symbol=ticker, interval=intervalList[interval], time_period=timeperiod, series_type=series[ser])[0]
    data.plot()
    plt.title(f'RSI for the {ticker} stock')
    plt.tight_layout()
    plt.grid()
    plt.show()
    return data

  elif option=='adx' or option=='7':
    interval=int(input("Enter the interval:\n\t1. 1 minute\n\t2. 5 minutes\n\t3. 15 minutes\n\t4. 30 minutes\n\t5. 60 minutes\n\t6. daily \n\t7. weekly\n\t8. monthly\n"))
    intervalList=['','1min','5min','15min','30min','60min','daily','weekly','monthly']
    timeperiod=int(input('Enter Time Period\n'))
    data=ti.get_adx(symbol=ticker, interval=intervalList[interval], time_period=timeperiod)[0]
    data.plot()
    plt.title(f'ADX for the {ticker} stock')
    plt.tight_layout()
    plt.grid()
    plt.show()
    return data

  elif option=='cci' or option=='8':
    interval=int(input("Enter the interval:\n\t1. 1 minute\n\t2. 5 minutes\n\t3. 15 minutes\n\t4. 30 minutes\n\t5. 60 minutes\n\t6. daily \n\t7. weekly\n\t8. monthly\n"))
    intervalList=['','1min','5min','15min','30min','60min','daily','weekly','monthly']
    timeperiod=int(input('Enter Time Period\n'))
    data=ti.get_cci(symbol=ticker, interval=intervalList[interval], time_period=timeperiod)[0]
    data.plot()
    plt.title(f'CCI for the {ticker} stock')
    plt.tight_layout()
    plt.grid()
    plt.show()
    return data

  elif option=='aroon' or option=='9':
    interval=int(input("Enter the interval:\n\t1. 1 minute\n\t2. 5 minutes\n\t3. 15 minutes\n\t4. 30 minutes\n\t5. 60 minutes\n\t6. daily \n\t7. weekly\n\t8. monthly\n"))
    intervalList=['','1min','5min','15min','30min','60min','daily','weekly','monthly']
    timeperiod=int(input('Enter Time Period'))
    data=ti.get_aroon(symbol=ticker, interval=intervalList[interval], time_period=timeperiod)[0]
    data.plot()
    plt.title(f'AROON for the {ticker} stock')
    plt.tight_layout()
    plt.grid()
    plt.show()
    return data
    
  elif option=='bbands' or option=='10':
    interval=int(input("Enter the interval:\n\t1. 1 minute\n\t2. 5 minutes\n\t3. 15 minutes\n\t4. 30 minutes\n\t5. 60 minutes\n\t6. daily \n\t7. weekly\n\t8. monthly\n"))
    intervalList=['','1min','5min','15min','30min','60min','daily','weekly','monthly']
    timeperiod=int(input('Enter Time Period\n'))
    ser=int(input('Enter the series:\n\t1. close\n\t2. open\n\t3. low\n\t4. high\n'))
    series=['','close','open','low','high']
    data=ti.get_bbands(symbol=ticker, interval=intervalList[interval], time_period=timeperiod, series_type=series[ser])[0]
    data.plot()
    plt.title(f'BBANDS for the {ticker} stock')
    plt.tight_layout()
    plt.grid()
    plt.show()
    return data

  elif option=='ad' or option=='11':
    interval=int(input("Enter the interval:\n\t1. 1 minute\n\t2. 5 minutes\n\t3. 15 minutes\n\t4. 30 minutes\n\t5. 60 minutes\n\t6. daily \n\t7. weekly\n\t8. monthly\n"))
    intervalList=['','1min','5min','15min','30min','60min','daily','weekly','monthly']
    data=ti.get_ad(symbol=ticker, interval=intervalList[interval])[0]
    data.plot()
    plt.title(f'AD for the {ticker} stock')
    plt.tight_layout()
    plt.grid()
    plt.show()
    return data

  elif option=='obv' or option=='12':
    interval=int(input("Enter the interval:\n\t1. 1 minute\n\t2. 5 minutes\n\t3. 15 minutes\n\t4. 30 minutes\n\t5. 60 minutes\n\t6. daily \n\t7. weekly\n\t8. monthly\n"))
    intervalList=['','1min','5min','15min','30min','60min','daily','weekly','monthly']
    data=ti.get_obv(symbol=ticker, interval=intervalList[interval])[0]
    data.plot()
    plt.title(f'OBV for the {ticker} stock')
    plt.tight_layout()
    plt.grid()
    plt.show()
    return data

  else:
    print("CANNOT RECOGNIZE")
Exemplo n.º 9
0
def preds(api_key):
    df = pd.read_csv('GOOGL.csv', index_col='Date')
    preds = pd.DataFrame()
    for i in np.arange(start=1, stop=6):
        if preds.empty:
            preds = pd.DataFrame(data=df['close'].pct_change(1))
            preds.columns = ['today']
        else:
            lags = pd.DataFrame(df['close'].pct_change(i))
            lags.columns = ['lag{}'.format(i)]
            preds = preds.join(lags)

    preds = preds.join(df['volume'])
    preds = preds.join(df['close'])
    preds['dir'] = (preds['close'] > preds['close'].shift(1)).shift(-1)

    filename = 'GOOGL-lags.csv'
    try:
        preds.to_csv('{}'.format(filename))
        print('GOOGL lags saved successfully as "{}"'.format(filename))
    except:
        print('Unable to save "{}"'.format(filename))

    ti = TechIndicators(key=api_key, output_format='pandas')
    sma, _ = ti.get_sma(symbol='GOOGL', interval='daily', series_type='close')
    ema, _ = ti.get_ema(symbol='GOOGL', interval='daily', series_type='close')
    wma, _ = ti.get_wma(symbol='GOOGL', interval='daily', series_type='close')
    trima, _ = ti.get_trima(symbol='GOOGL',
                            interval='daily',
                            series_type='close')
    kama, _ = ti.get_kama(symbol='GOOGL',
                          interval='daily',
                          series_type='close')
    macd, _ = ti.get_macd(symbol='GOOGL',
                          interval='daily',
                          series_type='close')
    rsi, _ = ti.get_rsi(symbol='GOOGL', interval='daily', series_type='close')
    adx, _ = ti.get_adx(symbol='GOOGL', interval='daily')
    apo, _ = ti.get_apo(symbol='GOOGL', interval='daily', series_type='close')
    stoch, _ = ti.get_stoch(symbol='GOOGL', interval='daily')
    ppo, _ = ti.get_ppo(symbol='GOOGL', interval='daily')
    mom, _ = ti.get_mom(symbol='GOOGL', interval='daily', series_type='close')
    cci, _ = ti.get_cci(symbol='GOOGL', interval='daily')
    aroon, _ = ti.get_aroon(symbol='GOOGL',
                            interval='daily',
                            series_type='close')
    mfi, _ = ti.get_mfi(symbol='GOOGL', interval='daily', series_type='close')
    dx, _ = ti.get_dx(symbol='GOOGL', interval='daily', series_type='close')
    ad, _ = ti.get_ad(symbol='GOOGL', interval='daily')
    obv, _ = ti.get_obv(symbol='GOOGL', interval='daily')

    filename2 = 'GOOGL-techs.csv'
    try:
        preds_test = pd.concat([
            sma, ema, wma, trima, kama, macd, rsi, adx, apo, stoch, ppo, mom,
            cci, aroon, mfi, dx, ad, obv
        ],
                               axis=1)
        pd.DataFrame(preds_test).to_csv('{}'.format(filename2))
        print('Google techs saved as successfully as "{}"'.format(filename2))
    except:
        print('Unable to save "{}"'.format(filename2))
class RealTimeApi(object):
    def __init__(self, symbol, api_key='KHMFAMB5CA0XGKXO'):
        self.api_key = api_key
        self.ticker = symbol
        self.ts = TimeSeries(api_key)
        self.ti = TechIndicators(api_key)
        self.sp = SectorPerformances(api_key)
        self.counter = 0
        self.MAX_API_CALL = 500

    def create_real_time_stock_dataframe(self):
        """
        Take the return of the real time stock api call and converts the return into a dataframe
        :return: Dataframe of new stock data
        """
        real_time_data = self.get_time_series_daily()[0]
        column_list = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume']
        new_stock_data = []
        for sd in real_time_data:
            date = sd.split(' ')[0]
            new_stock_data.append(
                (date, real_time_data[sd]['1. open'],
                 real_time_data[sd]['2. high'], real_time_data[sd]['3. low'],
                 real_time_data[sd]['4. close'],
                 real_time_data[sd]['5. volume']))

        return pd.DataFrame(new_stock_data, columns=column_list)

    def get_intra_day_data(self, interval='1min'):
        """
        Take the return of the real time stock api call and converts the return into a dataframe
        :return: Dataframe of new stock data
        """
        real_time_data = self.get_time_series_intraday(interval='1min')[0]
        column_list = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume']
        new_stock_data = []
        for sd in real_time_data:
            date = sd.split(' ')[0]
            new_stock_data.append(
                (date, real_time_data[sd]['1. open'],
                 real_time_data[sd]['2. high'], real_time_data[sd]['3. low'],
                 real_time_data[sd]['4. close'],
                 real_time_data[sd]['5. volume']))

        return pd.DataFrame(new_stock_data, columns=column_list)

    def _counter(self):
        """
        Utility function that keeps track of how many API calls are made. Limit is
        5 per minute and no more then 500 per day per api_key. This function only
        will track api calls and raise an exception when the count reaches the max
        count of 500.
        """
        self.counter += 1
        if self.counter <= self.MAX_API_CALL:
            string = 'API call has been made'
            # print(string)
            pass
        else:
            string = 'You have reached the limit of the API calls. '.format(
                x=self.MAX_API_CALL)
            # print(string)
            raise ValueError('Too many API calls have been made today.')

    def _get_counter(self):
        return 'Current API call counter is at: {}'.format(self.counter)

    def get_time_series_intraday(self,
                                 interval='1min',
                                 outputsize='compact',
                                 datatype='json'):
        """
        This API returns intraday time series (timestamp, open, high, low, close,
        volume) of the equity specified. API Parameters
        Required: symbol
            The name of the equity of your choice. For example: symbol=MSFT

        Required: interval
            Time interval between two consecutive data points in the time series.
            The following values are supported: 1min, 5min, 15min, 30min, 60min

        Optional: outputsize
            By default, outputsize=compact. Strings compact and full are accepted
            with the following specifications: compact returns only the latest 100
            data points in the intraday time series; full returns the full-length
            intraday time series. The "compact" option is recommended if you would
            like to reduce the data size of each API call.

        Optional: datatype
            By default, datatype=json. Strings json and csv are accepted with the
            following specifications: json returns the intraday time series in JSON
            format; csv returns the time series as a CSV (comma separated value)
            file.
        """
        self._counter()
        try:
            data, meta_data = self.ts.get_intraday(symbol=self.ticker,
                                                   interval=interval,
                                                   outputsize=outputsize)
        except:
            raise Exception('API call get_intraday failed.')
        return data, meta_data

    def get_time_series_daily(self, outputsize='compact', datatype='json'):
        """
        This API returns daily time series (date, daily open, daily high, daily low,
        daily close, daily volume) of the global equity specified, covering 20+
        years of historical data. The most recent data point is the prices and
        volume information of the current trading day, updated realtime.

        API Parameters
        Required: symbol
            The name of the equity of your choice. For example: symbol=MSFT

        Optional: outputsize
            By default, outputsize=compact. Strings compact and full are accepted
            with the following specifications: compact returns only the latest 100
            data points; full returns the full-length time series of 20+ years of
            historical data. The "compact" option is recommended if you would like
            to reduce the data size of each API call.

        Optional: datatype
            By default, datatype=json. Strings json and csv are accepted with the
            following specifications: json returns the daily time series in JSON
            format; csv returns the time series as a CSV (comma separated value)
            file.
        """
        self._counter()
        try:
            data, meta_data = self.ts.get_daily(symbol=self.ticker,
                                                outputsize=outputsize)
        except:
            raise Exception('API call get_daily failed')

        return data, meta_data

    def get_time_series_daily_adjusted(
        self,
        outputsize='compact',
        datatype='json',
    ):
        """
        This API returns daily time series (date, daily open, daily high, daily low,
         daily close, daily volume, daily adjusted close, and split/dividend events)
          of the global equity specified, covering 20+ years of historical data.
        The most recent data point is the prices and volume information of the
        current trading day, updated realtime.

        API Parameters
        Required: symbol
           The name of the equity of your choice. For example: symbol=MSFT

        Optional: outputsize
            By default, outputsize=compact. Strings compact and full are accepted
            with the following specifications: compact returns only the latest 100
            data points; full returns the full-length time series of 20+ years of
            historical data. The "compact" option is recommended if you would
            like to reduce the data size of each API call.

        Optional: datatype
            By default, datatype=json. Strings json and csv are accepted with the
            following specifications: json returns the daily time series in JSON
            format; csv returns the time series as a CSV (comma separated value)
            file.
        """
        self._counter()
        try:
            data, meta_data = self.ts.get_daily_adjusted(symbol=self.ticker,
                                                         outputsize=outputsize,
                                                         datatype=datatype)
        except:
            raise Exception('API call get_daily_adjusted failed')

        return data, meta_data

    def get_simple_moving_average(self,
                                  interval='daily',
                                  time_period=20,
                                  series_type='close',
                                  datatype='json'):
        """
        This API returns the simple moving average (SMA) values. See also:
        Investopedia article and mathematical reference.

        API Parameters
        Required: symbol
            The name of the security of your choice. For example: symbol=MSFT

        Required: interval
            Time interval between two consecutive data points in the time series.
            The following values are supported: 1min, 5min, 15min, 30min, 60min,
            daily, weekly, monthly

        Required:time_period
            Number of data points used to calculate each moving average value.
            Positive integers are accepted (e.g., time_period=60, time_period=200)

        Required: series_type
            The desired price type in the time series. Four types are supported:
            close, open, high, low

        Optional: datatype
            By default, datatype=json. Strings json and csv are accepted with the
            following specifications: json returns the daily time series in JSON
            format; csv returns the time series as a CSV (comma separated value)
            file.
        """
        self._counter()
        try:
            data, meta_data = self.ti.get_sma(symbol=self.ticker,
                                              interval=interval,
                                              time_period=time_period,
                                              series_type=series_type,
                                              datatype=datatype)
        except:
            raise Exception('API call simple_moving_average failed')

        return data, meta_data

    def get_exponential_moving_average(self,
                                       interval='daily',
                                       time_period=20,
                                       series_type='close',
                                       datatype='json'):
        """
        This API returns the exponential moving average (EMA) values.
        API Parameters
        Required: symbol
           The name of the security of your choice. For example: symbol=MSFT

        Required: interval
            Time interval between two consecutive data points in the time series.
            The following values are supported: 1min, 5min, 15min, 30min, 60min,
            daily, weekly, monthly

        Required:time_period
            Number of data points used to calculate each moving average value.
            Positive integers are accepted (e.g., time_period=60, time_period=200)

        Required: series_type
            The desired price type in the time series. Four types are supported:
            close, open, high, low

        Optional: datatype
            By default, datatype=json. Strings json and csv are accepted with the
            following specifications: json returns the daily time series in JSON
            format; csv returns the time series as a CSV (comma separated value)
            file.
        """
        self._counter()
        try:
            data, meta_data = self.ti.get_ema(symbol=self.ticker,
                                              interval=interval,
                                              time_period=time_period,
                                              series_type=series_type,
                                              datatype=datatype)
        except:
            raise Exception('API call exponential_moving_average failed')

        return data, meta_data

    def get_moving_average_conv_div(self,
                                    interval='daily',
                                    series_type='close',
                                    fastperiod=12,
                                    slowperiod=26,
                                    signalperiod=9,
                                    datatype='json'):
        """
        This API returns the moving average convergence / divergence (MACD) values.

        API Parameters
        Required: symbol
            The name of the security of your choice. For example: symbol=MSFT

        Required: interval
            Time interval between two consecutive data points in the time series.
            The following values are supported: 1min, 5min, 15min, 30min, 60min,
            daily, weekly, monthly

        Required: series_type
            The desired price type in the time series. Four types are supported:
            close, open, high, low

        Optional: fastperiod
            Positive integers are accepted. By default, fastperiod=12.

        Optional: slowperiod
            Positive integers are accepted. By default, slowperiod=26.

        Optional: signalperiod
            Positive integers are accepted. By default, signalperiod=9.

        Optional: datatype
            By default, datatype=json. Strings json and csv are accepted with the
            following specifications: json returns the daily time series in JSON
            format; csv returns the time series as a CSV (comma separated value)
            file.
        """
        self._counter()
        try:
            data, meta_data = self.ti.get_macd(symbol=self.ticker,
                                               interval=interval,
                                               series_type=series_type,
                                               fastperiod=fastperiod,
                                               slowperiod=slowperiod,
                                               signalperiod=signalperiod,
                                               datatype=datatype)
        except:
            raise Exception('API call get_moving_average_conv_div failed')

        return data, meta_data

    def get_stochastic_oscillator(self,
                                  interval='daily',
                                  fastkperiod=5,
                                  slowkperiod=3,
                                  slowdperiod=3,
                                  slowkmatype=0,
                                  slowdmatype=0,
                                  datatype='json'):
        """
        This API returns the stochastic oscillator (STOCH) values.

        API Parameters
        Required: symbol
            The name of the security of your choice. For example: symbol=MSFT

        Required: interval
            Time interval between two consecutive data points in the time series.
            The following values are supported: 1min, 5min, 15min, 30min, 60min,
            daily, weekly, monthly

        Optional: fastkperiod
            The time period of the fastk moving average. Positive integers are
            accepted. By default, fastkperiod=5.

        Optional: slowkperiod
            The time period of the slowk moving average. Positive integers are
            accepted. By default, slowkperiod=3.

        Optional: slowdperiod
          The time period of the slowd moving average. Positive integers are
          accepted. By default, slowdperiod=3.

        Optional: slowkmatype
            Moving average type for the slowk moving average. By default,
            slowkmatype=0. Integers 0 - 8 are accepted with the following mappings.
                0 = Simple Moving Average (SMA),
                1 = Exponential Moving Average (EMA),
                2 = Weighted Moving Average (WMA),
                3 = Double Exponential Moving Average (DEMA),
                4 = Triple Exponential Moving Average (TEMA),
                5 = Triangular Moving Average (TRIMA),
                6 = T3 Moving Average,
                7 = Kaufman Adaptive Moving Average (KAMA),
                8 = MESA Adaptive Moving Average (MAMA).

        Optional: slowdmatype
        Moving average type for the slowd moving average. By default, slowdmatype=0.
        Integers 0 - 8 are accepted with the following mappings.
            0 = Simple Moving Average (SMA),
            1 = Exponential Moving Average (EMA),
            2 = Weighted Moving Average (WMA),
            3 = Double Exponential Moving Average (DEMA),
            4 = Triple Exponential Moving Average (TEMA),
            5 = Triangular Moving Average (TRIMA),
            6 = T3 Moving Average,
            7 = Kaufman Adaptive Moving Average (KAMA),
            8 = MESA Adaptive Moving Average (MAMA).

        Optional: datatype
            By default, datatype=json. Strings json and csv are accepted with the
            following specifications: json returns the daily time series in JSON
            format; csv returns the time series as a CSV (comma separated value)
            file.
        """
        self._counter()
        try:
            data, meta_data = self.ti.get_stoch(symbol=self.ticker,
                                                interval=interval,
                                                fastkperiod=fastkperiod,
                                                slowkperiod=slowkperiod,
                                                slowdperiod=slowdperiod,
                                                slowkmatype=slowkmatype,
                                                slowdmatype=slowdmatype,
                                                datatype=datatype)
        except:
            raise Exception('API call get_moving_average_conv_div failed')

        return data, meta_data

    def get_bollinger_bands(self,
                            interval='daily',
                            time_period=20,
                            series_type='close',
                            nbdevup=2,
                            nbdevdn=2,
                            matype=0,
                            datatype='json'):
        """
        This API returns the Bollinger bands (BBANDS) values.

        API Parameters
        Required: symbol
           The name of the security of your choice. For example: symbol=MSFT

        Required: interval
            Time interval between two consecutive data points in the time series.
            The following values are supported: 1min, 5min, 15min, 30min, 60min,
            daily, weekly, monthly

        Required:time_period
            Number of data points used to calculate each BBANDS value. Positive
            integers are accepted (e.g., time_period=60, time_period=200)

        Required: series_type
            The desired price type in the time series. Four types are supported:
            close, open, high, low

        Optional: nbdevup
            The standard deviation multiplier of the upper band. Positive integers
            are accepted. By default, nbdevup=2.

        Optional: nbdevdn
           The standard deviation multiplier of the lower band. Positive integers
           are accepted. By default, nbdevdn=2.

        Optional: matype
            Moving average type of the time series. By default, matype=0.
            Integers 0 - 8 are accepted with the following mappings.
            0 = Simple Moving Average (SMA),
            1 = Exponential Moving Average (EMA),
            2 = Weighted Moving Average (WMA),
            3 = Double Exponential Moving Average (DEMA),
            4 = Triple Exponential Moving Average (TEMA),
            5 = Triangular Moving Average (TRIMA),
            6 = T3 Moving Average,
            7 = Kaufman Adaptive Moving Average (KAMA),
            8 = MESA Adaptive Moving Average (MAMA).

        Optional: datatype
            By default, datatype=json. Strings json and csv are accepted with the
            following specifications: json returns the daily time series in JSON
            format; csv returns the time series as a CSV (comma separated value)
            file.
        """
        self._counter()
        try:
            data, meta_data = self.ti.get_bbands(symbol=self.ticker,
                                                 interval=interval,
                                                 time_period=time_period,
                                                 series_type=series_type,
                                                 nbdevup=nbdevup,
                                                 nbdevdn=nbdevdn,
                                                 matype=matype,
                                                 datatype=datatype)
        except:
            raise Exception('API call get_bollinger_bands failed')

        return data, meta_data

    def get_Chaikin_A_D_line(self, interval='daily', datatype='json'):
        """
        This API returns the Chaikin A/D line (AD) values.

        API Parameters
        Required: symbol
            The name of the security of your choice. For example: symbol=MSFT

        Required: interval
            Time interval between two consecutive data points in the time series.
            The following values are supported: 1min, 5min, 15min, 30min, 60min,
            daily, weekly, monthly

        Optional: datatype
            By default, datatype=json. Strings json and csv are accepted with the
            following specifications: json returns the daily time series in JSON
            format; csv returns the time series as a CSV (comma separated value)
            file.
        """
        self._counter()
        try:
            data, meta_data = self.ti.get_ad(symbol=self.ticker,
                                             interval=interval,
                                             datatype=datatype)
        except:
            raise Exception('API call get_Chaikin_A_D_line failed')

        return data, meta_data

    def get_balance_volume(self, interval='daily', datatype='json'):
        """
        This API returns the on balance volume (OBV) values.

        API Parameters
        Required: symbol
            The name of the security of your choice. For example: symbol=MSFT

        Required: interval
            Time interval between two consecutive data points in the time series.
            The following values are supported: 1min, 5min, 15min, 30min, 60min,
            daily, weekly, monthly

        Optional: datatype
            By default, datatype=json. Strings json and csv are accepted with the
            following specifications: json returns the daily time series in JSON
            format; csv returns the time series as a CSV (comma separated value)
            file.
        """
        self._counter()
        try:
            data, meta_data = self.ti.get_obv(symbol=self.ticker,
                                              interval=interval,
                                              datatype=datatype)
        except:
            raise Exception('API call get_balance_volume failed')

        return data, meta_data

    def get_sector_performance(self):
        """
        This API returns the realtime and historical sector performances calculated
        from S&P500 incumbents.
        """
        self._counter()
        try:
            data, meta_data = self.sp.get_sector()
        except:
            raise Exception('API call get_sector_performance failed')

        return data, meta_data
 def alpha_collect_technical_indicators():
     ti = TechIndicators(key='YOUR_API_KEY', output_format='pandas')
     data, meta_data = ti.get_ad(symbol='MSFT', interval='60min', time_period=60)
Exemplo n.º 12
0
df['ema'], _ = ti.get_ema(symbol=symbol, time_period=ema_time_period)
df['rsi'], _ = ti.get_rsi(symbol=symbol, time_period=rsi_time_period)
df['obv'], _ = ti.get_obv(symbol=symbol)
macd = ti.get_macd(symbol=symbol)[0].sort_index(axis=0, ascending=True)
for column in macd.columns:
    df[column] = macd[column]

stoch = ti.get_stoch(symbol=symbol)[0].sort_index(axis=0, ascending=True)
for column in stoch.columns:
    df[column] = stoch[column]

df['adx'], _ = ti.get_adx(symbol=symbol, time_period=adx_time_period)
df['cci'], _ = ti.get_cci(symbol=symbol, time_period=cci_time_period)
aroon = ti.get_aroon(
    symbol=symbol, time_period=aroon_time_period)[0].sort_index(axis=0,
                                                                ascending=True)
for column in aroon.columns:
    df[column] = aroon[column]

bbands = ti.get_bbands(symbol=symbol,
                       time_period=bbands_time_period)[0].sort_index(
                           axis=0, ascending=True)
for column in bbands.columns:
    df[column] = bbands[column]

df['ad'], _ = ti.get_ad(symbol=symbol)

df['shifted_ROC_BOOL'] = (df['roc'].shift(-1) >= 0).astype(int)

df.to_csv(filename)
def techIndicatorPull(symbol):
    interval = "1min"
    print("Calculating Tech Indicators ...")

    ti = TechIndicators(key='1HAYLUHGCB6E0VXC', output_format='pandas')

    print("Progress: 0% complete...")

    ad_data, meta_data = ti.get_ad(symbol=symbol, interval=interval)
    adosc_data, meta_data = ti.get_adosc(symbol=symbol, interval=interval)
    adx_data, meta_data = ti.get_adx(symbol=symbol, interval=interval)
    adxr_data, meta_data = ti.get_adxr(symbol=symbol, interval=interval)
    apo_data, meta_data = ti.get_apo(symbol=symbol, interval=interval)
    aroon_data, meta_data = ti.get_aroon(symbol=symbol, interval=interval)
    aroonosc_data, meta_data = ti.get_aroonosc(symbol=symbol,
                                               interval=interval)
    atr_data, meta_data = ti.get_atr(symbol=symbol, interval=interval)
    bop_data, meta_data = ti.get_bop(symbol=symbol, interval=interval)
    cci_data, meta_data = ti.get_cci(symbol=symbol, interval=interval)

    print("Progress: 20% complete...")

    cmo_data, meta_data = ti.get_cmo(symbol=symbol, interval=interval)
    dema_data, meta_data = ti.get_dema(symbol=symbol, interval=interval)
    dx_data, meta_data = ti.get_dx(symbol=symbol, interval=interval)
    ema_data, meta_data = ti.get_ema(symbol=symbol, interval=interval)
    ht_dcperiod_data, meta_data = ti.get_ht_dcperiod(symbol=symbol,
                                                     interval=interval)
    ht_dcphase_data, meta_data = ti.get_ht_dcphase(symbol=symbol,
                                                   interval=interval)
    ht_phasor_data, meta_data = ti.get_ht_phasor(symbol=symbol,
                                                 interval=interval)
    ht_sine_data, meta_data = ti.get_ht_sine(symbol=symbol, interval=interval)
    ht_trendline_data, meta_data = ti.get_ht_trendline(symbol=symbol,
                                                       interval=interval)
    ht_trendmode_data, meta_data = ti.get_ht_trendmode(symbol=symbol,
                                                       interval=interval)

    print("Progress: 40% complete...")

    kama_data, meta_data = ti.get_kama(symbol=symbol, interval=interval)
    macd_data, meta_data = ti.get_macd(symbol=symbol, interval=interval)
    macdext_data, meta_data = ti.get_macdext(symbol=symbol, interval=interval)
    mama_data, meta_data = ti.get_mama(symbol=symbol, interval=interval)
    mfi_data, meta_data = ti.get_mfi(symbol=symbol, interval=interval)
    midpoint_data, meta_data = ti.get_midpoint(symbol=symbol,
                                               interval=interval)
    midprice_data, meta_data = ti.get_midprice(symbol=symbol,
                                               interval=interval)
    minus_di_data, meta_data = ti.get_minus_di(symbol=symbol,
                                               interval=interval)
    mom_data, meta_data = ti.get_mom(symbol=symbol, interval=interval)
    natr_data, meta_data = ti.get_natr(symbol=symbol, interval=interval)

    print("Progress: 60% complete...")

    obv_data, meta_data = ti.get_obv(symbol=symbol, interval=interval)
    plus_di_data, meta_data = ti.get_plus_di(symbol=symbol, interval=interval)
    plus_dm_data, meta_data = ti.get_plus_dm(symbol=symbol, interval=interval)
    ppo_data, meta_data = ti.get_ppo(symbol=symbol, interval=interval)
    roc_data, meta_data = ti.get_roc(symbol=symbol, interval=interval)
    rocr_data, meta_data = ti.get_rocr(symbol=symbol, interval=interval)
    rsi_data, meta_data = ti.get_rsi(symbol=symbol, interval=interval)
    sar_data, meta_data = ti.get_sar(symbol=symbol, interval=interval)
    sma_data, meta_data = ti.get_sma(symbol=symbol, interval=interval)
    stoch_data, meta_data = ti.get_stoch(symbol=symbol, interval=interval)

    print("Progress: 80% complete...")

    stochf_data, meta_data = ti.get_stochf(symbol=symbol, interval=interval)
    stochrsi_data, meta_data = ti.get_stochrsi(symbol=symbol,
                                               interval=interval)
    t3_data, meta_data = ti.get_t3(symbol=symbol, interval=interval)
    tema_data, meta_data = ti.get_tema(symbol=symbol, interval=interval)
    trange_data, meta_data = ti.get_trange(symbol=symbol, interval=interval)
    trima_data, meta_data = ti.get_trima(symbol=symbol, interval=interval)
    trix_data, meta_data = ti.get_trix(symbol=symbol, interval=interval)
    ultsoc_data, meta_data = ti.get_ultsoc(symbol=symbol, interval=interval)
    willr_data, meta_data = ti.get_willr(symbol=symbol, interval=interval)
    wma_data, meta_data = ti.get_wma(symbol=symbol, interval=interval)
    bbands_data, meta_data = ti.get_bbands(symbol=symbol, interval=interval)

    print("Progress: 90% complete...")

    result = pd.concat([
        ad_data, adosc_data, adx_data, adxr_data, apo_data, aroon_data,
        aroonosc_data, atr_data, bop_data, cci_data, cmo_data, dema_data,
        dx_data, ema_data, ht_dcperiod_data, ht_dcphase_data, ht_phasor_data,
        ht_sine_data, ht_trendline_data, ht_trendmode_data, kama_data,
        macd_data, macdext_data, mama_data, mfi_data, midpoint_data,
        midprice_data, minus_di_data, mom_data, natr_data, obv_data,
        plus_di_data, plus_dm_data, ppo_data, roc_data, rocr_data, rsi_data,
        sar_data, sma_data, stoch_data, stochf_data, stochrsi_data, t3_data,
        tema_data, trange_data, trima_data, trix_data, ultsoc_data, willr_data,
        wma_data, bbands_data
    ],
                       axis=1)

    result["stockticker"] = symbol

    result = result.reindex(result.index.rename('timestamp'))
    result = result.dropna(axis=0, how='any')
    result = result.round(2)
    result = result.rename(
        columns={
            'Chaikin A/D': 'ChaikinAD',
            'Aroon Up': 'AroonUp',
            'Aroon Down': 'AroonDown',
            'LEAD SINE': 'LeadSine',
            'Real Upper Band': 'RealUpperBand',
            'Real Middle Band': 'RealMiddleBand',
            'Real Lower Band': 'RealLowerBand'
        })

    fd = open('results/rawTechIndicatorData.csv', 'w')
    result.to_csv(fd, index=True, encoding='utf-8')
    fd.close()

    print("Progress: 99% complete...")

    df = pd.read_csv('results/rawTechIndicatorData.csv')

    insertToOracleDatabase(
        df,
        '''insert /*+ ignore_row_on_dupkey_index(stocktechindicator, stocktechindicator_pk) */
                                    into stocktechindicator 
                                    (timestamp,ChaikinAD,ADOSC,ADX,ADXR,
                                    APO,AroonUp,AroonDown,AROONOSC,ATR,
                                    BOP,CCI,CMO,DEMA,DX,
                                    EMA,DCPERIOD,HT_DCPHASE,QUADRATURE, PHASE,
                                    LEADSINE,SINE,HT_TRENDLINE,TRENDMODE,KAMA,
                                    MACD,MACD_Hist,MACD_Signal,MACD_Signal2,MACD2,
                                    MACD_Hist2,FAMA,MAMA,MFI,MIDPOINT,
                                    MIDPRICE,MINUS_DI,MOM,NATR,OBV,
                                    PLUS_DI,PLUS_DM,PPO,ROC,ROCR,
                                    RSI,SAR,SMA,SlowK,SlowD,
                                    FastK,FastD,FastK2,FastD2,T3,
                                    TEMA,TRANGE,TRIMA,TRIX,ULTOSC,
                                    WILLR,WMA,RealLowerBand,RealUpperBand,RealMiddleBand,
                                    stockticker) 
                                    values (:1, :2, :3, :4, :5, 
                                            :6, :7, :8, :9, :10,
                                            :11, :12, :13, :14, :15, 
                                            :16, :17, :18, :19, :20, 
                                            :21, :22, :23, :24, :25, 
                                            :26, :27, :28, :29, :30, 
                                            :31, :32, :33, :34, :35, 
                                            :36, :37, :38, :39, :40, 
                                            :41, :42, :43, :44, :45, 
                                            :46, :47, :48, :49, :50, 
                                            :51, :52, :53, :54, :55, 
                                            :56, :57, :58, :59, :60, 
                                            :61, :62, :63, :64, :65, 
                                            :66)''')
Exemplo n.º 14
0
def getData(tker,alg,time,tDF,tI,incP,typeClass,return_list):

	print("Getting Data")

	dataDict= []
	symb = tker
	#Do not use 60min since that does not work.
	#Cannot figure out how, but the keys for date and time are different.
	tInterval = time
	ourKey = '2ONP54KRQ2G73D3K'

	#Using the wrapper class to get the different data for the inputted ticker
	#In a try-catch because sometime the API fails
	try:
		#Making the retry number high so the API call should not fail
		ts = TimeSeries(key = ourKey, output_format = 'json',retries=10000)
		#tInterval has first letter capitalized when getting input for neatness, it is then lowered here for the API call
		#Here we are getting the price data for the requested time interval
		if tInterval == 'Daily':
			priceData, meta_priceData = ts.get_daily(symbol= symb, outputsize='full')
			tInterval = 'daily'
		elif tInterval == 'Weekly':
			priceData, meta_priceData = ts.get_weekly(symbol = symb)
			tInterval = 'weekly'
		elif tInterval =='Monthly':
			priceData, meta_priceData = ts.get_monthly(symbol = symb)
			tInterval = 'monthly'
		else:
			priceData, meta_priceData = ts.get_intraday(symbol = symb, interval = tInterval, outputsize='full')
			#Intraday date and time key includes seconds, while it does not for technicial indicators
			for day in priceData.copy():
				priceData[day[:-3]] = priceData.pop(day)


		ti = TechIndicators(key = ourKey, output_format ='json')
		#Here we get the technical indicators the user chose from the menu, unless they chose to do a tDF.
		if tDF == "No":
			if 0 in tI:
				macD, meta_macD = ti.get_macd(symbol = symb, interval = tInterval,  series_type = 'close')
				dataDict.append(macD)
			if 1 in tI:
				stoch, meta_stoch = ti.get_stoch(symbol = symb, interval = tInterval, fastkperiod = '5')
				dataDict.append(stoch)
			if 2 in tI:
				ema, meta_ema = ti.get_ema(symbol = symb, interval = tInterval, time_period = '8', series_type = 'close')
				dataDict.append(ema)
			if 3 in tI:
				rsi, meta_rsi = ti.get_rsi(symbol = symb, interval = tInterval, time_period = '14', series_type='close')
				dataDict.append(rsi)
			if 4 in tI:
				plusDI, meta_plusDI = ti.get_plus_di(symbol = symb, interval = tInterval, time_period = '14')
				minusDI, meta_minusDI = ti.get_minus_di(symbol = symb, interval = tInterval, time_period = '14')
				dataDict.append(plusDI)
				dataDict.append(minusDI)
			if 5 in tI:
				cci, meta_cci = ti.get_cci(symbol = symb, interval = tInterval, time_period = '14')
				dataDict.append(cci)
			if 6 in tI:
				willR, meta_willR = ti.get_willr(symbol = symb, interval = tInterval, time_period = '14')
				dataDict.append(willR)
			if 7 in tI:
				oBV, meta_OBV = ti.get_obv(symbol = symb, interval = tInterval)
				dataDict.append(oBV)
			if 8 in tI:
				aD, meta_AD = ti.get_ad(symbol = symb, interval = tInterval)
				dataDict.append(aD)
			if 9 in tI:
				bBands, meta_bBands = ti.get_bbands(symbol = symb, interval = tInterval, time_period = '14', series_type = 'close')
				dataDict.append(bBands)
			if 10 in tI:
				aroon, meta_aroon = ti.get_aroon(symbol = symb, interval = tInterval, time_period = '14')
				dataDict.append(aroon)
			if 11 in tI:
				adx, meta_adx = ti.get_adx(symbol = symb, interval = tInterval, time_period = '14')
				dataDict.append(adx)
			if(incP == "Yes"):
				dataDict.append(priceData)
		#Since a tDF requires a manual transformation, we choose the technical indicators for it, which are retrieved here
		else:
			macD, meta_macD = ti.get_macd(symbol = symb, interval = tInterval,  series_type = 'close')
			stoch, meta_stoch = ti.get_stoch(symbol = symb, interval = tInterval, fastkperiod = '5')
			ema, meta_ema = ti.get_ema(symbol = symb, interval = tInterval, time_period = '8', series_type = 'close')
			rsi, meta_rsi = ti.get_rsi(symbol = symb, interval = tInterval, time_period = '14', series_type='close')
			plusDI, meta_plusDI = ti.get_plus_di(symbol = symb, interval = tInterval, time_period = '14')
			minusDI, meta_minusDI = ti.get_minus_di(symbol = symb, interval = tInterval, time_period = '14')
			cci, meta_cci = ti.get_cci(symbol = symb, interval = tInterval, time_period = '14')
			willR, meta_willR = ti.get_willr(symbol = symb, interval = tInterval, time_period = '14')
			dataDict.append(macD)
			dataDict.append(stoch)
			dataDict.append(ema)
			dataDict.append(rsi)
			dataDict.append(plusDI)
			dataDict.append(minusDI)
			dataDict.append(cci)
			dataDict.append(willR)
	#Returning with nothing tells our main process that there was an error
	except ValueError:
		return

	#Sometimes the API may return a empty list which will cause an error for the training
	for list in dataDict:
		if not list:
			return

	#Need atleast one of the dictionaries to be ordered by date, so we can organize all our data.
	priceData = collections.OrderedDict(sorted(priceData.items()))

	#dates used for drawing graph afterwards
	dates = []
	for day in priceData:
		dates.append(day)

	#Parsing the data
	#All the data for each day is put into an array, which is put into trainingData, sorted by dates
	trainingData = []
	#Putting the ordered price data into priceList, instead of using a Dictionary
	#So if the user doesn't want to include price in training, we still have a list to train
	#for the actual outputs/
	priceList = []
	#If the user is using this in the middle of the day/week/month, the data will have a partial time interval up to the current time
	#Here we remove the last day if it is the same date as today, so we can get a guess for the timer interval asked.
	todaysDate = str(datetime.datetime.now())[:10]
	if todaysDate in priceData.keys():
		del priceData[todaysDate]

	for day in priceData:
		#Making sure the day is in the priceData and each of the technical indicator lists.
		#The API doesn't necessarily give the data for every data for the different requests
		if all(day in indic for indic in dataDict):
			vector = []
			priceData[day] = collections.OrderedDict(sorted(priceData[day].items()))
			for stat in priceData[day]:
				vector.append(float(priceData[day][stat]))
			priceList.append(vector)

			vector = []
			for x in range(0,len(dataDict)):
			#Order the different stats within a data, so the order is consistent across vectors
				dataDict[x][day] = collections.OrderedDict(sorted(dataDict[x][day].items()))
			#Combine all the different data into a vector
			for x in range(0,len(dataDict)):
				for stat in dataDict[x][day]:
					vector.append(float(dataDict[x][day][stat]))
			trainingData.append(vector)

	#If the user wanted to do a tDF, the training data is transformed, otherwise the trainingData goes straight to PredictAndTest
	trendDeter = False if tDF == "No" else True
	#delete first element of priceList because trendDeter, remove first element form training data
	if trendDeter:
		del priceList[0]
		predictAndTest(trendDeterTransform(trainingData), priceList, trendDeter, alg, tInterval, dates, typeClass, return_list)
	else:
		predictAndTest(trainingData, priceList, trendDeter, alg, tInterval, dates, typeClass, return_list)
    cursor.executemany(query, rows)
    connection.commit()


print("Begining")

symbol = "ORCL"
interval = "1min"


ti = TechIndicators(key='1HAYLUHGCB6E0VXC', output_format='pandas')

print("Progress: 0% complete...")


ad_data, meta_data = ti.get_ad(symbol=symbol, interval=interval)
adosc_data, meta_data = ti.get_adosc(symbol=symbol, interval=interval)
adx_data, meta_data = ti.get_adx(symbol=symbol, interval=interval)
adxr_data, meta_data = ti.get_adxr(symbol=symbol, interval=interval)
apo_data, meta_data = ti.get_apo(symbol=symbol, interval=interval)
aroon_data, meta_data = ti.get_aroon(symbol=symbol, interval=interval)
aroonosc_data, meta_data = ti.get_aroonosc(symbol=symbol, interval=interval)
atr_data, meta_data = ti.get_atr(symbol=symbol, interval=interval)
bop_data, meta_data = ti.get_bop(symbol=symbol, interval=interval)
cci_data, meta_data = ti.get_cci(symbol=symbol, interval=interval)

print("Progress: 20% complete...")

cmo_data, meta_data = ti.get_cmo(symbol=symbol, interval=interval)
dema_data, meta_data = ti.get_dema(symbol=symbol, interval=interval)
dx_data, meta_data = ti.get_dx(symbol=symbol, interval=interval)
Exemplo n.º 16
0
def save_ti(ticker, interval='daily'):
    ti = TechIndicators(key='WS8K5VM8FZL52BTH', output_format='pandas')

    ti.get_sma(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_sma.csv')
    call_check()
    ti.get_ema(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_ema.csv')
    call_check()
    ti.get_wma(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_wma.csv')
    call_check()
    ti.get_dema(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_dema.csv')
    call_check()
    ti.get_tema(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_tema.csv')
    call_check()
    ti.get_trima(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_trima.csv')
    call_check()
    ti.get_kama(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_kama.csv')
    call_check()
    ti.get_mama(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_mama.csv')
    call_check()
    ti.get_t3(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_t3.csv')
    call_check()
    ti.get_macd(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_macd.csv')
    call_check()
    ti.get_macdext(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_macdext.csv')
    call_check()
    ti.get_stoch(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_stoch.csv')
    call_check()
    ti.get_stochf(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_stochf.csv')
    call_check()
    ti.get_rsi(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_rsi.csv')
    call_check()
    ti.get_stochrsi(ticker, interval)[0].to_csv(
        f'./Stock Data/TI/{ticker}_{interval}_stochris.csv')
    call_check()
    ti.get_willr(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_willr.csv')
    call_check()
    ti.get_adx(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_adx.csv')
    call_check()
    ti.get_adxr(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_adxr.csv')
    call_check()
    ti.get_apo(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_apo.csv')
    call_check()
    ti.get_ppo(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_ppo.csv')
    call_check()
    ti.get_mom(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_mom.csv')
    call_check()
    ti.get_bop(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_bop.csv')
    call_check()
    ti.get_cci(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_cci.csv')
    call_check()
    ti.get_cmo(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_cmo.csv')
    call_check()
    ti.get_roc(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_roc.csv')
    call_check()
    ti.get_rocr(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_rocr.csv')
    call_check()
    ti.get_aroon(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_aroon.csv')
    call_check()
    ti.get_aroonosc(ticker, interval)[0].to_csv(
        f'./Stock Data/TI/{ticker}_{interval}_aroonosc.csv')
    call_check()
    ti.get_mfi(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_mfi.csv')
    call_check()
    ti.get_trix(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_trix.csv')
    call_check()
    ti.get_ultosc(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_ultosc.csv')
    call_check()
    ti.get_dx(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_dx.csv')
    call_check()
    ti.get_minus_di(ticker, interval)[0].to_csv(
        f'./Stock Data/TI/{ticker}_{interval}_minus_di.csv')
    call_check()
    ti.get_plus_di(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_plus_di.csv')
    call_check()
    ti.get_minus_dm(ticker, interval)[0].to_csv(
        f'./Stock Data/TI/{ticker}_{interval}_minus_dm.csv')
    call_check()
    ti.get_plus_dm(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_plus_dm.csv')
    call_check()
    ti.get_bbands(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_bbands.csv')
    call_check()
    ti.get_midpoint(ticker, interval)[0].to_csv(
        f'./Stock Data/TI/{ticker}_{interval}_midpoint.csv')
    call_check()
    ti.get_midprice(ticker, interval)[0].to_csv(
        f'./Stock Data/TI/{ticker}_{interval}_midprice.csv')
    call_check()
    ti.get_sar(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_sar.csv')
    call_check()
    ti.get_trange(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_trange.csv')
    call_check()
    ti.get_atr(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_atr.csv')
    call_check()
    ti.get_natr(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_natr.csv')
    call_check()
    ti.get_ad(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_ad.csv')
    call_check()
    ti.get_adosc(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_adosc.csv')
    call_check()
    ti.get_obv(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_obv.csv')
    call_check()
    ti.get_ht_trendline(ticker, interval)[0].to_csv(
        f'./Stock Data/TI/{ticker}_{interval}_ht_trendline.csv')
    call_check()
    ti.get_ht_sine(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_ht_sine.csv')
    call_check()
    ti.get_ht_trendmode(ticker, interval)[0].to_csv(
        f'./Stock Data/TI/{ticker}_{interval}_ht_trendmode.csv')
    call_check()
    ti.get_ht_dcperiod(ticker, interval)[0].to_csv(
        f'./Stock Data/TI/{ticker}_{interval}_dcperiod.csv')
    call_check()
    ti.get_ht_dcphase(
        ticker,
        interval)[0].to_csv(f'./Stock Data/TI/{ticker}_{interval}_dcphase.csv')
    call_check()
    ti.get_ht_phasor(ticker, interval)[0].to_csv(
        f'./Stock Data/TI/{ticker}_{interval}_ht_phasor.csv')