Exemplo n.º 1
0
def get_data_from_av():
    '''
    Get live date from Alpha Vantage, and store as *.csv files under $STOCK_HOME/csv subfolder
    :return:
    '''
    if not isdir(csv_dir):
        mkdir(csv_dir)
    ts = TimeSeries(key=environ['AlphaVantageKey'], output_format='pandas')
    ti = TechIndicators(key=environ['AlphaVantageKey'], output_format='pandas')
    index_name2fun_dict = {'mcd':ti.get_macd, 'sma':ti.get_sma, 'ema':ti.get_ema, 'rsi':ti.get_rsi, \
                           'sar':ti.get_sar, 'obv':ti.get_obv}
    print('Load ^DJI to {}/^DJI.csv'.format(stock_home))
    ts.get_daily_adjusted('^DJI',
                          'full')[0].to_csv("{}/^DJI.csv".format(stock_home))
    time.sleep(20)
    tickers = get_tickers()
    for tic in tickers:
        _data, _ = ts.get_daily_adjusted(tic, 'full')
        _data.to_csv('{}/{}.csv'.format(csv_dir, format(tic)))
        print('Load {} to dir {}'.format(tic, csv_dir))
        time.sleep(20)
        for index_name in index_name2fun_dict.keys():
            _tidata, _ = index_name2fun_dict[index_name](tic)
            ti_filename = "{}/{}_{}.csv".format(ti_dir, tic, index_name)
            _tidata.to_csv(ti_filename)
            print('Save to {}'.format(ti_filename))
            time.sleep(20)
    def GetStockInformation(self, Ticker):
        self.ticker = Ticker
        ts = TimeSeries(key=self.alphaVantage_Appid, output_format='pandas')
        ti = TechIndicators(key=self.alphaVantage_Appid,
                            output_format='pandas')
        data, meta_data = ts.get_intraday(symbol=Ticker,
                                          interval='1min',
                                          outputsize='full')
        indicators, indicator_metadata = ti.get_sma(symbol=Ticker,
                                                    interval='1min',
                                                    time_period=100,
                                                    series_type='close')
        data['close'].plot()
        #indicators.plot()
        plt.show()

        latest = len(data) - 1
        iLatest = len(indicators) - 1

        print(data['close'][latest])
        print(indicators['SMA'][iLatest])
        if data['close'][latest] > indicators['SMA'][iLatest]:
            print('High')
        else:
            print('Low')
Exemplo n.º 3
0
    def add_technicals(self, tech_symbols, primary_df, supp_symbol=None):

        if supp_symbol == None:
            symbol = self.symbol
        else:
            symbol = supp_symbol

        ti = TechIndicators(key=config('ALPHA_VANTAGE'),
                            output_format='pandas')

        new_indicators = ["get_" + symbol.lower() for symbol in tech_symbols]

        i_count = 0

        for ind in new_indicators:

            data, meta_data = getattr(ti, ind)(symbol=symbol)

            print(meta_data)

            data = data.rename(columns={
                symbol: self.symbol + '_' + symbol,
            })
            if i_count == 0:
                final_df = primary_df.merge(data, how='inner', on='date')
            else:
                final_df = final_df.merge(data, how='inner', on='date')

            i_count += 1

        return final_df
Exemplo n.º 4
0
def check_rsi(symbol='', key='', time=5, treshold=65, points=5):
    ti = TechIndicators(key=key, output_format='pandas')
    data, meta_data = ti.get_rsi(symbol=symbol, time_period=time)
    rsidata = data.tail(points).to_dict()
    for rsi in rsidata['RSI']:
        if rsidata['RSI'][rsi] > treshold:
            print('RSI ' + str(time), rsi, rsidata['RSI'][rsi])
def technical_indicators(symbol, interval):
    import pandas as pd
    from alpha_vantage.techindicators import TechIndicators
    import matplotlib.pyplot as plt
    api_key = '67O5YS2MXMMVBHVL'

    period = 60
    ti = TechIndicators(key=api_key, output_format='pandas')
    data_rsi, meta_data_rsi = ti.get_rsi(symbol,
                                         interval,
                                         time_period=period,
                                         series_type='close')
    data_sma, meta_data_sma = ti.get_sma(symbol,
                                         interval,
                                         time_period=period,
                                         series_type='close')
    #print(data_ti)

    df1 = data_sma.iloc[1::]
    df2 = data_rsi
    df1.index = df2.index

    fig, ax1 = plt.subplots()
    ax1.plot(df1, 'b-')
    ax2 = ax1.twinx()
    ax2.plot(df2, 'r.')
    plt.title("SMA & RSI graph")
    # plt.show()
    r2 = df1, df2
    return (r2)
Exemplo n.º 6
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.º 7
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.º 8
0
 def __init__(self, equity):
     self.ti = TechIndicators(output_format='pandas')
     self.current = None
     self.info = None
     self.equity = equity
     self.rsi = self.rsi_data()
     self.avg = self.avg_rsi()
Exemplo n.º 9
0
def get_historical_data(stock):
  # Your key here
  key = os.getenv("ALPHA_VANTAGE_API_KEY")
  # Chose your output format, or default to JSON (python dict)
  ts = TimeSeries(key, output_format='pandas')
  ti = TechIndicators(key)

  # Get the data, returns a tuple
  # stock_data is a pandas dataframe, stock_meta_data is a dict
  stock_data, stock_meta_data = ts.get_daily(symbol=stock, outputsize='full')
  # stock_data, stock_meta_data = ts.get_intraday(symbol='TSLA',interval='60min', outputsize='full')

  # stock_sma is a dict, stock_meta_sma also a dict
  # stock_sma, stock_meta_sma = ti.get_sma(symbol='TSLA')

  stock_data['same_day_change'] = stock_data['4. close'] - stock_data['1. open']
  stock_data['same_day_percentage_change'] = stock_data['same_day_change'] / stock_data['1. open']

  stock_data['1_day_change'] = stock_data['4. close'].diff()
  stock_data['1_day_percentage_change'] = stock_data['4. close'].pct_change()

  # embed()


  stock_data.index = stock_data.index.astype('datetime64[ns, UTC]')
  # stock_data = stock_data.shift(1)

  # embed()

  print (stock_data)
  return stock_data
Exemplo n.º 10
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.º 11
0
def rsi_dataframe(stock=stock):
    api_key = ''
    period = 60
    ts = TimeSeries(key=api_key, output_format='pandas')
    data_ts = ts.get_intraday(stock.upper(),
                              interval='1min',
                              outputsize='full')

    ti = TechIndicators(key=stock.upper(), output_format='pandas')

    data_ti, meta_data_ti = ti.get_rsi(symbol=stock.upper(),
                                       interval='1min',
                                       time_period=period,
                                       series_type='close')

    df = data_ts[0][period::]

    df.index = pd.Index(map(lambda x: str(x)[:-3], df.index))

    df2 = data_ti

    total_df = pd.concat([df, df2], axis=1, sort=True)

    # for i in total_df['RSI']:
    #     print(i)
    return print(total_df)
Exemplo n.º 12
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.º 13
0
    def __init__(self,
                 interval=None,
                 symbol=None,
                 use_rapid=False,
                 skip_data_init=False,
                 outputsize="full"):
        super(AlphaVantageHandle, self).__init__()
        self.log = logging.getLogger("Alpha Vantage API")

        self._outputsize = outputsize
        self.api_time_queue = Queue()
        # Initialize alpha vantage time series
        if use_rapid:
            self.time_series = TimeSeries(key=self.RAPIDAPI_KEY,
                                          output_format="pandas",
                                          rapidapi=True)
        else:
            self.time_series = TimeSeries(key=self.ALPHA_VANTAGE_PRIMIUM_KEY,
                                          output_format="pandas")

        self.tech_indicators = TechIndicators(
            key=self.ALPHA_VANTAGE_PRIMIUM_KEY, output_format='pandas')

        if not skip_data_init:
            # Set the symbol and interval for the handle
            self.update_symbol_interval(symbol=symbol, interval=interval)
            # Fetch time series data
            self.log.info(
                "Downloading time series and technical indicator data from alpha vantage:\n "
                "   symbol: %s\n"
                "   interval: %s\n", self._symbol, self._interval)
            self.update_all_data()
            self.log.info("Data downloaded")
Exemplo n.º 14
0
def ROCIndicator(StockName):
    ti = TechIndicators(key='QBGRPFYFV5WBTTCO', output_format='pandas')
    data, meta_data = ti.get_roc(symbol=StockName,
                                 interval='1min',
                                 time_period=60,
                                 series_type='close')
    # realdata = data.to_json(orient='table')
    # print(realdata)

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

    # print(type(data))
    # # print(data)
    # data.plot()

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

    print('Success')
Exemplo n.º 15
0
def get_indicator(indicator, time_period=20, plot=True):
    """
    Gets a particular indicator associated to the company and from the starting date selected in the file config.py.

    :param indicator: specifies which indicator to retrieve.
    :param time_period: number of data points used to calculate the indicator values. default_value=20
    :param plot: if True it plots the data inside the dataframe downloaded. default_value=True
    :return: the path of the directory in which the data are stored.
    """
    ti = TechIndicators(key=alpha_vantage_api_key, output_format='pandas', indexing_type='date')
    indicator_dict = {'bbands': ti.get_bbands, 'sma': ti.get_sma, 'ema': ti.get_ema, 'rsi': ti.get_rsi,
                      'adx': ti.get_adx, 'cci': ti.get_cci, 'aroon': ti.get_aroon}
    function = indicator_dict[indicator]
    data, meta_data1 = function(symbol=company, interval='daily', time_period=time_period)
    data = data.sort_index(ascending=True)
    # Retain only the entries from the starting date selected in config.py until now
    data = data.loc[starting_date:]
    # Save the dataset acquired in a pickle file
    data_directory = os.path.join(base_dir, f'{indicator}.pkl')
    to_pickle(data, data_directory)
    if plot:
        sn.set()
        data.plot()
        plt.title(f'{indicator} indicator for {company} stock')
        plt.show()
    return data_directory
Exemplo n.º 16
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
def Standard_TechIndicator(dict_kwargs, series, price_type_list, start_date,
                           end_date):
    starttime = time.time()
    ti = TechIndicators(key='6RX0I0CC3SZBVUCI', output_format='pandas')
    appended_data = []
    function = ('get_' + series.casefold())
    if price_type_list == []:
        data, meta_data = getattr(ti, function)(**dict_kwargs)
        file_name = 'C:\\Users\\BabyHulk\\PycharmProjects\\IntelligentTrader\\AlphaVantageCSV\\TrainData\\SingleColumn' \
                    + '\\' + dict_kwargs['symbol'] + '_' + series + '_' + str(dict_kwargs['time_period']) \
                    + '.csv'
        appended_data_slice = data.loc[start_date:end_date]
        appended_data_slice.to_csv(file_name)
        time.sleep(3.0 - ((time.time() - starttime) % 3.0))
    else:
        for price in price_type_list:

            columns_name = {series: price}

            data, meta_data = getattr(ti, function)(**dict_kwargs)
            data.rename(columns=columns_name, inplace=True)
            appended_data.append(data)

        file_name = 'C:\\Users\\BabyHulk\\PycharmProjects\\IntelligentTrader\\AlphaVantageCSV\\TrainData\\Open_Low_High_Close\\' \
                    + dict_kwargs['symbol'] + '_' + series + '_' + str(dict_kwargs['time_period']) + '.csv'

        appended_data = pandas.concat(appended_data, axis=1)
        appended_data_slice = appended_data.loc[start_date:end_date]
        appended_data_slice.to_csv(file_name)
        time.sleep(15.0 - ((time.time() - starttime) % 15.0))
def getData(equity, MY_API_KEY):
    """
    parse data for a given stock symbol.

    :param equity (panda series): TimeSeries data and TechIndicators pandaframe.
    """
    # Pandaframe for TimeSeries
    ts = TimeSeries(key=f"{MY_API_KEY}",
                    output_format='pandas',
                    indexing_type='date')
    tsdata, tsmeta_data = ts.get_intraday(symbol=equity,
                                          interval='60min',
                                          outputsize='full')
    TS = tsdata.head(1000)
    path = "data/TimeSeries/"
    path += equity + ".csv"
    tsdata.to_csv(path_or_buf=path)

    # Pandaframe for TechIndicators
    ti = TechIndicators(key=f"{MY_API_KEY}",
                        output_format='pandas',
                        indexing_type='data')
    tidata, timeta_data = ti.get_bbands(symbol=equity,
                                        interval='60min',
                                        time_period=60)
    TI = tidata.head(1000)
    path = "data/TechIndicators/"
    path += equity + ".csv"
    tidata.to_csv(path_or_buf=path)
Exemplo n.º 19
0
def get_fifteen_minute_rsi(symbol):
    time.sleep(15)
    ti = TechIndicators(key=API_KEY, output_format='pandas')
    data, meta_data = ti.get_rsi(symbol=symbol,
                                 interval='15min',
                                 time_period=14)
    return int(data.tail(1).iloc[0]['RSI'])
Exemplo n.º 20
0
def ROCIndicator(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_roc(symbol=StockName,
                                 interval='daily',
                                 series_type='close')
    # realdata = data.to_json(orient='table')
    # print(realdata)

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

    # print(type(data))
    # # print(data)
    # data.plot()

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

    print(StockName + '_ROC saved successfully.')
    insertDatabase(StockName + '_ROC')
Exemplo n.º 21
0
def get_data_from_api(stock_list):
    """
    Sources stock market data from the AlphaVantage API for a given list of stocks.

    Parameters: 
        stock_list (list): List of stock symbols specifying desired stocks

    Returns:
        stock_dict (dict): Dictionary containing daily stock prices indexed by stock symbol

    """

    # Get time series data, returns a tuple (data, meta_data)
    # First entry is a pandas dataframe containing data, second entry is a dict containing meta_data
    print("Sourcing stock market data from AlphaVantage API...")
    key = 'RY4QOCLLB7ZIVZ8M'  # your API key here
    ts = TimeSeries(key, output_format='pandas'
                    )  # choose output format, defaults to JSON (python dict)
    ti = TechIndicators(key)

    # Create dictionary of form stock_symbol: (data, meta_data)
    stock_dict = {}
    for stock in stock_list:
        print(stock)
        stock_dict[stock] = ts.get_daily(symbol=stock)
    return stock_dict
Exemplo n.º 22
0
def get_ingest_ticker_price(inticker):
    '''
    Load AlphaVantage stock data into DB

    parameter(s): stock (str)

    returns: void
    '''
    conn = sqlite3.connect('../../data/sentiment.db')
    cursor = conn.cursor()

    try:
        ts = TechIndicators(key='INSERTKEY', output_format='pandas')
        data, meta_data = ts.get_sma(symbol=inticker,
                                     interval='60min',
                                     time_period=32,
                                     series_type='close')
        for row in data:
            cursor.execute(
                "INSERT INTO Tickerprices(ticker, date, close) VALUES(?,?,?)",
                (inticker, timestamp, row))
        return True
    except:
        se.send_ticker_error()
        return False
Exemplo n.º 23
0
def stock_comparison(symbol, interval):
    import pandas as pd
    from alpha_vantage.timeseries import TimeSeries
    from alpha_vantage.techindicators import TechIndicators
    import matplotlib.pyplot as plt
    api_key = '67O5YS2MXMMVBHVL'

    ts = TimeSeries(key=api_key, output_format='pandas')
    data_ts, meta_data = ts.get_intraday(symbol, interval, outputsize='full')
    #print(data_ts)

    period = 60
    ti = TechIndicators(key=api_key, output_format='pandas')
    data_ti, meta_data_ti = ti.get_sma(symbol,
                                       interval,
                                       time_period=period,
                                       series_type='close')
    #print(data_ti)

    df1 = data_ti
    df2 = data_ts['4. close'].iloc[period - 1::]
    df2.index = df1.index
    total_df = pd.concat([df1, df2], axis=1)
    #print(total_df)
    total_df.plot()

    r1 = total_df
    return (r1)
Exemplo n.º 24
0
def rsi_df(stock=stock):
    api_key = key.API_key
    period = 60
    ts = TimeSeries(key=api_key, output_format='pandas')#This ts is helping us to connect to API
    data_ts = ts.get_intraday(stock.upper(), interval='1min', outputsize='full')

    #indicator
    ti = TechIndicators(key=api_key, output_format='pandas')
    #data_ti, meta_data_ti = ti.get_bbands(symbol = stock.upper(), interval='1min', time_period=period, series_type='close')
    data_ti, meta_data_ti = ti.get_rsi(symbol=stock.upper(), interval='1min', time_period=period,
                                          series_type='close')

    df = data_ts[0]

    df = df.iloc[::-1][period::]
    df.index = pd.Index(map(lambda x: str(x)[:-3], df.index))
    df.index.name = 'Date'

    df2 = data_ti
    df2.index = pd.Index(map(lambda x: str(x)[:-3], df2.index))
    df2.index.name = 'Date'
    total_df = pd.merge(df, df2, on="Date")

    open = []
    for i in total_df['1. open']:
        open.append(float(i))

    close = []
    for c in total_df['4. close']:
        close.append(float(c))

    low = []
    for l in total_df['3. low']:

        low.append(float(l))

    high = []
    for h in total_df['2. high']:
        high.append(float(h))

    rsi = []
    for r, l in zip(total_df['RSI'], low):
        rsi.append(l-(l/r))

    high_rsi_value = []
    high_rsi_time = []

    for value, time, l in zip(total_df['RSI'], total_df.index, low):
        if value>60:
            high_rsi_value.append(l-(l/value))
            high_rsi_time.append(time)

    low_rsi_value = []
    low_rsi_time = []
    for value, time, l in zip(total_df['RSI'], total_df.index, low):
        if value<35:
            low_rsi_value.append(l-(l/value))
            low_rsi_time.append(time)

    return print(total_df.columns)
Exemplo n.º 25
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.º 26
0
def visualization(key, s):
    """
        This function is used to create the stock chart visualization. It receives the API key and the ticker
        as arguments and then produces the plot as a result.

        @param: this function has two parameters: the first is the API key that is a string. The second is the stock ticker
                which is a string and has already been validated. 

    """
    #this was adopted from the alpha vantage customer service website/ github
    #https://medium.com/alpha-vantage/get-started-with-alpha-vantage-data-619a70c7f33a
    key = ALPHA_VANTAGE_API_KEY
    ts = TimeSeries(key, output_format='pandas')
    ti = TechIndicators(key)

    # Get the data, returns a tuple
    # stock_data is a pandas dataframe
    # note that the API is requested one more time
    stock_data, stock_meta_data = ts.get_daily(symbol=s)

    # Visualization
    figure(num=None, figsize=(15, 6), dpi=80, facecolor='w', edgecolor='k')
    stock_data['4. close'].plot()
    plt.tight_layout()
    plt.grid()
    plt.show()
Exemplo n.º 27
0
 def techIndicator_get_bbands(self, timePeriod, format):
     #outputting data in JSON format in the below line
     ti = TechIndicators(key=settings.API_KEY, output_format=format)
     data, meta_data = ti.get_bbands(symbol=self.symbol,
                                     interval='daily',
                                     time_period=timePeriod)
     return data, meta_data
Exemplo n.º 28
0
 def __init__(self):
     self.ts = TimeSeries(key='4ZXG1S4Z055LPBAW')
     self.ti = TechIndicators(key='4ZXG1S4Z055LPBAW')
     self.apiData = dict()
     self.latestData_Time = None
     self.latestData_Price = dir({})
     self.rsiData = dict()
Exemplo n.º 29
0
 def __init__(self):
     self.ts = TimeSeries(key=os.environ.get("ALPHA_VANTAGE_KEY"))
     self.ti = TechIndicators(key=os.environ.get("ALPHA_VANTAGE_KEY"))
     self.apiData = dict()
     self.latestData_Time = None
     self.latestData_Price = dir({})
     self.rsiData = dict()
Exemplo n.º 30
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