Ejemplo n.º 1
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
Ejemplo n.º 2
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')
Ejemplo n.º 3
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
Ejemplo n.º 4
0
    def sma(self):  #simple moving average
        d = TechIndicators(key=self.api_key, output_format='pandas')
        data, meta_data = d.get_sma(symbol=self.stock_name,
                                    interval='15min',
                                    time_period=40)

        return data
Ejemplo n.º 5
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
Ejemplo n.º 6
0
 def get_WMA(name, duration, sr_type):
     ti = TechIndicators(key='YOUR_OWN_API', output_format='pandas')
     data_wma, meta_data_wma = ti.get_wma(symbol=Company.comp[name],
                                          interval=duration,
                                          time_period='60',
                                          series_type=sr_type)
     return data_wma
Ejemplo n.º 7
0
	def getInfo(self):
		'''
		Prints all relevant info about stock to a text file
		
		Returns
		------
		none
                
		'''
		
		f = open("stockinfo.txt", "w")
		ts = TimeSeries(key='GZR6JEGOB3LF6RCB')
		tc = TechIndicators(key='GZR6JEGOB3LF6RCB')
		data, meta_data = ts.get_daily(self.name)
		data2, meta_data2 = tc.get_rsi(self.name)
		data3, meta_data3 = tc.get_sma(self.name)
		self.rsi = float(data2['2019-01-16']['RSI'])
		self.sma = float(data3['2019-01-16']['SMA'])
		teststring = data['2019-01-16']
		self.value = float(teststring['4. close'])
		f.write("The stock chosen is: " + self.name + "\n")
		f.write("The most recent closing price is: " + str(self.value) + " more info in console")
		if(self.rsi > 70):
			print("this stock has a high RSI and is currently oversold. The price may fall soon")
		elif(self.rsi < 30):
			print("this stock has a low RSI and is currently overbought. The price may rise soon")
		else:
			print("the stock is trading at normal levels")
		if(self.value > self.sma):
			print("the price of this stock is currently higher than the moving average. it is trending upwards")
		else:
			print("the price of this stock is currently lower than the moving average. it is trending downwards")
		f.close()
def get_alpha(ticker_list, alpha_key):
    '''
    Input:
        ticker_list: list of strings of publicly traded companies symbols, 'XYZ'
        alpha_key: get alpha vantage API key from alpha vantage website
    Output:
        build CSV files of stock price history, and technical indicators for
        each company
    '''

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

    # Build CSV for Daily prices, RSI, CCI, OBV for each company
    for ticker in ticker_list:
        print('company: {}, time: {}'.format(ticker, str(time() - zero_time)))
        df, meta = ts.get_daily(symbol=ticker, outputsize='full')
        df.to_csv('data/daily/{}.csv'.format(ticker))
        sleep(1)
        df, meta = ti.get_rsi(ticker, interval='daily', time_period=5)
        df.to_csv('data/rsi/{}.csv'.format(ticker))
        sleep(1)
        df, meta = ti.get_cci(ticker, interval='daily', time_period=5)
        df.to_csv('data/cci/{}.csv'.format(ticker))
        sleep(1)
        df, meta = ti.get_obv(ticker, interval='daily')
        df.to_csv('data/obv/{}.csv'.format(ticker))
Ejemplo n.º 9
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)
Ejemplo n.º 10
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
Ejemplo n.º 11
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")
Ejemplo n.º 12
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)
Ejemplo n.º 13
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'])
Ejemplo n.º 14
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])
Ejemplo n.º 15
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()
    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')
Ejemplo n.º 17
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
Ejemplo n.º 18
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)
Ejemplo n.º 19
0
def load_stock(stock):
    a.clear()
    a2.clear()

    ts_data = None
    rsi_data = None

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

    while ts_data is None:
        try:
            ts_data, _ = ts.get_intraday(symbol=stock,
                                         interval='1min',
                                         outputsize='full')
        except KeyError:
            print("trying again...")

    while rsi_data is None:
        try:
            rsi_data, _ = ti.get_rsi(symbol=stock,
                                     interval='60min',
                                     time_period=60)
        except KeyError:
            print("trying again...")

    ts_data['4. close'].plot(ax=a)
    fig.suptitle(f"{stock} Intraday")
    rsi_data.plot(ax=a2)
    fig2.suptitle(f"{stock} RSI")

    canvas.draw()
    canvas2.draw()
    window.title(f"{stock} Info")
Ejemplo 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')
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)
Ejemplo n.º 22
0
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)
 def __init__(self, symbol, api_key='KHMFAMB5CA0XGKXO'):
     self.api_key = api_key
     self.ticker = symbol
     self.ts = TimeSeries(api_key)
     self.ti = TechIndicators(api_key)
     self.sp = SectorPerformances(api_key)
     self.counter = 0
     self.MAX_API_CALL = 500
Ejemplo n.º 24
0
def get_company_techindicators(company_symbol, interval):

    ts = TechIndicators(key=apiKey, output_format='json')

    # Get json object with the techindicator data and another with  the call's metadata
    data, meta_data = ts.get_bbands(symbol=company_symbol, interval=interval)

    return data, meta_data
Ejemplo n.º 25
0
def get_sma(symbol):
    #Gera uma key aleatoria cada vez
    ti = TechIndicators(key=str(randint(99994, 447389428)), output_format='pandas')
    
    data7, metadata = ti.get_sma(symbol=symbol, interval='daily', time_period=7, series_type='close')
    data21, metadata = ti.get_sma(symbol=symbol, interval='daily', time_period=21, series_type='close')
    
    return data7, data21
Ejemplo n.º 26
0
 def __init__(self, name, tag):
     self.__name = name
     self.__tag = tag
     self.__timestamp = None
     self.__sma7 = ''
     self.__sma21 = ''
     self.__ti = TechIndicators('IIB8DA6B2CRR6UL7')
     self.updateData()
Ejemplo n.º 27
0
def GetMADay(ticker=None):
    if ticker:
        ti = TechIndicators(key=os.environ['AlphaKey'], output_format='json')
        data, meta = ti.get_sma(symbol=ticker,
                                interval='daily',
                                time_period=480,
                                series_type='close')
        return data
    return None
Ejemplo n.º 28
0
 def initialise(self) -> None:
     logging.info("Initialising AVInterface...")
     api_key = self._config.get_credentials()["av_api_key"]
     self.TS = TimeSeries(key=api_key,
                          output_format="pandas",
                          treat_info_as_error=True)
     self.TI = TechIndicators(key=api_key,
                              output_format="pandas",
                              treat_info_as_error=True)
Ejemplo n.º 29
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
Ejemplo n.º 30
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')