Exemplo n.º 1
0
def save_csv(stock, time_window, indicators):
    api_key = av_key
    print(stock, time_window)
    ts = TimeSeries(key=api_key, output_format='pandas')
    ti = TechIndicators(key=api_key, output_format='pandas')

    if time_window.upper() == 'DAILY':
        data, meta_data = ts.get_daily(symbol=stock, outputsize='full')
    elif time_window.upper() == 'INTRADAILY':
        data, meta_data = ts.get_intraday(symbol=stock,
                                          interval='1min',
                                          outputsize='full')
    else:
        print('Invalid Time Window.')
        return

    data = data.sort_values(by=['date'], ascending=True)
    pprint(data.head(10))
    data.to_csv(f'./charts/{stock}_{time_window.lower()}.csv')

    for indicator in indicators:
        # Daily values (throughout the past year)
        if time_window.upper() == 'DAILY':
            if indicator.upper() == 'SMA':
                data, meta_data = ti.get_sma(symbol=stock,
                                             interval='daily',
                                             series_type='close')
            elif indicator.upper() == 'RSI':
                data, meta_data = ti.get_rsi(symbol=stock,
                                             interval='daily',
                                             series_type='close')
            elif indicator.upper() == 'MACD':
                data, meta_data = ti.get_macd(symbol=stock,
                                              interval='daily',
                                              series_type='close')
        # Intradaily values (throughout the past week)
        else:
            if indicator.upper() == 'SMA':
                data, meta_data = ti.get_sma(symbol=stock,
                                             interval='1min',
                                             series_type='close')
            elif indicator.upper() == 'RSI':
                data, meta_data = ti.get_rsi(symbol=stock,
                                             interval='1min',
                                             series_type='close')
            elif indicator.upper() == 'MACD':
                data, meta_data = ti.get_macd(symbol=stock,
                                              interval='1min',
                                              series_type='close')

        data = data.sort_values(by=['date'], ascending=True)
        pprint(data.head(10))
        data.to_csv(
            f'./charts/{stock}_{time_window.lower()}_{indicator.lower()}.csv')
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 getData(key, stock):

    tS = TimeSeries(key=key, output_format='pandas', indexing_type='date')
    tI = TechIndicators(key=key, output_format='pandas')

    data, meta_data = tS.get_daily_adjusted(symbol=stock, outputsize='full')
    macd, macd_meta = tI.get_macd(symbol=stock,
                                  interval='daily',
                                  series_type='close')
    rsi, rsi_meta = tI.get_rsi(symbol=stock,
                               interval='daily',
                               time_period=14,
                               series_type='close')
    willr, willr_meta = tI.get_willr(symbol=stock,
                                     interval='daily',
                                     time_period=14)
    adx, adx_meta = tI.get_adx(symbol=stock, interval='daily', time_period=14)
    mom, mom_meta = tI.get_mom(symbol=stock,
                               interval='daily',
                               time_period=10,
                               series_type='close')

    all_vals = [data, macd, rsi, willr, adx, mom]

    final_df = pd.concat(
        all_vals, axis=1, sort=True
    )  # Sort arg may need to be False, leaving it blank raises Pandas error
    final_df = final_df.dropna()
    df = final_df.iloc[::-1]
    df = df.reset_index()
    df = df.drop(['6. volume', '7. dividend amount'], axis=1)

    return df
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
class ApiConnector:
    """
    Responsability: To connecto to the alpha vantage api.
    """

    def __init__(self, api_key):
        """Api objects instanciated with api_key"""
        self.key = api_key
        self.time_app = TimeSeries(api_key)
        # can change the output_format to json which is default
        self.tech_app = TechIndicators(api_key, output_format="json")

    def get_macd(self, stock, time_interval, fastperiod, slowperiod, signalperiod):
        """
        Returns macd_signal, macd, macd_hist
        Interval: '1min', '5min', '15min', '30min', '60min', 'daily',
            'weekly', 'monthly'
        """
        return self.tech_app.get_macd(stock, interval=time_interval, fastperiod=fastperiod, slowperiod=slowperiod, signalperiod=signalperiod, series_type="close")

    def get_days(self, stock):
        """Returns timeseries with close-value each day (20 years back)"""
        return self.time_app.get_daily(stock)

    def get_intraday(self, stock):
        """"interval: '1min', '5min', '15min', '30min', '60min'"""
        return self.time_app.get_intraday(stock, '1min', outputsize="full")
Exemplo n.º 6
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.º 7
0
def grabCompact(key, input_ticker, lookBack):

	# Query ALPHA VANTAGE
	try:
	    tS = TimeSeries(key=key, output_format='pandas', indexing_type='date')
	    tI = TechIndicators(key=key, output_format='pandas')

	    data, meta_data = tS.get_daily_adjusted(symbol=input_ticker, outputsize='compact')
	    macd, macd_meta = tI.get_macd(symbol=input_ticker, interval='daily', series_type='close')
	    rsi, rsi_meta = tI.get_rsi(symbol=input_ticker, interval='daily', time_period=14, series_type='close')
	    willr, willr_meta = tI.get_willr(symbol=input_ticker, interval='daily', time_period=14)
	    adx, adx_meta = tI.get_adx(symbol=input_ticker, interval='daily', time_period=14)
	    mom, mom_meta = tI.get_mom(symbol=input_ticker, interval='daily', time_period=10, series_type='close')

	    all_vals = [data, macd, rsi, willr, adx, mom]

	    final_df = pd.concat(all_vals, axis=1, sort=True) # Sort arg may need to be False, leaving it blank raises Pandas error
	    final_df = final_df.dropna()
	    df = final_df.iloc[::-1]
	    df = df.reset_index()
	    df = df.drop(['6. volume', '7. dividend amount'], axis=1)
	    df = df.drop(df.index[lookBack:])

	    return df

	except:
		print ("There was an error with %s" % input_ticker)

		pass
Exemplo n.º 8
0
def get_raw_input_data(stock="DJI"):
    ts = TimeSeries(key=AV_API_KEY, output_format='pandas')
    d, md = ts.get_daily(symbol=stock, outputsize='compact')
    d = d.loc['2020-01-01':'2020-03-27']
    d[CLOSE] = d[CLOSE].pct_change()
    d = d[d[CLOSE] <= 100]
    d = d.dropna(axis=0)

    TI = TechIndicators(key=AV_API_KEY, output_format='pandas')

    rsi_data, meta_data = TI.get_rsi(symbol=stock,
                                     interval="daily",
                                     time_period=14)
    macd_data, meta_data = TI.get_macd(symbol=stock, interval="daily")
    sma_data, meta_data = TI.get_sma(symbol=stock, time_period=30)
    bbands_data, meta_data = TI.get_bbands(symbol=stock)

    input_data = pd.DataFrame(columns=["Volume", "Price_Change"],
                              index=d.index)
    input_data["Volume"] = d[VOLUME]
    input_data["Price_Change"] = d[CLOSE]
    input_data = input_data.merge(rsi_data, left_index=True, right_index=True)
    input_data = input_data.merge(sma_data, left_index=True, right_index=True)
    input_data = input_data.merge(macd_data, left_index=True, right_index=True)
    input_data = input_data.merge(bbands_data,
                                  left_index=True,
                                  right_index=True)
    input_data = input_data.merge(load_covid(),
                                  left_index=True,
                                  right_index=True)
    input_data = input_data.merge(gen_sentiment_df(stock),
                                  left_index=True,
                                  right_index=True)
    return input_data
Exemplo n.º 9
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.º 10
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.º 11
0
def checkSymbol(symbol, interval, msgInterval, mustCandleBullish = False):
    
    bullish = False
    rate = 0
    gMsg = '#'+symbol + ' '+msgInterval
    
    ts = TimeSeries(key=cfg.APIKey, output_format=cfg.format)
    if interval == cfg.intervalDaily: #daily
        dataTS, meta_data = ts.get_daily(symbol=symbol)
    else:
        dataTS, meta_data = ts.get_intraday(symbol=symbol,interval=interval)
        
    sample = [dict() for x in range(3)]
    
    for i in range(1,4):
        sample[i-1] = {'close':dataTS['close'][-i],'high':dataTS['high'][-i],'low':dataTS['low'][-i],'open':dataTS['open'][-i]}
                
    csp = CandleStickPattern(sample[2],sample[1],sample[0])
    if csp.bullishPattern():
        bullish = True
        rate += 1
        gMsg += '\nCandle Bull'
    else:
        if mustCandleBullish:
            return False, gMsg, rate
    
    ti = TechIndicators(key=cfg.APIKey, output_format=cfg.format)
    ##### bband
    data, meta_data = ti.get_bbands(symbol=symbol, interval=interval)
    # data.plot()
    bbLower = data['Real Lower Band'][-1]
    if sample[0]['low'] < bbLower:
        bullish = True
        rate += 1
        gMsg += '\nBB lower band tested'
    
    ##### MACD
    data, meta_data = ti.get_macd(symbol=symbol, interval=interval, fastperiod=12, slowperiod = 26, signalperiod = 9)
    #print data.keys()
    if data['MACD_Hist'][-1] > 0:
        for i in range(2,6):
            if data['MACD_Hist'][-i] < 0:
                gMsg += '\nMACD cross'
                bullish = True
                rate += 1
                break
    
    if bullish:
        data, meta_data = ti.get_rsi(symbol=symbol, interval = interval)
        if data['RSI'][-1] < 50:
            rate += 1
        gMsg += '\nRSI ' + round(data['RSI'][-1]).__str__()
        gMsg += '\nVol ' + printInK(dataTS['volume'][-1]) +" "+ printInK(dataTS['volume'][-2]) +" "+ printInK(dataTS['volume'][-3])
    
    
    return bullish, gMsg, rate
Exemplo n.º 12
0
    def MACD(stock_name):
        '''
        Moving Average Convergence / Divergence (指数平滑异同移动平均线)
        https://zh.wikipedia.org/wiki/MACD
        '''

        ti = TechIndicators(key=Env.alpha_vantage_api_key, output_format='pandas')
        data, meta_data = ti.get_macd(symbol=stock_name, interval='daily', series_type='close')
        #data.to_csv(stock_name + '_MACD indicator.csv', index=True, sep=',')
        return data.to_json(orient='split')
Exemplo n.º 13
0
def collect_data(ticker: str, interval: str, key):
    """ Collect data from alpha vantage. Currently collects current stock price
        and 5 technical indicators """

    print(f'Collecting data for {ticker}')
    ts = TimeSeries(key)
    ti = TechIndicators(key)

    # get stock price
    price, meta = ts.get_intraday(symbol=ticker,
                                  interval=interval,
                                  outputsize='full')
    price = parse_ts(price).reset_index().rename(columns={'index': 'ts'})
    price['ts'] = pd.to_datetime(price['ts'])
    print(price.head())
    # pause to avoid API throttling limits
    time.sleep(45)

    # get technical indicators
    print('Collecting Technical Indicators')
    rsi = parse_ts(ti.get_rsi(
        symbol=ticker,
        interval=interval)[0]).reset_index().rename(columns={'index': 'ts'})
    rsi['ts'] = pd.to_datetime(rsi['ts'])
    print(rsi.head())
    macd = parse_ts(ti.get_macd(
        symbol=ticker,
        interval=interval)[0]).reset_index().rename(columns={'index': 'ts'})
    macd['ts'] = pd.to_datetime(macd['ts'])
    print(macd.head())
    sar = parse_ts(ti.get_sar(
        symbol=ticker,
        interval=interval)[0]).reset_index().rename(columns={'index': 'ts'})
    sar['ts'] = pd.to_datetime(sar['ts'])
    print(sar.head())
    time.sleep(45)
    adx = parse_ts(ti.get_adx(
        symbol=ticker,
        interval=interval)[0]).reset_index().rename(columns={'index': 'ts'})
    adx['ts'] = pd.to_datetime(adx['ts'])
    print(adx.head())
    stoch = parse_ts(ti.get_stoch(
        symbol=ticker,
        interval=interval)[0]).reset_index().rename(columns={'index': 'ts'})
    stoch['ts'] = pd.to_datetime(stoch['ts'])
    print(stoch.head())

    # merge into single data set
    dfs = [price, rsi, macd, sar, adx, stoch]
    df_final = reduce(
        lambda left, right: pd.merge(left, right, on='ts', how='outer'), dfs)

    return df_final.sort_values('ts').dropna()
Exemplo n.º 14
0
def get_data(symbol):
    #get tech indicators for stock
    ti = TechIndicators(key='5FWAPV1GCOE2WQLV', output_format='pandas')

    sma_, _ = ti.get_sma(symbol=symbol, interval='daily')
    macd_, _ = ti.get_macd(symbol=symbol, interval='daily')
    rsi_, _ = ti.get_rsi(symbol=symbol, interval='daily')
    adx_, _ = ti.get_adx(symbol=symbol, interval='daily')

    ts = TimeSeries(key='5FWAPV1GCOE2WQLV', output_format='pandas')
    data, _ = ts.get_daily(symbol=symbol, outputsize='full')

    final_data = pd.concat([data, sma_, macd_, rsi_, adx_], axis=1, sort=True)
    return final_data
Exemplo n.º 15
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.º 16
0
def checkMACD(message):
    try:
        ts = TechIndicators(key='ZBRM5PCHPIYQV8BY', output_format='pandas')
        data, meta_data = ts.get_macd(tic, interval=interval)
        data.plot()
        plt.title('MACD indicator for ' + tic + ' stock')
        plt.savefig('MACD.png')
        plt.close()
        photo = open("MACD.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.º 17
0
class TechIndicatorClient(object):
    def __init__(self, index=None):
        self.ti = TechIndicators(constants.ALPHA_VANTAGE_API_KEY)
        self.index = index

    def get_full_code(self, stock_code):
        if self.index:
            return stock_code + "." + self.index
        else:
            return stock_code

    def get_macd(self, stock_code):
        stock_code = self.get_full_code(stock_code)
        score = self.ti.get_macd(stock_code,
                                 interval=constants.INTERVAL_60MIN,
                                 series_type=constants.SERIES_TYPE_CLOSE)

        return score

    def get_rsi(self, stock_code):
        stock_code = self.get_full_code(stock_code)
        score = self.ti.get_rsi(stock_code,
                                interval=constants.INTERVAL_60MIN,
                                series_type=constants.SERIES_TYPE_CLOSE)

        return score

    def get_stoch(self, stock_code):
        stock_code = self.get_full_code(stock_code)
        score = self.ti.get_stoch(stock_code,
                                  interval=constants.INTERVAL_60MIN)

        return score

    def get_stochrsi(self, stock_code):
        stock_code = self.get_full_code(stock_code)
        score = self.ti.get_stochrsi(stock_code,
                                     interval=constants.INTERVAL_60MIN)

        return score

    def get_last_value(self, indicator_score):
        last_key = list(indicator_score[0].keys())[0]
        last_score = indicator_score[0][last_key]

        return json.dumps(last_score)
Exemplo n.º 18
0
def grabData(key, input_ticker, delta):
    tS = TimeSeries(key=key, output_format='pandas', indexing_type='date')
    tI = TechIndicators(key=key, output_format='pandas')

    data, meta_data = tS.get_daily_adjusted(symbol=input_ticker, outputsize='full') #compact for last 100 or full for everything
    macd, macd_meta = tI.get_macd(symbol=input_ticker, interval='daily', series_type='close')
    rsi, rsi_meta = tI.get_rsi(symbol=input_ticker, interval='daily', time_period=14, series_type='close')
    willr, willr_meta = tI.get_willr(symbol=input_ticker, interval='daily', time_period=14)
    adx, adx_meta = tI.get_adx(symbol=input_ticker, interval='daily', time_period=14)
    mom, mom_meta = tI.get_mom(symbol=input_ticker, interval='daily', time_period=10, series_type='close')

    all_vals = [data, macd, rsi, willr, adx, mom]

    final_df = pd.concat(all_vals, axis=1, sort=True) # Sort arg may need to be False, leaving it blank raises Pandas error
    final_df = final_df.dropna()
    df = final_df.iloc[::-1]
    df = df.reset_index()
    df = df.drop(['6. volume', '7. dividend amount'], axis=1)

    # *************************************************************************
    
    labels = []
    priceDiffernces = []

    for index, row in df.iterrows():
        if 0 <= index < delta:
            pass
        else:
            initPrice = row[5]
            deltaPrice = df.iloc[index-delta][5]
            priceDiffernces.append(round((deltaPrice-initPrice), 2))

            if deltaPrice > initPrice:
                labels.append(1)
            else:
                labels.append(0)
    
    df = df.drop(list(range(delta)))

    labelsPD = pd.Series(labels)
    priceDiffsPD = pd.Series(priceDiffernces)
    df['Labels'] = labelsPD.values
    df['Price Diffs'] = priceDiffsPD.values

    df.to_csv(input_ticker + '.csv')
Exemplo n.º 19
0
def getMACD(sym):
    global finalList

    ti = TechIndicators(key='GSD3E3P11LSBZG5O', output_format='pandas')
    try:
        data, meta_data = ti.get_macd(symbol=sym, interval='monthly')
    except Exception:
        return

    if len(data) == 0:
        print("Misssing MACD Data!", sym)
        return

    if ((data["MACD_Hist"].iloc[-1]) < 0).all():
        print("failed MACD", sym, (data["MACD_Hist"].iloc[-1]))
    else:
        finalList.put(sym)
        print("passed MACD", sym)
Exemplo n.º 20
0
def MACDIndicator(StockName):
	ti = TechIndicators(key='QBGRPFYFV5WBTTCO', output_format='pandas')
	data, meta_data= ti.get_macd(symbol=StockName, interval='1min', series_type ='close')
	# realdata = data.to_json(orient='table')
	# print(realdata)

	# # data.plot()
	# json_path = './' + StockName +'MACD.json'
	# with open(json_path, "w") as f:
	# 	json.dump(realdata, f)
	# 	print("Complete...")

	# plt.title('MACD indicator for '+ StockName+ ' stock (1 min)')
	# fig = plt.gcf()
	# plt.savefig("MACD.pdf")
	# plt.show()	
	data.to_csv(StockName+'MACD indicator.csv',index=True,sep=',') 

	print('Success')
Exemplo n.º 21
0
def loadMACD(symb, ival):
    try:
        apikey = random.randint(0, 1)
        #print ("Key is {} ie {}".format(apikey,ALPHA_VANTAGE_API_KEY[apikey]))
        ti = TechIndicators(key='ALPHA_VANTAGE_API_KEY[apikey]',
                            output_format='json')
        data, meta_data = ti.get_macd(symbol=symb,
                                      interval=ival,
                                      series_type='close',
                                      fastperiod=12,
                                      slowperiod=26,
                                      signalperiod=9)
        systime.sleep(15)
        return data

    except Exception as e:
        print(e)
        systime.sleep(15)
        return False
Exemplo n.º 22
0
def MACD(stock_name, size, k):
    ti = TechIndicators(key=k)
    hist = []
    signal = []
    macd = []
    temp_data, temp_meta = ti.get_macd(symbol=stock_name,
                                       interval='5min',
                                       fastperiod='12',
                                       slowperiod='26',
                                       signalperiod='9')
    del temp_meta
    for key in temp_data:
        hist.append(float(temp_data[key]['MACD_Hist']))
        signal.append(float(temp_data[key]['MACD_Signal']))
        macd.append(float(temp_data[key]['MACD']))
    del hist[size:], signal[size:], macd[size:]
    hist.reverse()
    signal.reverse()
    macd.reverse()
    return hist, signal, macd
Exemplo n.º 23
0
def check_macd(symbol='', key='', interval='daily', points=5):
    """
    https://mindspace.ru/abcinvest/shozhdenie-rashozhdenie-skolzyashhih-srednih-moving-average-convergence-divergence-macd/
    https://mindspace.ru/abcinvest/aleksandr-elder-o-rashozhdeniyah-tseny-i-macd/
    https://mindspace.ru/30305-kak-ispolzovat-divergentsii-macd-dlya-vyyavleniya-razvorota-na-rynke/
    """
    ti = TechIndicators(key=key, output_format='pandas')
    data, meta_data = ti.get_macd(symbol=symbol, interval=interval)
    macddata = data.tail(points).to_dict()
    last = None
    for macd_date in macddata['MACD_Hist']:
        macd_hist_value = macddata['MACD_Hist'][macd_date]
        if not last:
            last = macd_hist_value
            continue

        if last > 0 and macd_hist_value < 0:
            print('MACD crossed on ' + interval, macd_date, last,
                  macd_hist_value)

        last = macd_hist_value
Exemplo n.º 24
0
def getMACD():
    global finalList
    
    smaList = list(finalList.queue)

    for sym in smaList:
        ti = TechIndicators(key='GSD3E3P11LSBZG5O', output_format='pandas')
        try:
            data, meta_data = ti.get_macd(symbol=sym, interval='monthly')
        except Exception:
            return

        if len(data) == 0:
            continue
        if ((data["MACD_Hist"].iloc[-1]) < 0).all():
            print("failed MACD", sym, (data["MACD_Hist"].iloc[-1]))
            finalList.get(sym)    

    tempList = list(finalList.queue)
    print ("MACD List:")
    for item in tempList:
        print item
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.º 26
0
def MACDIndicator(StockName):
    ti = TechIndicators(key='GKLC3DF23TMWX8LS', output_format='pandas')
    time.sleep(15)  # The alpha_ventage API limit 5 calls per minute
    data, meta_data = ti.get_macd(symbol=StockName,
                                  interval='daily',
                                  series_type='close')
    # realdata = data.to_json(orient='table')
    # print(realdata)

    # # data.plot()
    # json_path = './' + StockName +'MACD.json'
    # with open(json_path, "w") as f:
    # 	json.dump(realdata, f)
    # 	print("Complete...")

    # plt.title('MACD indicator for '+ StockName+ ' stock (1 min)')
    # fig = plt.gcf()
    # plt.savefig("MACD.pdf")
    # plt.show()
    data.to_csv(StockName + '_MACD.csv', index=True, sep=',')

    print(StockName + '_MACD saved successfully.')
    insertDatabase(StockName + '_MACD')
Exemplo n.º 27
0
from alpha_vantage.techindicators import TechIndicators
import matplotlib.pyplot as plt

ti = TechIndicators(key='GSD3E3P11LSBZG5O', output_format='pandas')
data, meta_data = ti.get_macd(symbol='FB', interval='monthly')
data.plot()
plt.title('Simple Moving Average for FB stock (monthly)')
plt.show()
Exemplo n.º 28
0
    print("Fetch new data...")
    oldData = False

if not oldData:
    ts = TimeSeries(key=api_key, output_format="pandas")
    ti = TechIndicators(key=api_key, output_format="pandas")

    # 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:
Exemplo n.º 29
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.º 30
0
from alpha_vantage.timeseries import TimeSeries
from alpha_vantage.techindicators import TechIndicators
import matplotlib.pyplot as plt
import Config

ApiKey = Config.config['alphaVantageApiKey']

ts = TimeSeries(key=ApiKey, output_format='pandas')
data, meta_data = ts.get_intraday(symbol='MSFT',interval='1min', outputsize='full')
data.plot()
plt.title('Intraday Times Series for the MSFT stock (1 min)')
plt.show()

ti = TechIndicators(key=ApiKey, output_format='pandas')
data, meta_data = ti.get_macd(symbol='MSFT',interval='1min')
data.plot()
plt.title('MACD for the MSFT stock (1 min)')
plt.show()