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 data_to_csv(ticker):
	# Your key here - keep it
	key = '6LGG0QGAGBROB2M6'

	dire = 'DATA/'+ticker+'/'
	no_dir = True
	i = 0
	while no_dir:
		if os.path.isdir(dire+str(i)):
			i += 1
		else:
			dire += str(i) + '/'
			os.mkdir(dire)
			no_dir = False # break out of loop

	print(dire)

	ts = TimeSeries(key=key, output_format='pandas')
	ti = TechIndicators(key=key, output_format='pandas')
	
	### PRICE ###############################################################
	intra, meta = ts.get_intraday(symbol=ticker, interval='5min', outputsize='full')
	intra.to_csv(dire+ticker+"_prices.csv")
	
	### SMA #################################################################
	sma8, meta = ti.get_sma(symbol=ticker, interval='5min', time_period=8)
	sma8.to_csv(dire+ticker+"_sma8.csv")

	### EMA #################################################################
	ema8, meta = ti.get_ema(symbol=ticker, interval='5min', time_period=8)
	ema8.to_csv(dire+ticker+"_ema8.csv")

	### MACD ################################################################
	macd, meta = ti.get_macd(symbol=ticker, interval='5min')
	macd.to_csv(dire+ticker+"_macd.csv")
Exemplo n.º 3
0
    def ema(self):  #exponential moving average
        d = TechIndicators(key=self.api_key, output_format='pandas')
        data, meta_data = d.get_ema(symbol=self.stock_name,
                                    interval='15min',
                                    time_period=20)

        return data
Exemplo n.º 4
0
    def save_all_indicators(stock_name):
        '''
        Saves everything to local .csv files with corresponding name
        @DEV NOTE: can only process any 5 of them, the other 2 will encounter unexpected error
        :param stock_name:
        :return: None
        '''

        ti = TechIndicators(key=Env.alpha_vantage_api_key, output_format='pandas')

        d, _ = ti.get_cci(symbol=stock_name, interval='daily', time_period=60)
        d.to_csv(stock_name + '_CCI.csv', index=True, sep=',')

        d, _ = ti.get_rsi(symbol=stock_name, interval='daily', series_type='close', time_period='60')
        d.to_csv(stock_name + '_RSI.csv', index=True, sep=',')

        d, _ = ti.get_stoch(symbol=stock_name, interval='daily')
        d.to_csv(stock_name + '_stoch.csv', index=True, sep=',')

        d, _ = ti.get_macd(symbol=stock_name, interval='daily', series_type='close')
        d.to_csv(stock_name + '_MACD.csv', index=True, sep=',')

        d, _ = ti.get_obv(symbol=stock_name, interval='daily')
        d.to_csv(stock_name + '_OBV.csv', index=True, sep=',')

        d, _ = ti.get_ema(symbol=stock_name, interval='daily', series_type='close')
        d.to_csv(stock_name + '_EMA.csv', index=True, sep=',')

        d, _ = ti.get_roc(symbol=stock_name, interval='daily', time_period=60, series_type='close')
        d.to_csv(stock_name + '_ROC.csv', index=True, sep=',')
Exemplo n.º 5
0
 def ema(self, tp):
     e = TechIndicators(key=self.api_key2, output_format='json')
     data, meta_data = e.get_ema(symbol=self.stock_name,
                                 interval='1min',
                                 time_period=tp,
                                 series_type='close')
     return data
Exemplo n.º 6
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
Exemplo n.º 7
0
    def EMA(stock_name):
        '''
        Exponential Moving Average (指数移动平均)
        https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
        '''

        ti = TechIndicators(key=Env.alpha_vantage_api_key, output_format='pandas')
        data, meta_data = ti.get_ema(symbol=stock_name, interval='daily', series_type='close')
        # data.to_csv(stock_name + '_EMA indicator.csv', index=True, sep=',')
        return data.to_json(orient='split')
Exemplo n.º 8
0
def getEMA200(symb):
    whatever = None
    while whatever is None:
        try:
            ti = TechIndicators(key='KU7YQYX4LFOFNQTU', output_format='pandas')
            data, metadata = ti.get_ema(symbol=symb,
                                        interval='1min',
                                        time_period='200',
                                        series_type='close')
            whatever = data
            return data
        except KeyError:
            pass
def ema_ratio(ticker_list, slow=10, fast=5):
    ti = TechIndicators(key=alpha_key, output_format='pandas')
    for ticker in ticker_list:
        print(ticker)
        slow_df, meta = ti.get_ema(ticker, interval='daily', time_period=slow)
        fast_df, meta = ti.get_ema(ticker, interval='daily', time_period=fast)
        ratio_df = slow_df.EMA / fast_df.EMA
        ratio_df.fillna(1, inplace=True)
        ratio_df = ratio_df.rename('{0}_{1}_mar'.format(str(slow), str(fast)))
        # ratio_df = ratio_df.set_index(df.index)
        ratio_df.to_csv('data/{0}_{1}_mar/{2}.csv'.format(
            str(slow), str(fast), ticker),
                        header=True)
Exemplo n.º 10
0
def get_indicators(ticker):
    key = 'VDWEV1WBSQCQRZDF'
    ti = TechIndicators(key=key, output_format='pandas')
    ts = TimeSeries(key=key, output_format='pandas')

    # RSI
    data_rsi, meta_data_rsi = ti.get_rsi(symbol=ticker,
                                         interval='30min',
                                         time_period='14',
                                         series_type='close')
    rsi = float(data_rsi.tail(1)["RSI"].iloc[-1])

    # MACD
    data_macd, meta_data_macd = ti.get_macd(symbol=str(ticker),
                                            interval='30min',
                                            series_type='close',
                                            fastperiod='12',
                                            slowperiod='26',
                                            signalperiod='9')
    macd = float(data_macd["MACD_Hist"].head(1).iloc[-1])
    prevMacd = float(data_macd["MACD_Hist"].head(2).iloc[-1])

    # EMA
    data_ema, meta_data_ema = ti.get_ema(ticker,
                                         interval='30min',
                                         time_period=9,
                                         series_type='close')
    ema = data_ema["EMA"].tail(1).iloc[-1]

    # Stoch
    # data_stoch, meta_data_stoch = ti.get_stoch(symbol = ticker, interval='30min')
    # print(data_stoch.head(1))
    # slowD = data_stoch.head(1)['SlowD'].iloc[-1]
    # slowK = data_stoch.head(1)['SlowK'].iloc[-1]

    # Intraday
    data_intra, meta_data_intra = ts.get_intraday(ticker,
                                                  interval='30min',
                                                  outputsize='compact')
    low = data_intra.head(1)['3. low'].iloc[-1]
    prevLow = data_intra.head(2)['3. low'].iloc[-1]

    # print(data_intra.head(3))
    # lastLow = data_intra.head(3)['4. close'].iloc[-1]
    # volume = data_intra.head(1)['5. volume'].iloc[-1]
    # prevVol = data_intra.head(2)['5. volume'].iloc[-1]

    return ((low > ema) and (macd > float(0.05)) and (rsi < 71)
            and (macd - prevMacd > 0.0) and (low < float(100))
            and ((low - prevLow) > 0.0) and ((low - lastLow) > 0.0))
Exemplo n.º 11
0
def getEMA(message):
    try:
        ts = TechIndicators(key='ZBRM5PCHPIYQV8BY', output_format='pandas')
        data, meta_data = ts.get_ema(tic, interval=interval, time_period=60)
        data.plot()
        plt.title('ema indicator for ' + tic + ' stock')
        plt.savefig('ema.png')
        plt.close()
        photo = open("ema.png", 'rb')
        bot.send_photo(message.chat.id, photo)
    except Exception as e:
        markup = types.ReplyKeyboardMarkup()
        markup.row('get back')
        bot.send_message(message.chat.id,
                         "ooops... something got wrong",
                         reply_markup=markup)
Exemplo n.º 12
0
 def getEMA26(self):
     whatever = None
     while whatever is None:
         try:
             ti = TechIndicators(key='JMCHDT9XJ90DOIQL',
                                 output_format='pandas')
             data, metadata = ti.get_ema(symbol=self.symbol,
                                         interval='1min',
                                         time_period='26',
                                         series_type='close')
             whatever = data
             return [
                 float(data.iloc[data.shape[0] - 2]),
                 float(data.iloc[data.shape[0] - 1])
             ]
         except KeyError:
             pass
Exemplo n.º 13
0
def fetch_stock_data(ticker, sma=False, ema=False):
	api_key = 'FP2YNP4PVWVSKZ4J'
	ts = TimeSeries(key=api_key, output_format='pandas')
	ts_data, ti_meta_data = ts.get_daily(symbol=ticker, outputsize='full')

	output_df = ts_data

	if sma or rsi or ema:
		
		ti = TechIndicators(key=api_key, output_format='pandas')
		
		if sma:
			sma_data, sma_meta_data = ti.get_sma(symbol=ticker, interval='daily', time_period=180, series_type='open')
			output_df = pd.merge(output_df, sma_data, left_index=True, right_index=True)
		
		if ema:
			ema_data, ema_meta_data = ti.get_ema(symbol=ticker, interval='daily', time_period=20, series_type='open')
			output_df = pd.merge(output_df, ema_data, left_index=True, right_index=True)

	print(output_df.head())
	return output_df
Exemplo n.º 14
0
def getIndicators(stocks, plot=False, write_to_csv=False):
    for stock in stocks:
        ti = TechIndicators(key='UOVDY8C1SRAQHY5D', output_format='pandas')
        data, meta_data = ti.get_ema(symbol=stock,
                                     interval='60min',
                                     time_period=20)

        for key, val in meta_data.items():
            print(key[3:] + ': ' + str(val))

        if plot:
            data.plot()
            plt.title('Ema Indicator for the ' + stock + ' stock (60 min)')
            plt.xticks(
                rotation=15)  # Help prevent axis labels from overlapping
            plt.show()

        if write_to_csv:
            csv_data = pd.DataFrame(data)
            csv_data.to_csv("../indicators_data/EMA/" + stock + ".csv",
                            index=False)
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.º 16
0
    # get PriceData
    weekly_price, price_meta = ts.get_weekly_adjusted(symbol)
    del weekly_price["7. dividend amount"]
    weekly_price = weekly_price.sort_index()  # sort to newst date last

    # get MACD
    macd_weekly, macd_meta = ti.get_macd(symbol,
                                         interval="weekly",
                                         fastperiod=12,
                                         slowperiod=26,
                                         signalperiod=9)
    macd_weekly = macd_weekly.sort_index()

    # get EMA
    ema13_weekly, ema13_meta = ti.get_ema(symbol,
                                          interval="weekly",
                                          time_period=13)
    ema13_weekly = ema13_weekly.sort_index()

    # join everything
    weekly_data = weekly_price.join(macd_weekly.join(ema13_weekly))

    def elder_impulse(idx):
        if idx == 0:
            return 0

        emaCur = weekly_data["EMA"].iat[idx]
        emaLast = weekly_data["EMA"].iat[idx - 1]
        mhCur = weekly_data["MACD_Hist"].iat[idx]
        mhLast = weekly_data["MACD_Hist"].iat[idx - 1]
Exemplo n.º 17
0
period = 60
symbol = 'MSFT'
interval = '60min'  #1min, 15min, 30min, 60min

ts = TimeSeries(key=api_key, output_format='pandas')
data_ts, meta_data_ts = ts.get_intraday(symbol=symbol,
                                        interval=interval,
                                        outputsize='full')
ti_sma = TechIndicators(key=api_key, output_format='pandas')
data_ti_sma, meta_data_ti_sma = ti_sma.get_sma(symbol=symbol,
                                               interval=interval,
                                               time_period=period,
                                               series_type='close')
ti_ema = TechIndicators(key=api_key, output_format='pandas')
data_ti_ema, meta_data_ti_ema = ti_ema.get_ema(symbol=symbol,
                                               interval=interval,
                                               time_period=period,
                                               series_type='close')
ti_rsi = TechIndicators(key=api_key, output_format='pandas')
data_ti_rsi, meta_data_ti_rsi = ti_rsi.get_rsi(symbol=symbol,
                                               interval=interval,
                                               time_period=period,
                                               series_type='close')

# In[5]:

df1 = data_ti_sma
df2 = data_ti_ema
df3 = data_ti_rsi
df4 = data_ts['4. close'].iloc[period - 1::]
#df2.index = df1.index
Exemplo n.º 18
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.º 19
0
def data_to_csv(ticker, dire):
    # Your key here - keep it - not an issue, free
    key = '6LGG0QGAGBROB2M6'

    # make the directory if it doesn't exist
    if os.path.isdir(dire) == False:
        os.mkdir(ticker)
        os.mkdir(dire)

    ts = TimeSeries(key=key, output_format='pandas')
    ti = TechIndicators(key=key, output_format='pandas')

    ### PRICE ###############################################################
    intra, meta = ts.get_intraday(symbol=ticker,
                                  interval='1min',
                                  outputsize='full')
    intra.to_csv(dire + ticker + "_prices.csv")

    ### SMA #################################################################
    sma8, meta = ti.get_sma(symbol=ticker, interval='1min', time_period=8)
    sma8.to_csv(dire + ticker + "_sma8.csv")

    ### EMA #################################################################
    ema8, meta = ti.get_ema(symbol=ticker, interval='1min', time_period=8)
    ema8.to_csv(dire + ticker + "_ema8.csv")

    ### VWAP ################################################################
    vwap, meta = ti.get_vwap(symbol=ticker, interval='1min')
    vwap.to_csv(dire + ticker + "_vwap.csv")

    ### MACD ################################################################
    macd, meta = ti.get_macd(symbol=ticker, interval='1min')
    macd.to_csv(dire + ticker + "_macd.csv")

    # they limit user to 5 calls per minute and 500 per day for free access #
    print("waiting so we don't overload API (60 seconds...)")
    time.sleep(60)

    ### STOCH ###############################################################
    stoch, meta = ti.get_stoch(symbol=ticker, interval='1min')
    stoch.to_csv(dire + ticker + "_stoch.csv")

    ### RSI #################################################################
    rsi, meta = ti.get_rsi(symbol=ticker, interval='1min', time_period=60)
    rsi.to_csv(dire + ticker + "_rsi.csv")

    ### ADX #################################################################
    adx, meta = ti.get_adx(symbol=ticker, interval='1min', time_period=60)
    adx.to_csv(dire + ticker + "_adx.csv")

    ### CCI #################################################################
    cci, meta = ti.get_cci(symbol=ticker, interval='1min', time_period=60)
    cci.to_csv(dire + ticker + "_cci.csv")

    # TODO: These are tricky, several lines, parse differently, separate indices really
    ### AROON ###############################################################
    aroon, meta = ti.get_aroon(symbol=ticker, interval='1min', time_period=60)
    aroon.to_csv(dire + ticker + "_aroon.csv")

    # they limit user to 5 calls per minute and 500 per day for free access #
    print("waiting so we don't overload API (60 seconds...)")
    time.sleep(60)

    ### BBANDS ###############################################################
    bbands, meta = ti.get_bbands(symbol=ticker,
                                 interval='1min',
                                 time_period=60)
    bbands.to_csv(dire + ticker + "_bbands.csv")
    '''
Exemplo n.º 20
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.º 21
0
import pandas as pd

API_KEY = "your key"
listOfTickers = ["ASX:CBA"]  # , "ASX:CBA", "ASX:MP1"

# Chose your output format, or default to JSON (python dict)
ts = TimeSeries(API_KEY, output_format='pandas')
ti = TechIndicators(API_KEY)

# Get the data, returns a tuple
# data is a pandas dataframe, meta_data is a dict
for ticker in listOfTickers:

    df, df_meta_data = ts.get_daily(symbol=ticker, outputsize='full')
    # aapl_sma is a dict, aapl_meta_sma also a dict
    df_ema, df_meta_sma = ti.get_ema(symbol=ticker)
    df = df.rename_axis(None)
    # generate output file based on current ticker name. Removes "ASX:"
    outfilename = "D:/00git/alphaAdvantageStocks/TestDeleteOutput" + ticker.replace(
        'ASX:', '') + ".pkl"
    test_df = pd.DataFrame.from_dict(df_ema, orient='index', columns=['EMA'])
    print(test_df, df)
    df = pd.concat([df, test_df], axis=1)
    # df["Vol20dAvrg"] = map(is_hammer, df["Open"], df["Low"], df["Close"], df["High"])
    print(df.tail())

    # with open(outfilename, 'w') as outfile:
    #     aapl_data.to_pickle(outfilename)

# # Visualization
# figure(num=None, figsize=(15, 6), dpi=80, facecolor='w', edgecolor='k')
Exemplo n.º 22
0
def get_daily_history(token_1, symbol, amount_of_entries=1000):
    ts_1 = TimeSeries(key=token_1, output_format='pandas')
    ti_1 = TechIndicators(key=token_1, output_format='pandas')

    print('get_daily_history')

    interval = 'daily'
    series_type = 'open'

    # Fetch dataset from api
    # OHLC series #1
    time_series, meta_time_series = ts_1.get_daily(symbol=symbol, outputsize='full')
    # Bollinger Bands #2
    bbands, meta = ti_1.get_bbands(symbol=symbol, interval=interval, time_period=60, series_type=series_type)
    bbands = bbands.sort_index(ascending=False)
    # SMA10 or MA10 #3
    sma_10, meta = ti_1.get_sma(symbol=symbol, interval=interval, time_period=10, series_type=series_type)
    sma_10 = sma_10.sort_index(ascending=False)
    # SMA5 or MA5 #4
    sma_5, meta = ti_1.get_sma(symbol=symbol, interval=interval, time_period=5, series_type=series_type)
    sma_5 = sma_5.sort_index(ascending=False)
    # ROC #5
    roc_20, meta = ti_1.get_roc(symbol=symbol, interval=interval, time_period=20, series_type=series_type)
    roc_20 = roc_20.sort_index(ascending=False)
    # Wait 70 seconds
    print('waiting 70 seconds');
    sleep(70)
    # MACD #1
    macd, meta = ti_1.get_macd(symbol=symbol, interval=interval, series_type=series_type)
    macd = macd.sort_index(ascending=False)
    # CCI #2
    cci_20, meta = ti_1.get_cci(symbol=symbol, interval=interval, time_period=20)
    cci_20 = cci_20.sort_index(ascending=False)
    # ATR #3
    atr_20, meta = ti_1.get_atr(symbol=symbol, interval=interval, time_period=20)
    atr_20 = atr_20.sort_index(ascending=False)
    # EMA20 #4
    ema_20, meta = ti_1.get_ema(symbol=symbol, interval=interval, time_period=20, series_type=series_type)
    ema_20 = ema_20.sort_index(ascending=False)
    # MTM6 #5
    mtm_6, meta = ti_1.get_mom(symbol=symbol, interval=interval, time_period=180, series_type=series_type)
    mtm_6 = mtm_6.sort_index(ascending=False)
    # Wait 70 seconds
    print('waiting 70 seconds');
    sleep(70)
    # MTM12 #1
    mtm_12, meta = ti_1.get_mom(symbol=symbol, interval=interval, time_period=360, series_type=series_type)
    mtm_12 = mtm_12.sort_index(ascending=False)

    # Get last n data points in the dataset and set your respective column name
    d1 = time_series[:amount_of_entries];
    d1.columns = ['open', 'high', 'low', 'close', 'volume']
    d2 = sma_10[:amount_of_entries]
    d2.columns = ['sma10']
    d3 = sma_5[:amount_of_entries]
    d3.columns = ['sma5']
    d4 = pd.DataFrame(bbands['Real Middle Band'][:amount_of_entries])
    d4.columns = ['bbands']
    d5 = roc_20[:amount_of_entries]
    d5.columns = ['roc']
    d6 = pd.DataFrame(macd['MACD'][:amount_of_entries])
    d6.columns = ['macd']
    d7 = cci_20[:amount_of_entries]
    d7.columns = ['cci']
    d8 = atr_20[:amount_of_entries]
    d8.columns = ['atr']
    d9 = ema_20[:amount_of_entries]
    d9.columns = ['ema20']
    d10 = mtm_6[:amount_of_entries]
    d10.columns = ['mtm6']
    d11 = mtm_12[:amount_of_entries]
    d11.columns = ['mtm12']
    # Merge elements
    merged = d1.merge(d2, left_index=True, right_index=True)
    merged = merged.merge(d3, left_index=True, right_index=True)
    merged = merged.merge(d4, left_index=True, right_index=True)
    merged = merged.merge(d5, left_index=True, right_index=True)
    merged = merged.merge(d6, left_index=True, right_index=True)
    merged = merged.merge(d7, left_index=True, right_index=True)
    merged = merged.merge(d8, left_index=True, right_index=True)
    merged = merged.merge(d9, left_index=True, right_index=True)
    merged = merged.merge(d10, left_index=True, right_index=True)
    merged = merged.merge(d11, left_index=True, right_index=True)

    sep = os.path.sep
    filename = 'datasets'+sep+'history_'+symbol+'.csv'
    merged.to_csv(filename, index=True)
    return merged, meta_time_series
Exemplo n.º 23
0
    'QCOM', 'SLAB', 'SIMO', 'SWKS', 'TSM', 'TER', 'TXN', 'XLNX', 'GOOG',
    'SBUX', 'SNE', 'TSLA', 'MMM', 'AXP', 'AAPL', 'BA', 'CAT', 'CVX', 'CSCO',
    'KO', 'DIS', 'DD', 'XOM', 'GE', 'GS', 'HD', 'IBM', 'INTC', 'JNJ', 'JPM',
    'MCD', 'MRK', 'MSFT', 'NKE', 'PFE', 'PG', 'TRV', 'UTX', 'UNH', 'VZ', 'V',
    'WMT', 'MU', 'MRNA', 'NIO', 'GILD', 'AMD', 'AMZN', 'T', 'COST', 'NFLX',
    'PYPL'
]
watchlist = [
    'TSLA', 'AAPL', 'AMZN', 'MSFT', 'GOOG', 'FB', 'AMD', 'NVDA', 'NIO', 'PLTR',
    'SQ'
]
sybmL = ['NKLA']

for sym in sybmL:
    data5, meta_data5 = ti.get_ema(symbol=sym,
                                   interval='daily',
                                   time_period=5,
                                   series_type='close')
    time.sleep(12)
    pprint(data5.tail(1))
    data20, meta_data20 = ti.get_ema(symbol=sym,
                                     interval='daily',
                                     time_period=20,
                                     series_type='close')
    time.sleep(12)
    pprint(data20.tail(1))

    fiveTwenty = data5.tail(1).values[0] > data20.tail(1).values[0]

    print(sym + " " + str(fiveTwenty))
Exemplo n.º 24
0
def main_job():
    global data_EMA_10, data_EMA_20, data_MACD, data_BBands, data_Price

    API_key = '5LDF8BV8UHC3F4Y7'
    TI = TechIndicators(key=API_key, output_format='json')
    TS = TimeSeries(key=API_key, output_format='json')

    Stop_1 = True
    while Stop_1:
        try:
            symbol = 'USDCHF'
            interval = '5min'
            slowperiod = '26'
            signalperiod = '9'
            fastperiod = '12'
            series_type = 'close'
            time_period = '20'
            outputsize = "compact"

            data_Price, meta_data_Price = TS.get_intraday(
                symbol=symbol, interval=interval, outputsize=outputsize)

            data_BBands, meta_data_BBands = TI.get_bbands(
                symbol=symbol,
                interval=interval,
                time_period=time_period,
                series_type=series_type)
            time_period = '10'
            data_EMA_10, meta_data_EMA_50 = TI.get_ema(symbol=symbol,
                                                       interval=interval,
                                                       time_period=time_period,
                                                       series_type=series_type)

            time_period = '20'
            data_EMA_20, meta_data_EMA_200 = TI.get_ema(
                symbol=symbol,
                interval=interval,
                time_period=time_period,
                series_type=series_type)

            data_MACD, meta_data_MACD = TI.get_macd(symbol=symbol,
                                                    interval=interval,
                                                    series_type=series_type,
                                                    fastperiod=fastperiod,
                                                    slowperiod=slowperiod,
                                                    signalperiod=signalperiod)

            Stop_1 = False
        except (UnboundLocalError, ValueError, MaxRetryError, ConnectionError,
                SSLError) as e:
            print(e)
            time.sleep(60)
            pass

    # print(data_EMA_10)
    # print(data_EMA_20)

    # Retrieve EMA 10 and EMA 20 data
    """EMA 10"""
    EMA_10 = list(data_EMA_10.values())
    """Current ema 10"""
    level = EMA_10[0].values()
    current_ema_10 = (float([x for x in level][0]))
    """Previous ema 10"""
    level = EMA_10[1].values()
    previous_ema_10 = (float([x for x in level][0]))
    """EMA 20"""
    EMA_20 = list(data_EMA_20.values())
    """Current ema 20"""
    level = EMA_20[0].values()
    current_ema_20 = (float([x for x in level][0]))
    """Previous ema 20"""
    level = EMA_20[1].values()
    previous_ema_20 = (float([x for x in level][0]))

    # Check for crossover between EMA 10 and EMA 20

    current_diff = current_ema_10 - current_ema_20
    prev_diff = previous_ema_10 - previous_ema_20

    file_name = 'Crossing_Flags_EMA.json'

    with open(file_name) as f_obj:
        data = f_obj.read()
        retrieve = json.loads(data)

    Prev_Cross_Up = retrieve['Cross_Up']
    Prev_Cross_Down = retrieve['Cross_Down']

    Crossing_Flag = {}

    if current_diff >= 0 > prev_diff:
        Crossing_Flag['Cross_Up'] = Prev_Cross_Up
        Crossing_Flag['Cross_Down'] = True
    elif current_diff <= 0 < prev_diff:
        Crossing_Flag['Cross_Up'] = True
        Crossing_Flag['Cross_Down'] = Prev_Cross_Down
    else:
        Crossing_Flag['Cross_Up'] = Prev_Cross_Up
        Crossing_Flag['Cross_Down'] = Prev_Cross_Down

    # Update the Crossing flag folder
    file_name = "Crossing_Flags_EMA.json"

    with open(file_name, "w") as f_obj:
        json.dump(Crossing_Flag, f_obj)

    # Retrieve MACD data
    """MACD"""
    MACD = list(data_MACD.values())
    current_Hist = float(MACD[0]['MACD_Hist'])
    prev_Hist = float(MACD[1]['MACD_Hist'])

    file_name = 'Crossing_Flags_MACD.json'

    with open(file_name) as f_obj:
        data = f_obj.read()
        retrieve = json.loads(data)

    Prev_Cross_Up = retrieve['Cross_Up']
    Prev_Cross_Down = retrieve['Cross_Down']

    Crossing_Flag = {}

    if "-" not in str(prev_Hist) and "-" in str(current_Hist):
        Crossing_Flag['Cross_Up'] = Prev_Cross_Up
        Crossing_Flag['Cross_Down'] = True
    elif "-" in str(prev_Hist) and "-" not in str(current_Hist):
        Crossing_Flag['Cross_Up'] = True
        Crossing_Flag['Cross_Down'] = Prev_Cross_Down
    else:
        Crossing_Flag['Cross_Up'] = Prev_Cross_Up
        Crossing_Flag['Cross_Down'] = Prev_Cross_Down

    file_name = "Crossing_Flags_MACD.json"

    with open(file_name, "w") as f_obj:
        json.dump(Crossing_Flag, f_obj)

    # Retrieve crossing data for EMA and MACD
    file_name = 'Crossing_Flags_MACD.json'

    with open(file_name) as f_obj:
        data = f_obj.read()
        retrieve = json.loads(data)

    MACD_Up = retrieve['Cross_Up']
    MACD_Down = retrieve['Cross_Down']

    file_name = 'Crossing_Flags_EMA.json'

    with open(file_name) as f_obj:
        data = f_obj.read()
        retrieve = json.loads(data)

    EMA_Up = retrieve['Cross_Up']
    EMA_Down = retrieve['Cross_Down']

    # Retrieve price and bollinger band data
    BBands = list(data_BBands.values())
    middle_band = float(BBands[0]['Real Middle Band'])

    Price = list(data_Price.values())
    Price = float(Price[0]['4. close'])

    Trigger_Flags = {}

    if MACD_Up and EMA_Up:
        if Price < middle_band:
            Buy_flag = True
            Sell_flag = False
        else:
            Buy_flag = False
            Sell_flag = False
    elif MACD_Down and EMA_Down:
        if Price > middle_band:
            Buy_flag = False
            Sell_flag = True
        else:
            Buy_flag = False
            Sell_flag = False
    else:
        Buy_flag = False
        Sell_flag = False

    Trigger_Flags["Buy_flag"] = Buy_flag
    Trigger_Flags["Sell_flag"] = Sell_flag

    file_name = "Trigger_Flags.json"
    with open(file_name, "w") as f_obj:
        json.dump(Trigger_Flags, f_obj)
Exemplo n.º 25
0
data, metadata =TS.get_intraday(symbol=Ticker, interval=datainterval,outputsize="full") #names the columns and gets intraday data for symbol MSFT (generalize this later)
d1=data[::-1] #for some reason the time series data is list in reverse in the dataframe, this corrects that
d1subset=d1[startdatetime:enddatetime]


#creating technical indicators for buy and sell signals

TI=TechIndicators(key=APIkey,output_format='pandas') #getting technical indicator and setting output to pandas dataframe

dataSMA200, metadataSMA200 = TI.get_sma(symbol=Ticker, interval=datainterval, time_period=200) #200 periodSMA
dataSMA200subset = dataSMA200[startdatetime:enddatetime]

dataSMA, metadataSMA = TI.get_sma(symbol=Ticker, interval=datainterval, time_period=50) #50 periodSMA
dataSMAsubset = dataSMA[startdatetime:enddatetime]

dataEMA, metadataEMA = TI.get_ema(symbol=Ticker, interval=datainterval,time_period=10) #20 PeriodEMA
dataEMAsubset = dataEMA[startdatetime:enddatetime]

# dataRSI, metadataRSI = TI.get_rsi(symbol=Ticker, interval=datainterval,time_period=14)
# dataRSIsubset = dataRSI[startdatetime:enddatetime]


### creating data frame with all of closing price and technical indicators

total_df = pd.concat([d1subset["4. close"],dataSMAsubset,dataSMA200subset, dataEMAsubset], axis=1)
total_df.columns=["Closing_Price","50_SMA","200_SMA","10_EMA"]


#create buy and sell signals based off of moving average crossover.
#genereates BUY signal when 10 EMA crosses 50SMA while above 200 SMA, SELL when crossing back below 50SMA
#Also generates BUY signal when 10 EMA crosses above 200 SMA, signifying the the stock has strong momentum, sells if 10EMA crosses below 50SMA or 200SMA
Exemplo n.º 26
0
# datetime have differrent format
for idx, el in enumerate(data.index._data):
    data.index._data[idx] = el[:-3]
data["trend"] = data["4. close"].subtract(data["1. open"], fill_value=0)
del data["4. close"]
del data["1. open"]

print data.shape

ti = TechIndicators(key=apikey, output_format='pandas')
#1
bbands, meta_data_bbands = ti.get_bbands(symbol=stock, interval=t_period, series_type=series_type)
print bbands.shape
#2
ema, meta_data_ema = ti.get_ema(symbol=stock, interval=t_period, series_type= series_type)
print ema.shape
#3
wma, meta_data_wma = ti.get_wma(symbol=stock, interval=t_period, series_type= series_type)
print wma.shape
#4
sma, meta_data_sma = ti.get_sma(symbol=stock, interval=t_period, series_type= series_type)
print sma.shape
#5
rsi, meta_data_rsi = ti.get_rsi(symbol=stock, interval=t_period, series_type= series_type)
print rsi.shape
#6
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)
Exemplo n.º 27
0
    pass
# Get json object with the intraday data and another with  the call's metadata
# data, meta_data = ts.get_intraday('GOOGL', interval='15min')
# print (data)

# this strategy takes account of ema4/8, sma20/50, bb20, macd12/26, rsi14,
# and volume. 
# It detects abnomal activities, and suggests a potential trend base on 
# analysises from multiple time-window
count = 10
trend_period = 5
ema4his = deque(maxlen=trend_period)
ema8his = deque(maxlen=trend_period)
his_len = 5
while True:
    ema4, ema4_meta = ti.get_ema(symbol='GOOGL', interval='1min', time_period=4)
    ema8, ema8_meta = ti.get_ema(symbol='GOOGL', interval='1min', time_period=8)
#    sorted4ema = collections.OrderedDict(sorted(ema4.keys()))
    keys = sorted(ema4)[-trend_period:]
    print (keys[-1:])
    v4 = []
    v8 = []
    t = []
    for k in keys:
        v4.append(float(ema4[k]['EMA']))
        v8.append(float(ema8[k]['EMA']))
        t.append(time.mktime(dateutil.parser.parse(k).timetuple()))
    v4 = np.array(v4)
    v8 = np.array(v8)
    t = np.array(t)
outputsize = 'compact'
interval = input(
    'Interval- 1min,5min,15min,30min,60min,daily,weekly,monthly : ')
time = input('Time Period : ')
tech_indi = input(
    'Technical Indicator- SMA,EMA,VWAP,MACD,Stochastic Oscillator,RSI,Bollinger bands :'
)
ti = TechIndicators(key, output_format='pandas')
if tech_indi == 'SMA':
    state = ti.get_sma(symbol,
                       interval=interval,
                       time_period=time,
                       series_type='close')[0]
elif tech_indi == 'EMA':
    state = ti.get_ema(symbol,
                       interval=interval,
                       time_period=time,
                       series_type='close')[0]
elif tech_indi == 'VWAP':
    state = ti.get_vwap(symbol, interval=interval)[0]
elif tech_indi == 'MACD':
    state = ti.get_macd(symbol, interval=interval, series_type='close')[0]
elif tech_indi == 'Stochastic Oscillator':
    state = ti.get_stoch(symbol, interval=interval)[0]
elif tech_indi == 'RSI':
    state = ti.get_rsi(symbol,
                       interval=interval,
                       time_period=time,
                       series_type='close')[0]
elif tech_indi == 'Bollinger bands':
    state = ti.get_bbands(symbol,
                          interval=interval,
Exemplo n.º 29
0
#support.plot()
stonks.plot()

m, b = np.polyfit(highindexes, highpoints, 1)
# toppy line ^^
a, z = np.polyfit(lowindexes, lowpoints, 1)
# m, b = np.polyfit(stonks.index,stonks.values, 1)
# plt.plot(stonks.index, ((a + m) / 2) * stonks.index + ((b + z) / 2))
plt.plot(stonks.index, m * stonks.index + b)
plt.plot(stonks.index, a * stonks.index + z)
plt.ylabel("Price ($)")
plt.xlabel("Days")

t1 = TechIndicators(output_format='pandas', key=key)
ema200, meta = t1.get_ema(symbol=symbol,
                          interval='daily',
                          time_period=200,
                          series_type='close')
ema50, meta = t1.get_ema(symbol=symbol,
                         interval='daily',
                         time_period=50,
                         series_type='close')
ema200 = ema200.tail(100)
ema200.index = np.arange(100)
ema50 = ema50.tail(100)
ema50.index = np.arange(100)

ema50_m, ema50_b = np.polyfit(ema50.index, ema50, 1)
ema200_m, ema200_b = np.polyfit(ema200.index, ema200, 1)
plt.plot(ema50.index,
         ema50_m * ema50.index + ema50_b,
         label="50 Day Moving Average")
Exemplo n.º 30
0
def init_data(comp, interval):

    # Input all the technical indicators and the stock times series data

    # Initialize the AlphaVantage API call functions
    ts = TimeSeries(key='L2O2TYTG382ETN0N', output_format='pandas')
    ti = TechIndicators(key='L2O2TYTG382ETN0N', output_format='pandas')

    # Other keys: QB5APLD84E50TQAC, L2O2TYTG382ETN0N

    # Fetch the simple moving average (SMA) values
    main_data, meta_data = ti.get_sma(symbol=comp,
                                      interval='60min',
                                      time_period=20,
                                      series_type='close')

    time.sleep(3)

    # Fetch the exponential moving average (EMA) values
    ema_data, meta_data = ti.get_ema(symbol=comp,
                                     interval='60min',
                                     time_period=20,
                                     series_type='close')
    main_data['EMA'] = ema_data

    time.sleep(3)
    """
		# Fetch the weighted moving average (WMA) values
		wma_data, meta_data = ti.get_wma(symbol=comp,interval='60min', time_period=10, series_type='close')
		main_data['WMA'] = wma_data
		
		# Fetch the double exponential moving agerage (DEMA) values
		dema_data, meta_data = ti.get_dema(symbol=comp,interval='60min', time_period=10, series_type='close')
		main_data['DEMA'] = dema_data
		
		# Fetch the triple exponential moving average (TEMA) values
		tema_data, meta_data = ti.get_tema(symbol=comp,interval='60min', time_period=10, series_type='close')
		main_data['TEMA'] = tema_data
		
		# Fetch the triangular moving average (TRIMA) values 
		trima_data, meta_data = ti.get_trima(symbol=comp,interval='60min', time_period=10, series_type='close')
		main_data['TRIMA'] = trima_data

		# Fetch the Kaufman adaptive moving average (KAMA) values
		kama_data, meta_data = ti.get_kama(symbol=comp,interval='60min', time_period=10, series_type='close')
		main_data['KAMA'] = kama_data		

		# Fetch the MESA adaptive moving average (MAMA) values
		mama_data, meta_data = ti.get_mama(symbol=comp,interval='60min', time_period=10, series_type='close')
		main_data['MAMA'] = mama_data['MAMA']
		main_data['FAMA'] = mama_data['FAMA']

		# Fetch the triple exponential moving average (T3) values
		t3_data, meta_data = ti.get_t3(symbol=comp,interval='60min', time_period=10, series_type='close')
		main_data['T3'] = t3_data	
		"""

    # Fetch the moving average convergence / divergence (MACD) values
    macd_data, meta_data = ti.get_macd(symbol=comp,
                                       interval='60min',
                                       series_type='close')
    main_data['MACD'] = macd_data['MACD']
    main_data['MACD_Hist'] = macd_data['MACD_Hist']
    main_data['MACD_Signal'] = macd_data['MACD_Signal']

    time.sleep(3)
    """		
		# Fetch the moving average convergence / divergence values with controllable moving average type
		macdext_data, meta_data = ti.get_macdext(symbol=comp,interval='60min', series_type='close')
		main_data['MACDEXT'] = macdext_data['MACD']
		main_data['MACDEXT_Hist'] = macdext_data['MACD_Hist']
		main_data['MACDEXT_Signal'] = macdext_data['MACD_Signal']
		"""

    # Fetch the stochastic oscillator (STOCH) values
    stoch_data, meta_data = ti.get_stoch(symbol=comp, interval='60min')
    main_data['SlowK'] = stoch_data['SlowK']
    main_data['SlowD'] = stoch_data['SlowD']

    time.sleep(3)
    """
		# Fetch the stochastic fast (STOCHF) values
		stochf_data, meta_data = ti.get_stochf(symbol=comp,interval='60min')
		main_data['FastK'] = stochf_data['FastK']
		main_data['FastD'] = stochf_data['FastD']
		"""

    # Fetch the relative strength index (RSI) values
    rsi_data, meta_data = ti.get_rsi(symbol=comp,
                                     interval='60min',
                                     time_period=10,
                                     series_type='close')
    main_data['RSI'] = rsi_data

    time.sleep(3)
    """
		# Fetch the stochastic relative strength index (STOCHRSI) values
		stochrsi_data, meta_data = ti.get_stochrsi(symbol=comp,interval='60min', time_period=10, series_type='close')
		main_data['STOCHRSI_FastK'] = stochrsi_data['FastK']
		main_data['STOCHRSI_FastD'] = stochrsi_data['FastD']

		# Fetch the Williams' %R (WILLR) values
		willr_data, meta_data = ti.get_willr(symbol=comp,interval='60min', time_period=10)
		main_data['WILLR'] = willr_data
		"""

    # Fetch the average directional movement index (ADX) values
    adx_data, meta_data = ti.get_adx(symbol=comp,
                                     interval='60min',
                                     time_period=20)
    main_data['ADX'] = adx_data

    time.sleep(3)
    """
		# Fetch the average directional movement index rating (ADXR) values
		adxr_data, meta_data = ti.get_adxr(symbol=comp,interval='60min', time_period=10)
		main_data['ADXR'] = adxr_data

		# Fetch the absolute price oscillator (APO) values
		apo_data, meta_data = ti.get_apo(symbol=comp,interval='60min', series_type='close')
		main_data['APO'] = apo_data

		# Fetch the percentage price oscillator (PPO) values
		ppo_data, meta_data = ti.get_ppo(symbol=comp,interval='60min', series_type='close')
		main_data['PPO'] = ppo_data

		# Fetch the momentum (MOM) values
		mom_data, meta_data = ti.get_mom(symbol=comp,interval='60min', time_period=10, series_type='close')
		main_data['MOM'] = mom_data

		# Fetch the balance of power (BOP) values
		bop_data, meta_data = ti.get_bop(symbol=comp,interval='60min')
		main_data['BOP'] = bop_data
		"""

    # Fetch the commodity channel index (CCI) values
    cci_data, meta_data = ti.get_cci(symbol=comp,
                                     interval='60min',
                                     time_period=20)
    main_data['CCI'] = cci_data

    time.sleep(3)
    """
		# Fetch the Chande momentum oscillator (CMO) values
		cmo_data, meta_data = ti.get_cmo(symbol=comp,interval='60min', time_period=10, series_type='close')
		main_data['CMO'] = cmo_data

		# Fetch the rate of change (ROC) values
		roc_data, meta_data = ti.get_roc(symbol=comp,interval='60min', time_period=10, series_type='close')
		main_data['ROC'] = roc_data


		# Fetch the rate of change ratio (ROCR) values
		rocr_data, meta_data = ti.get_rocr(symbol=comp,interval='60min', time_period=10, series_type='close')
		main_data['ROCR'] = rocr_data

		time.sleep(5)
		"""
    # Fetch the Aroon (AROON) values
    aroon_data, meta_data = ti.get_aroon(symbol=comp,
                                         interval='60min',
                                         time_period=20)
    main_data['Aroon Down'] = aroon_data['Aroon Down']
    main_data['Aroon Up'] = aroon_data['Aroon Up']

    time.sleep(3)
    """
		# Fetch the Aroon oscillator (AROONOSC) values
		aroonosc_data, meta_data = ti.get_aroonosc(symbol=comp,interval='60min', time_period=10)
		main_data['AROONOSC'] = aroonosc_data

		# Fetch the money flow index (MFI) values
		mfi_data, meta_data = ti.get_mfi(symbol=comp,interval='60min', time_period=10)
		main_data['MFI'] = mfi_data

		# Fetch the 1-day rate of change of a triple smooth exponential moving average (TRIX) values
		triX_train_data['AAPL'], meta_data = ti.get_trix(symbol=comp,interval='60min', time_period=10, series_type='close')
		main_data['TRIX'] = triX_train_data['AAPL']

		# Fetch the ultimate oscillator (ULTOSC) values
		ultosc_data, meta_data = ti.get_ultsoc(symbol=comp,interval='60min', time_period=10)
		main_data['ULTOSC'] = ultosc_data

		# Fetch the directional movement index (DX) values
		dX_train_data['AAPL'], meta_data = ti.get_dx(symbol=comp,interval='60min', time_period=10)
		main_data['DX'] = dX_train_data['AAPL']
		"""
    """
		# Fetch the Chaikin A/D line (AD) value
		ad_data, meta_data = ti.get_ad(symbol=comp,interval='60min')
		main_data['AD'] = ad_data
		"""

    # Fetch the on balance volume (OBV) values
    obv_data, meta_data = ti.get_obv(symbol=comp, interval='60min')
    main_data['OBV'] = obv_data

    intraday_data, meta_data = ts.get_intraday(symbol=comp,
                                               interval='60min',
                                               outputsize='full')

    intraday_data.index = pd.Index(
        [index[:-3] for index in intraday_data.index], name='date')
    #intraday_data.set_index('date')

    main_data = pd.concat([main_data, intraday_data], axis=1)
    print(main_data.index)

    print(main_data.head())

    main_data = main_data.dropna()
    main_data.index.name = 'date'

    company = comp
    main_data.to_csv(f'./rsc/{company}_AV_data.csv', sep=',')

    time.sleep(1)

    print(comp)

    time.sleep(5)