def get_stockdata(symbols): '''Get stock data (key stats and previous) from IEX. Just deal with IEX's 99 stocks limit per request. ''' partlen = 99 result = {} for i in range(0, len(symbols), partlen): part = symbols[i:i + partlen] kstats = iex.Stock(part).get_key_stats() previous = iex.Stock(part).get_previous() for symbol in part: kstats[symbol].update(previous[symbol]) result.update(kstats) return pd.DataFrame(result)
def get_quote(self, ticker): if ticker in self.quotes: return self.quotes[ticker] else: quote = iexfinance.Stock(ticker).get_quote() self.quotes[ticker] = quote return quote
def fetch(symbols): charts = _ensure_dict( iexfinance.Stock(symbols).get_chart(range=chart_range), symbols) result = {} for symbol, obj in charts.items(): df = pd.DataFrame( obj, columns=('date', 'open', 'high', 'low', 'close', 'volume'), ).set_index('date') df.index = pd.to_datetime(df.index, utc=True) result[symbol] = df return result
def iex_charts(symbols): partlen = 99 result = {} for i in range(0, len(symbols), partlen): charts = iexfinance.Stock(symbols[i:i+partlen]).get_chart(range='1m') if type(charts) == list: charts = {symbols[i]: charts} for symbol, data in charts.items(): df = pd.DataFrame(data) df.date = pd.to_datetime(df.date) df.set_index('date', inplace=True) df.index.names = ['epoch'] df.index = df.index.tz_localize('America/New_York') result[symbol] = df return result
def getOpenPrice(ticker): ''' Returns the most recent open price of passed ticker ''' return iex.Stock(ticker).get_open()
def getCurrentPrice(ticker): ''' Returns the current price of passed ticker ''' return iex.Stock(ticker).get_price()
import pandas as pd import iexfinance as iex from datetime import datetime start = datetime(2017, 2, 9) end = datetime(2017, 5, 24) msft = iex.Stock("MSFT", output_format='json') msftEarnings = msft.get_earnings() msftFinance = msft.get_financials() dfEarn = pd.DataFrame(msftEarnings) dfFin = pd.DataFrame(msftFinance) df = iex.get_historical_data("MSFT", start, end, output_format="pandas") df test = iex.StockReader.get_earnings.get_market_book("msft", output_format="json")
import iexfinance import pandas as pd import datetime all_symbols = [stock['symbol'] for stock in iexfinance.get_available_symbols()] volumes = {} data = iexfinance.get_historical_data('FB', datetime.datetime(2018, 4, 29), datetime.datetime(2018, 4, 30)) volume = list(list(data.values())[0].values())[0]['volume'] iexfinance.Stock('FB') for i in range(0, len(all_symbols), 99): print('{}/{}'.format(i, len(all_symbols))) stock = iexfinance.Stock(all_symbols[i:i + 99]) volumes.update(stock.get_volume()) volumes.update( iexfinance.Stock(all_symbols[-(len(all_symbols) % 99):]).get_volume()) volumes = pd.Series(volumes) volumes.sort_values(inplace=True, ascending=False) volumes = volumes.iloc[:1000] volumes.to_csv('out.csv')
def fetch(symbols): return _ensure_dict( getattr(iexfinance.Stock(symbols), method_name)(), symbols)
def get_past_prices(self): ### Fix ### stk = iex.Stock(self.selectedStock).chart_table(range="1y") return stk
def get_price(self): stk = iex.Stock(self.selectedStock) stk.get_open() print(self.selectedStock) return stk.get_price()
import iexfinance import pandas as pd import numpy as np import datetime uForm = pd.read_excel('Garrison Project.xlsm', 'User Form') iForm = pd.read_excel('Garrison Project.xlsm', 'Companies by Industry') userData = uForm['Response'].values symbol = userData[1] sector = userData[2] industry = userData[3] industryComp = iForm[industry].dropna(axis=0, how='all') industryComp = industryComp.values uData = iexfinance.Stock(symbol) allUserData = uData.get_key_stats() allUserData2 = uData.get_financials()[-1] userCompanyData = {} userCompanyData[symbol] = {} userCompanyData[symbol]['Market Cap'] = allUserData['marketcap'] userCompanyData[symbol]['Beta'] = allUserData['beta'] userCompanyData[symbol]['Debt Equity Ratio'] = allUserData2[ 'totalLiabilities'] / allUserData2['shareholderEquity'] userCompanyData[symbol]['PE Ratio'] = (allUserData['peRatioHigh'] + allUserData['peRatioLow']) / 2 userCompanyData[symbol]['Price to Sales'] = allUserData['priceToSales'] userCompanyData[symbol]['Price to Book'] = allUserData['priceToBook'] userCompanyData[symbol]['Short Ratio'] = allUserData['shortRatio'] userCompanyData[symbol]['50 Day Moving Average'] = allUserData[ 'day50MovingAvg'] userCompanyData[symbol]['200 Day Moving Average'] = allUserData[
def hist_prices(self, stock, end): self.stock = stock.upper() try: self.stock_df = data.DataReader(self.stock, 'iex', self.start, end) except: print("ignore this stock 1---------------" + str(self.stock)) return True self.row, col = self.stock_df.shape if self.row < 100: print("not enough data" + str(self.stock)) return True if self.stock_df.index[self.row - 1] != str(end)[0:10]: stock_quote = iex.Stock(self.stock) try: stock_pd = stock_quote.get_quote() except: print("ignore todays prices 2----------" + str(self.stock)) return True stock_date = stock_pd['latestTime'] stock_date = str(parser.parse(stock_date))[0:10] if stock_date == end: stock_open = stock_pd['open'] stock_high = stock_pd['high'] stock_low = stock_pd['low'] stock_close = stock_pd['close'] stock_volume = stock_pd['latestVolume'] if stock_volume == None: stock_volume = self.stock_df['volume'].mean() print("here") f_day = { 'open': [stock_open], 'high': [stock_high], 'low': [stock_low], 'close': [stock_close], 'volume': [stock_volume] } date_index = pd.date_range(stock_date, periods=1, freq='D') f_day = pd.DataFrame(data=f_day, index=date_index) f_day.index.name = 'date' self.stock_df = self.stock_df.append(f_day.ix[0]) self.row, col = self.stock_df.shape self.stock_df = self.stock_df.set_index( pd.to_datetime(self.stock_df.index)) self.data_years = self.row - int(round(253 * self.pull_years, 0)) self.stock_df['date'] = self.stock_df.index.map(mdates.date2num) self.stock_df['averaged_close'] = self.stock_df['close'].ewm( span=4, adjust=False).mean() # calculate MACD parameters self.stock_df['ema26'] = self.stock_df['averaged_close'].ewm( span=26, adjust=False).mean() self.stock_df['ema12'] = self.stock_df['averaged_close'].ewm( span=12, adjust=False).mean() self.stock_df[ 'daily_black'] = self.stock_df['ema12'] - self.stock_df['ema26'] self.stock_df['daily_red'] = self.stock_df['daily_black'].ewm( span=18, adjust=False).mean() self.stock_df['ema60'] = self.stock_df['averaged_close'].ewm( span=60, adjust=False).mean() self.stock_df['ema130'] = self.stock_df['averaged_close'].ewm( span=130, adjust=False).mean() self.stock_df[ 'weekly_black'] = self.stock_df['ema60'] - self.stock_df['ema130'] self.stock_df['weekly_red'] = self.stock_df['weekly_black'].ewm( span=45, adjust=False).mean() #self.stock_df['weekly_black'] = self.stock_df['weekly_black'].ewm(span=5, adjust=False).mean() env_percent = .04 self.stock_df['fit_env'] = 0 while self.stock_df['fit_env'].mean() <= .9: self.stock_df['ema26_highenv'] = self.stock_df['ema26'] * ( 1 + env_percent) self.stock_df['ema26_lowenv'] = self.stock_df['ema26'] * ( 1 - env_percent) self.stock_df['fit_env'] = np.where( (self.stock_df['ema26_highenv'] >= self.stock_df['high']) & (self.stock_df['ema26_lowenv'] <= self.stock_df['low']), 1, 0) env_percent += .005 pd.options.mode.chained_assignment = None self.stock_df['obv_volume'] = 0 self.stock_df['obv_volume'][0] = self.stock_df['volume'][0] for i in range(1, self.row): if self.stock_df['close'][i] > self.stock_df['close'][i - 1]: self.stock_df['obv_volume'][i] = self.stock_df['obv_volume'][ i - 1] + self.stock_df['volume'][i] elif self.stock_df['close'][i] < self.stock_df['close'][i - 1]: self.stock_df['obv_volume'][i] = self.stock_df['obv_volume'][ i - 1] - self.stock_df['volume'][i] else: self.stock_df['obv_volume'][i] = self.stock_df['obv_volume'][i - 1] self.stock_df['volume'] = self.stock_df['volume'] / self.stock_df[ 'volume'].max() self.stock_df['obv_volume'] = self.stock_df[ 'obv_volume'] / self.stock_df['obv_volume'].max() avg_volume = self.stock_df['volume'][self.row - 10:].mean() self.stock_df['close_from_top_env'] = self.stock_df[ 'ema26_highenv'] - self.stock_df['close'] if self.row > 5: self.stock_df['weekly_black_deriv'] = np.gradient( self.stock_df['weekly_black']) self.stock_df['weekly_black_deriv'] = self.stock_df[ 'weekly_black_deriv'] #.ewm(span=8, adjust=False).mean() self.stock_df['weekly_black_deriv'] = self.stock_df[ 'weekly_black_deriv'] self.stock_df['weekly_red_deriv'] = np.gradient( self.stock_df['weekly_red']) self.stock_df['weekly_red_deriv'] = self.stock_df[ 'weekly_red_deriv'] #.ewm(span=8, adjust=False).mean() self.stock_df['weekly_red_deriv'] = self.stock_df[ 'weekly_red_deriv'] self.stock_df['decision'] = 0 self.stock_df['stock-name'] = stock self.stock_df['performance'] = 0 self.short_stock_df = self.stock_df[self.data_years:] self.short_norm_stock_df = self.stock_df[self.data_years:] self.row, col = self.short_norm_stock_df.shape self.short_norm_stock_df['open'] = self.short_norm_stock_df[ 'open'] / self.short_norm_stock_df['open'].max() self.short_norm_stock_df['high'] = self.short_norm_stock_df[ 'high'] / self.short_norm_stock_df['high'].max() self.short_norm_stock_df['low'] = self.short_norm_stock_df[ 'low'] / self.short_norm_stock_df['low'].max() self.short_norm_stock_df['close'] = self.short_norm_stock_df[ 'close'] / self.short_norm_stock_df['close'].max() self.short_norm_stock_df['averaged_close'] = self.short_norm_stock_df[ 'averaged_close'] / self.short_norm_stock_df['averaged_close'].max( ) self.short_norm_stock_df['ema26'] = self.short_norm_stock_df[ 'close'].ewm(span=26, adjust=False).mean() self.short_norm_stock_df['ema12'] = self.short_norm_stock_df[ 'close'].ewm(span=12, adjust=False).mean() daily_max = self.short_norm_stock_df['daily_black'].abs().max() if daily_max < self.short_norm_stock_df['daily_red'].abs().max(): daily_max = self.short_norm_stock_df['daily_red'].abs().max() self.short_norm_stock_df['daily_black'] = self.short_norm_stock_df[ 'daily_black'] / daily_max self.short_norm_stock_df[ 'daily_red'] = self.short_norm_stock_df['daily_red'] / daily_max self.short_norm_stock_df['ema60'] = self.short_norm_stock_df[ 'close'].ewm(span=60, adjust=False).mean() self.short_norm_stock_df['ema130'] = self.short_norm_stock_df[ 'close'].ewm(span=130, adjust=False).mean() weekly_max = self.short_norm_stock_df['weekly_black'].abs().max() if weekly_max < self.short_norm_stock_df['weekly_red'].abs().max(): weekly_max = self.short_norm_stock_df['weekly_red'].abs().max() self.short_norm_stock_df['weekly_black'] = self.short_norm_stock_df[ 'weekly_black'] / weekly_max self.short_norm_stock_df[ 'weekly_red'] = self.short_norm_stock_df['weekly_red'] / weekly_max env_percent = .04 self.short_norm_stock_df['fit_env'] = 0 while self.short_norm_stock_df['fit_env'].mean() <= .95: self.short_norm_stock_df[ 'ema26_highenv'] = self.short_norm_stock_df['ema26'] * ( 1 + env_percent) self.short_norm_stock_df[ 'ema26_lowenv'] = self.short_norm_stock_df['ema26'] * ( 1 - env_percent) self.short_norm_stock_df['fit_env'] = np.where( (self.short_norm_stock_df['ema26_highenv'] >= self.short_norm_stock_df['high']) & (self.short_norm_stock_df['ema26_lowenv'] <= self.short_norm_stock_df['low']), 1, 0) env_percent += .0005 pd.options.mode.chained_assignment = None avg_volume = self.short_norm_stock_df['volume'][self.row - 10:].mean() self.short_norm_stock_df[ 'close_from_top_env'] = self.short_norm_stock_df[ 'ema26_highenv'] - self.short_norm_stock_df['close'] if self.row > 5: self.short_norm_stock_df['weekly_black_deriv'] = np.gradient( self.short_norm_stock_df['weekly_black']) self.short_norm_stock_df['weekly_red_deriv'] = np.gradient( self.short_norm_stock_df['weekly_red']) self.short_norm_stock_df[ 'weekly_black_double_deriv'] = np.gradient( self.short_norm_stock_df['weekly_black_deriv']) self.short_norm_stock_df[ 'weekly_black_deriv'] = self.short_norm_stock_df[ 'weekly_black_deriv'].ewm(span=6, adjust=False).mean() #self.short_norm_stock_df['weekly_black_deriv'] = self.short_norm_stock_df['weekly_black_deriv'].rolling(window=5).mean() #self.short_norm_stock_df['weekly_red_deriv'] = self.short_norm_stock_df['weekly_red_deriv'].ewm(span=2, adjust=False).mean() weekly_slope_max = self.short_norm_stock_df[ 'weekly_black_deriv'].abs().max() if weekly_slope_max < self.short_norm_stock_df[ 'weekly_red_deriv'].abs().max(): weekly_slope_max = self.short_norm_stock_df[ 'weekly_red_deriv'].abs().max() self.short_norm_stock_df[ 'weekly_black_deriv'] = self.short_norm_stock_df[ 'weekly_black_deriv'] / weekly_slope_max self.short_norm_stock_df[ 'weekly_red_deriv'] = self.short_norm_stock_df[ 'weekly_red_deriv'] / weekly_slope_max self.short_norm_stock_df[ 'weekly_slope_histogram'] = self.short_norm_stock_df[ 'weekly_black_deriv'] - self.short_norm_stock_df[ 'weekly_red_deriv'] self.short_norm_stock_df[ 'weekly_black_double_deriv'] = self.short_norm_stock_df[ 'weekly_black_double_deriv'] / self.short_norm_stock_df[ 'weekly_black_double_deriv'].abs().max() self.short_norm_stock_df[ 'weekly_black_double_deriv'] = self.short_norm_stock_df[ 'weekly_black_double_deriv'].ewm(span=6, adjust=False).mean() #self.short_norm_stock_df['weekly_red_double_deriv'] = np.gradient(self.short_norm_stock_df['weekly_red_deriv']) return False