async def connect(self): '''connect to exchange. should be asynchronous. For OrderEntry-only, can just return None ''' self._client = pyEX.Client(self._api_key, 'sandbox' if self._is_sandbox else 'stable')
async def connect(self) -> None: """connect to exchange. should be asynchronous. For OrderEntry-only, can just return None """ self._client = pyEX.Client(self._api_key, "sandbox" if self._is_sandbox else "stable")
def init_api(self, config): try: self.api = pyEX.Client(api_token=config['api_key'], version=config['api_version']) print('TSX: initialized') except Exception: print('TSX: an error occured while initializing') exit()
def get(self, request): context = {} accountDetails = Account.objects.get(user=request.user) if not accountDetails.rhoodID or not accountDetails.rhoodPWD or not accountDetails.rhQ: context['newUser'] = True #TODO: now that we know if its a new user, we must get the user to provide their RH credentials if they are new #This should be displayed as a modal token = os.environ['API_TOKEN'] platform = os.environ['API_PLATFORM'] c = p.Client(api_token=token, version=platform) dow = c.quote('DOW') sp500 = c.quote('SPY') nasdaq = c.quote('IWM') context['current'] = { 'dow': { 'price': dow['latestPrice'], 'change': dow['changePercent'] }, 'sp500': { 'price': sp500['latestPrice'], 'change': sp500['changePercent'] }, 'nasdaq': { 'price': nasdaq['latestPrice'], 'change': nasdaq['changePercent'] } } #return HttpResponse(context) return render(request, self.template_name, context)
def download_advanced_stats_data(symbol_list): """retrieves advanced stats data from IEX API Args: symbol_list (str): list of stock ticker symbols Returns: peer_df (Pandas Dataframe): peer data, columns: 'Ticker', 'Peer_string', 'Peer_list' """ # create Client subscribed API key and version iex_c = p.Client(api_token=get_api_key_from_cfg(), version='stable') stats_list = [] for symbol in symbol_list: try: stats_df = iex_c.advancedStatsDF(symbol) stats_df.insert(0, 'Ticker', symbol) stats_df['download_date'] = pd.to_datetime('now') stats_list.append(stats_df) except: print(f'Failed to download data for symbol {symbol}') stats_df = pd.concat(stats_list, ignore_index=True) stats_df.to_csv('..//data//2_fundamentals//iex_data//advanced-stats.csv', index=False) return stats_df
def add_entry_for_today(symbol, df): # IEX Client content = open('config.json').read() config = json.loads(content) iex_client = pyEX.Client(config["iex_api_key"]) # New DF Entry current_date = datetime.today().strftime('%Y-%m-%d') current_price = iex_client.quote(symbol)["latestPrice"] ''' # For testing transaction tomorrow = datetime.today() + timedelta(days=1) last_macd_entry = df.iloc[len(df) - 1, df.columns.get_loc('MACD')] last_signal_entry = df.iloc[len(df) - 1, df.columns.get_loc('signal_line')] sell_row = pd.Series(data={'close': current_price, '26ema': 0.0, '12ema': 0.0, "MACD": last_macd_entry - 5.0, "signal_line" : last_signal_entry + 5.0}, name=current_date) #buy_row = pd.Series(data={'close': current_price, '26ema': 0.0, '12ema': 0.0, "MACD": last_macd_entry + 10.0, # "signal_line": last_signal_entry - 10.0}, name=tomorrow) df = df.append(sell_row, ignore_index=False) #df = df.append(buy_row, ignore_index=False) ''' new_row = pd.Series(data={ 'close': current_price, '26ema': 0.0, '12ema': 0.0, "MACD": 0.0 }, name=current_date) df = df.append(new_row, ignore_index=False) update_df_with_macd(df) pd.to_pickle(df, "./watchlist_history/{}_history.pkl".format(symbol)) return df
def __init__(self, config_file: str = 'config/iexcloud-config.json', should_print: bool = True): """ This function initializes the Scraper class, which is a scraping object designed to scrape data from IEXCloud. :param config_file: A configuration file with IEX credentials. Must contain keys: {'api_token':str, 'api_secret':str, 'sandbox':str}. See `config/iexcloud-config.json` as an example. :type config_file: str :param should_print: Whether to print the status of scraping or not. :type should_print: bool """ self.timestamp = int(time.time()) with open(config_file) as file: config = json.load(file) self.access_token = config[CONFIG_CONSTANTS.API_TOKEN] self.access_secret = config[CONFIG_CONSTANTS.API_SECRET] self.sandbox_mode = config[CONFIG_CONSTANTS.SANDBOX_MODE] self.stage = ScraperConstants.Stage.SANDBOX if self.sandbox_mode else ScraperConstants.Stage.STABLE self.should_print = should_print self.client = pyEX.Client(api_token=self.access_secret, version=self.stage)
def __init__(self): self.secret = 'sk_fae174660924464996b77d14209a973b' self.public = 'pk_2f3691af11ad4df583c95f2a4d89d44a' p.Client(api_token=self.secret, version='v1', api_limit=5) self.chrome_options = Options() self.chrome_options.add_argument("--headless") self.agent = { "User-Agent": 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/83.0.4103.61 Chrome/83.0.4103.61 Safari/537.36' }
def get_basic_quote(ticker: str) -> discord.Embed: c = p.Client(api_token=load_json('IEX_pub'), version='v1') quote = c.quote(ticker) symbol = quote['symbol'] company_name = quote['companyName'] latest_price = quote['latestPrice'] high = quote['high'] low = quote['low'] prev = quote['previousClose'] q_time = quote['latestTime'] # These values might be null try: change_percent = round(quote['changePercent'] * 100, 3) change = round(quote['change'], 3) except TypeError: change_percent = None change = None if change_percent is None: market_percent_string = '' elif change_percent >= 0: market_percent_string = " (+" + str(change_percent) + "%)" else: market_percent_string = " (" + str(change_percent) + "%)" if change is None: change_string = '' elif change >= 0: change_string = "+" + str(change) else: change_string = str(change) desc1 = ''.join([str('${:,.2f}'.format(float(latest_price))), " ", change_string, market_percent_string]) if high is not None and low is not None: desc2 = ''.join(['High: ', '{:,.2f}'.format(float(high)), ' Low: ', '{:,.2f}'.format(float(low)), ' Prev: ', '{:,.2f}'.format(float(prev))]) else: desc2 = ''.join(['Prev: ', '{:,.2f}'.format(float(prev))]) embed = discord.Embed( title="".join([company_name, " ($", symbol, ")"]), url="https://www.tradingview.com/symbols/" + symbol, description=''.join([desc1, '\n', desc2]), color=0x85bb65 ) embed.set_footer(text=f'{q_time}') return embed
def main(): logging.basicConfig(filename='logs.log', level=logging.WARNING, format="%(asctime)s:%(levelname)s: ") logging.getLogger().addHandler(logging.StreamHandler()) # Wait for the market to open delay.wait_for_market_open() # Create iex client c = p.Client(version='v1', api_limit=0) # Collect market open prices executor = ThreadPoolExecutor(10) symbols = price.get_market_open_prices(c, executor) executor.shutdown(wait=False) # Check prices until close delay.run_until_close(symbols, c)
def download_peer_data(symbol_list): """retrieves peer data from IEX API Args: symbol_list (str): list of stock ticker symbols Returns: peer_df (Pandas Dataframe): peer data, columns: 'ticker', 'peer_string', 'peer_list' """ # create Client subscribed API key and version iex_c = p.Client(api_token=get_api_key_from_cfg(), version='stable') peer_dict = {} for symbol in symbol_list: peer_dict[symbol] = (',').join(iex_c.peersDF(symbol).peer.values) peer_df = pd.DataFrame.from_dict(peer_dict, orient='index').reset_index() peer_df.columns = ['ticker', 'peer_string'] peer_df['peer_list'] = peer_df['peer_string'].str.split(',') peer_df.to_csv('..//data//1_company_info//peer_list.csv', index=False) return peer_df
def get(num): # Maintain the state global q1_size global q1 global array global symbols # Can move to a pub/sub message implementation where assignments are pushed and nodes consume while q1.full(): time.sleep(5) q1.put(num) q1_size += 1 if symbols is None: c = p.Client(version='v1', api_limit=0) syms = c.symbolsList() for group in data.chunker(syms, int(num)): array.append(group) result = array[q1_size] q1.get() return jsonify(result)
import pyEX iex_cloud_client = pyEX.Client( api_token='Tpk_1e8fef17ee254009a45873d2c1b76828', version='sandbox') def receive_pyex_symbols(symbols_pattern): all_symbols = [ symbol_dict['symbol'] for symbol_dict in iex_cloud_client.symbols() ] selected_symbols = [ symbol for symbol in all_symbols if symbol.startswith(symbols_pattern) ] return selected_symbols
import matplotlib.pyplot as plt import pandas as pd from config import token import pyEX as p import os ticker = 'AMD' timeframe = '6m' if os.path.exists("input.csv"): df = pd.read_csv("input.csv") print("Loaded from CSV") else: c = p.Client(api_token=token) df = c.chartDF(ticker, timeframe) df.to_csv("input.csv") df = df[['close']] df.reset_index(level=0, inplace=True) df.columns = ['ds', 'y'] exp1 = df.y.ewm(span=12, adjust=False).mean() exp2 = df.y.ewm(span=26, adjust=False).mean() macd = exp1 - exp2 exp3 = macd.ewm(span=9, adjust=False).mean() plt.plot(df.ds, macd, label='AMD MACD', color='#EBD2BE')
import pandas as pd import os import pyEX as p from datetime import date # https://github.com/d-eremeev/ADM-VRP print(p.chart) c = p.Client(api_token="pk_6ff6a3397f864fa99013ac76f64173c6") # https://pyex.readthedocs.io/en/latest/# watchlist = [ 'AAPL', 'FB', 'TSLA', 'COF', 'MSFT', 'AMD', 'AMZN', 'SPY', 'UBER', 'MSI', 'UAL', 'BRK.B', 'GOOGL', 'RUN', 'NET', 'FSLY', 'NFLX', 'OKTA', 'SHOP', 'QQQ', 'NIO' ] today = date.today() for w in watchlist: csv_name = './dataset/' + w + '_' 'NovDec' + '.csv' if not os.path.exists(csv_name): print('geting infor for symbol: ', w) run_df_detailed_daily = c.chartDF(w, timeframe='1mm') run_df_detailed_daily.to_csv(csv_name)
def load(other_args: List[str], s_ticker, s_start, s_interval, df_stock): """ Load selected ticker Parameters ---------- other_args:List[str] Argparse arguments s_ticker: str Ticker s_start: str Start date s_interval: str Interval to get data for df_stock: pd.DataFrame Preloaded dataframe Returns ------- ns_parser.s_ticker : Ticker s_start: Start date str(ns_parser.n_interval) + "min": Interval df_stock_candidate Dataframe loaded with close and volumes. """ parser = argparse.ArgumentParser( add_help=False, prog="load", description= "Load stock ticker to perform analysis on. When the data source is 'yf', an Indian ticker can be" " loaded by using '.NS' at the end, e.g. 'SBIN.NS'. See available market in" " https://help.yahoo.com/kb/exchanges-data-providers-yahoo-finance-sln2310.html.", ) parser.add_argument( "-t", "--ticker", action="store", dest="s_ticker", required="-h" not in other_args, help="Stock ticker", ) parser.add_argument( "-s", "--start", type=valid_date, default="2019-01-01", dest="s_start_date", help="The starting date (format YYYY-MM-DD) of the stock", ) parser.add_argument( "-i", "--interval", action="store", dest="n_interval", type=int, default=1440, choices=[1, 5, 15, 30, 60], help="Intraday stock minutes", ) parser.add_argument( "--source", action="store", dest="source", choices=["yf", "av", "iex"], default="yf", help="Source of historical data.", ) parser.add_argument( "-p", "--prepost", action="store_true", default=False, dest="b_prepost", help= "Pre/After market hours. Only works for 'yf' source, and intraday data", ) try: # For the case where a user uses: 'load BB' if other_args: if "-t" not in other_args and "-h" not in other_args: other_args.insert(0, "-t") ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return [s_ticker, s_start, s_interval, df_stock] # Daily if ns_parser.n_interval == 1440: # Alpha Vantage Source if ns_parser.source == "av": ts = TimeSeries(key=cfg.API_KEY_ALPHAVANTAGE, output_format="pandas") # pylint: disable=unbalanced-tuple-unpacking df_stock_candidate, _ = ts.get_daily_adjusted( symbol=ns_parser.s_ticker, outputsize="full") df_stock_candidate.columns = [ val.split(". ")[1].capitalize() for val in df_stock_candidate.columns ] df_stock_candidate = df_stock_candidate.rename( columns={ "Adjusted close": "Adj Close", }) # Check that loading a stock was not successful # pylint: disable=no-member if df_stock_candidate.empty: print("") return [s_ticker, s_start, s_interval, df_stock] # pylint: disable=no-member df_stock_candidate.sort_index(ascending=True, inplace=True) # Slice dataframe from the starting date YYYY-MM-DD selected df_stock_candidate = df_stock_candidate[ns_parser. s_start_date:] # Yahoo Finance Source elif ns_parser.source == "yf": df_stock_candidate = yf.download(ns_parser.s_ticker, start=ns_parser.s_start_date, progress=False) # Check that loading a stock was not successful if df_stock_candidate.empty: print("") return [s_ticker, s_start, s_interval, df_stock] df_stock_candidate.index.name = "date" # IEX Cloud Source elif ns_parser.source == "iex": client = pyEX.Client(api_token=cfg.API_IEX_TOKEN, version="v1") df_stock_candidate = client.chartDF(ns_parser.s_ticker) # Check that loading a stock was not successful if df_stock_candidate.empty: print("") return [s_ticker, s_start, s_interval, df_stock] df_stock_candidate = df_stock_candidate[[ "uClose", "uHigh", "uLow", "uOpen", "fClose", "volume" ]] df_stock_candidate = df_stock_candidate.rename( columns={ "uClose": "Close", "uHigh": "High", "uLow": "Low", "uOpen": "Open", "fClose": "Adj Close", "volume": "Volume", }) df_stock_candidate.sort_index(ascending=True, inplace=True) # Slice dataframe from the starting date YYYY-MM-DD selected df_stock_candidate = df_stock_candidate[ns_parser. s_start_date:] # Check if start time from dataframe is more recent than specified if df_stock_candidate.index[0] > pd.to_datetime( ns_parser.s_start_date): s_start = df_stock_candidate.index[0] else: s_start = ns_parser.s_start_date # Intraday else: # Alpha Vantage Source if ns_parser.source == "av": ts = TimeSeries(key=cfg.API_KEY_ALPHAVANTAGE, output_format="pandas") # pylint: disable=unbalanced-tuple-unpacking df_stock_candidate, _ = ts.get_intraday( symbol=ns_parser.s_ticker, outputsize="full", interval=str(ns_parser.n_interval) + "min", ) df_stock_candidate.columns = [ val.split(". ")[1].capitalize() for val in df_stock_candidate.columns ] df_stock_candidate = df_stock_candidate.rename( columns={ "Adjusted close": "Adj Close", }) s_interval = str(ns_parser.n_interval) + "min" # Check that loading a stock was not successful # pylint: disable=no-member if df_stock_candidate.empty: print("") return [s_ticker, s_start, s_interval, df_stock] # pylint: disable=no-member df_stock_candidate.sort_index(ascending=True, inplace=True) # Slice dataframe from the starting date YYYY-MM-DD selected df_stock_candidate = df_stock_candidate[ns_parser. s_start_date:] # Check if start time from dataframe is more recent than specified if df_stock_candidate.index[0] > pd.to_datetime( ns_parser.s_start_date): s_start = df_stock_candidate.index[0] else: s_start = ns_parser.s_start_date # Yahoo Finance Source elif ns_parser.source == "yf": s_int = str(ns_parser.n_interval) + "m" s_interval = s_int + "in" d_granularity = { "1m": 6, "5m": 59, "15m": 59, "30m": 59, "60m": 729 } s_start_dt = datetime.utcnow() - timedelta( days=d_granularity[s_int]) s_date_start = s_start_dt.strftime("%Y-%m-%d") if s_start_dt > ns_parser.s_start_date: # Using Yahoo Finance with granularity {s_int} the starting date is set to: {s_date_start} df_stock_candidate = yf.download( ns_parser.s_ticker, start=s_date_start, progress=False, interval=s_int, prepost=ns_parser.b_prepost, ) else: df_stock_candidate = yf.download( ns_parser.s_ticker, start=ns_parser.s_start_date.strftime("%Y-%m-%d"), progress=False, interval=s_int, prepost=ns_parser.b_prepost, ) # Check that loading a stock was not successful if df_stock_candidate.empty: print("") return [s_ticker, s_start, s_interval, df_stock] if s_start_dt > ns_parser.s_start_date: s_start = pytz.utc.localize(s_start_dt) else: s_start = ns_parser.s_start_date df_stock_candidate.index.name = "date" # IEX Cloud Source elif ns_parser.source == "iex": s_interval = str(ns_parser.n_interval) + "min" client = pyEX.Client(api_token=cfg.API_IEX_TOKEN, version="v1") df_stock_candidate = client.chartDF(ns_parser.s_ticker) df_stock_candidate = client.intradayDF( ns_parser.s_ticker).iloc[0::ns_parser.n_interval] df_stock_candidate = df_stock_candidate[[ "close", "high", "low", "open", "volume", "close" ]] df_stock_candidate.columns = [ x.capitalize() for x in df_stock_candidate.columns ] df_stock_candidate.columns = list( df_stock_candidate.columns[:-1]) + ["Adj Close"] df_stock_candidate.sort_index(ascending=True, inplace=True) new_index = list() for idx in range(len(df_stock_candidate)): dt_time = datetime.strptime( df_stock_candidate.index[idx][1], "%H:%M") new_index.append( df_stock_candidate.index[idx][0] + timedelta(hours=dt_time.hour, minutes=dt_time.minute)) df_stock_candidate.index = pd.DatetimeIndex(new_index) df_stock_candidate.index.name = "date" # Slice dataframe from the starting date YYYY-MM-DD selected df_stock_candidate = df_stock_candidate[ns_parser. s_start_date:] # Check if start time from dataframe is more recent than specified if df_stock_candidate.index[0] > pd.to_datetime( ns_parser.s_start_date): s_start = df_stock_candidate.index[0] else: s_start = ns_parser.s_start_date s_intraday = (f"Intraday {s_interval}", "Daily")[ns_parser.n_interval == 1440] print( f"Loading {s_intraday} {ns_parser.s_ticker.upper()} stock " f"with starting period {s_start.strftime('%Y-%m-%d')} for analysis.\n" ) return [ ns_parser.s_ticker.upper(), s_start, str(ns_parser.n_interval) + "min", df_stock_candidate, ] except Exception as e: print(e, "\nEither the ticker or the API_KEY are invalids. Try again!\n") return [s_ticker, s_start, s_interval, df_stock] except SystemExit: print("") return [s_ticker, s_start, s_interval, df_stock]
## # Retrieves last minute prices for the stock tickers defined in tikers[]. The # retrieved prices are pushed to the corresponding stock metric in Gnocchi DB. ## import pyEX import json import urllib.request from datetime import datetime __author__ = "Leonardo Turchetti, Lorenzo Tonelli, Ludovica Cocchella and Rambod Rahmani" __copyright__ = "Copyright (C) 2021 Leonardo Turchetti, Lorenzo Tunelli, Ludovica Cocchella and Rambod Rahmani" __license__ = "GPLv3" # pyEX engine c = pyEX.Client("pk_e58014e8a6bd415d8af6e459f2353eb5") # keystone token keystone_token = "gAAAAABgqo4EBJerAKtAUGHMUyE93A7Vnoy3XUXZ7lLOGLXki_qXc0rCX6JqFXwFbbv_VrsMud-VEjyGu5KLQDp5NEZpHIExnVhdx6BIVkRAPGdIqKyRV5KJ4ycOLiuwjVkZGurhmvHPCfL1WO6veSc0Gk3D0AsuYPX-dAwGEQbPCN23o5dC9nk" # stock tickers to be retrieved tickers = ["AMZN", "GOOG", "BKNG", "CHTR", "NVDA", "TSLA", "NFLX", "ADBE", \ "FB", "MSFT", "PYPL", "ADSK", "AMD", "EBAY", "FOX"] tickers_metrics = ["a34a5ffb-a616-4583-99df-73885cbac719", \ "06a298cc-aa96-47b0-ac3a-4242536dda0e", \ "64499075-fcc6-4a12-bf8f-8fc6e7b5d20d", \ "606f0e27-7a9c-446b-8d8e-32283eeb3524", \ "955bf952-0f22-4a33-828b-e3046bcceb51", \ "ed8da2ec-fc58-48af-92f8-b746cef30a2d", \ "8f7cd857-b88a-4eb8-9ad7-ad361dea71ce", \ "e2bf842c-f010-44a5-8b91-510c524f8eee", \
def setup(self): self.c = p.Client("pk_123")
from datetime import datetime from time import sleep import pyEX as p from twilio.rest import Client import config # Account setup for Twilio msg account_sid = config.account_sid auth_token = config.auth_token client = Client(account_sid, auth_token) # Setup for Stock API Call c = p.Client(api_token=config.api_token, version='stable') sym="GME" # Current time now = datetime.now() # Time the market opens and closes marketOpenTime = now.replace(hour=8, minute=30, second=0, microsecond=0) marketCloseTime = now.replace(hour=15, minute=0, second=0, microsecond=0) # Check if the price from 5 mins ago has jumped 5% def stock(prev, current): fivePercent = (prev * .05) + prev if fivePercent <= current: return True else: return False
import pandas as pd import seaborn as sns from jupyterthemes import jtplot import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec jtplot.style(theme='onedork',context='talk',fscale=1.6) from matplotlib.lines import Line2D import talib as t #talib provides all kinds of tools for technical indicators import re import ast import decimal import math from datetime import datetime import re from dateutil.rrule import rrule, DAILY c = p.Client(api_token=YOUR API KEY) sym='IEX' col='close' period=14 #RSI typically takes the first 14 days to generate an average change score df = c.chartDF(symbol=sym, timeframe='1y') #need a lot of data for a good plot df.reset_index(inplace=True) df.sort_values(by=['date'],inplace=True) df['rsi']= t.RSI(df[col].values.astype(float), period) df['ema']= t.EMA(df['close'].values.astype(float)) macd, macdsignal,macdhist=t.MACD(df['close'].values.astype(float)) df['macd']=macd df['macdsignal']=macdsignal df['macdhist']=macdhist up,mid,low= t.BBANDS(df[col].values.astype(float),20) df['uppr']=up df['mid']=mid
def check_api_keys(): """Check api keys and if they are supplied""" key_dict = {} if cfg.API_KEY_ALPHAVANTAGE == "REPLACE_ME": # pragma: allowlist secret key_dict["ALPHA_VANTAGE"] = "Not defined" else: df = TimeSeries( key=cfg.API_KEY_ALPHAVANTAGE, output_format="pandas" ).get_intraday(symbol="AAPL") if df[0].empty: key_dict["ALPHA_VANTAGE"] = "defined, test failed" else: key_dict["ALPHA_VANTAGE"] = "defined, test passed" if cfg.API_KEY_FINANCIALMODELINGPREP == "REPLACE_ME": # pragma: allowlist secret key_dict["FINANCIAL_MODELING_PREP"] = "Not defined" else: r = requests.get( f"https://financialmodelingprep.com/api/v3/profile/AAPL?apikey={cfg.API_KEY_FINANCIALMODELINGPREP}" ) if r.status_code in [403, 401]: key_dict["FINANCIAL_MODELING_PREP"] = "defined, test failed" elif r.status_code == 200: key_dict["FINANCIAL_MODELING_PREP"] = "defined, test passed" else: key_dict["FINANCIAL_MODELING_PREP"] = "defined, test inconclusive" if cfg.API_KEY_QUANDL == "REPLACE_ME": # pragma: allowlist secret key_dict["QUANDL"] = "Not defined" else: try: quandl.save_key(cfg.API_KEY_QUANDL) quandl.get_table( "ZACKS/FC", paginate=True, ticker=["AAPL", "MSFT"], per_end_date={"gte": "2015-01-01"}, qopts={"columns": ["ticker", "per_end_date"]}, ) key_dict["QUANDL"] = "defined, test passed" except quandl.errors.quandl_error.ForbiddenError: key_dict["QUANDL"] = "defined, test failed" if cfg.API_POLYGON_KEY == "REPLACE_ME": key_dict["POLYGON"] = "Not defined" else: r = requests.get( f"https://api.polygon.io/v2/aggs/ticker/AAPL/range/1/day/2020-06-01/2020-06-17?apiKey={cfg.API_POLYGON_KEY}" ) if r.status_code in [403, 401]: key_dict["POLYGON"] = "defined, test failed" elif r.status_code == 200: key_dict["POLYGON"] = "defined, test passed" else: key_dict["POLYGON"] = "defined, test inconclusive" if cfg.API_FRED_KEY == "REPLACE_ME": key_dict["FRED"] = "Not defined" else: r = requests.get( f"https://api.stlouisfed.org/fred/series?series_id=GNPCA&api_key={cfg.API_FRED_KEY}" ) if r.status_code in [403, 401, 400]: key_dict["FRED"] = "defined, test failed" elif r.status_code == 200: key_dict["FRED"] = "defined, test passed" else: key_dict["FRED"] = "defined, test inconclusive" if cfg.API_NEWS_TOKEN == "REPLACE_ME": key_dict["NEWSAPI"] = "Not defined" else: r = requests.get( f"https://newsapi.org/v2/everything?q=keyword&apiKey={cfg.API_NEWS_TOKEN}" ) if r.status_code in [401, 403]: key_dict["NEWSAPI"] = "defined, test failed" elif r.status_code == 200: key_dict["NEWSAPI"] = "defined, test passed" else: key_dict["NEWSAPI"] = "defined, test inconclusive" if cfg.TRADIER_TOKEN == "REPLACE_ME": key_dict["TRADIER"] = "Not defined" else: r = requests.get( "https://sandbox.tradier.com/v1/markets/quotes", params={"symbols": "AAPL"}, headers={ "Authorization": f"Bearer {cfg.TRADIER_TOKEN}", "Accept": "application/json", }, ) if r.status_code in [401, 403]: key_dict["TRADIER"] = "defined, test failed" elif r.status_code == 200: key_dict["TRADIER"] = "defined, test passed" else: key_dict["TRADIER"] = "defined, test inconclusive" if cfg.API_CMC_KEY == "REPLACE_ME": key_dict["COINMARKETCAP"] = "Not defined" else: cmc = CoinMarketCapAPI(cfg.API_CMC_KEY) try: cmc.exchange_info() key_dict["COINMARKETCAP"] = "defined, test passed" except CoinMarketCapAPIError: key_dict["COINMARKETCAP"] = "defined, test failed" if cfg.API_FINNHUB_KEY == "REPLACE_ME": key_dict["FINNHUB"] = "Not defined" else: r = r = requests.get( f"https://finnhub.io/api/v1/quote?symbol=AAPL&token={cfg.API_FINNHUB_KEY}" ) if r.status_code in [403, 401, 400]: key_dict["FINNHUB"] = "defined, test failed" elif r.status_code == 200: key_dict["FINNHUB"] = "defined, test passed" else: key_dict["FINNHUB"] = "defined, test inconclusive" if cfg.API_IEX_TOKEN == "REPLACE_ME": key_dict["IEXCLOUD"] = "Not defined" else: try: pyEX.Client(api_token=cfg.API_IEX_TOKEN, version="v1") key_dict["IEXCLOUD"] = "defined, test passed" except PyEXception: key_dict["IEXCLOUD"] = "defined, test failed" # Reddit reddit_keys = [ cfg.API_REDDIT_CLIENT_ID, cfg.API_REDDIT_CLIENT_SECRET, cfg.API_REDDIT_USERNAME, cfg.API_REDDIT_PASSWORD, cfg.API_REDDIT_USER_AGENT, ] if "REPLACE_ME" in reddit_keys: key_dict["REDDIT"] = "Not defined" else: praw_api = praw.Reddit( client_id=cfg.API_REDDIT_CLIENT_ID, client_secret=cfg.API_REDDIT_CLIENT_SECRET, username=cfg.API_REDDIT_USERNAME, user_agent=cfg.API_REDDIT_USER_AGENT, password=cfg.API_REDDIT_PASSWORD, ) try: praw_api.user.me() key_dict["REDDIT"] = "defined, test passed" except ResponseException: key_dict["REDDIT"] = "defined, test failed" # Twitter keys twitter_keys = [ cfg.API_TWITTER_KEY, cfg.API_TWITTER_SECRET_KEY, cfg.API_TWITTER_BEARER_TOKEN, ] if "REPLACE_ME" in twitter_keys: key_dict["TWITTER"] = "Not defined" else: params = { "query": "(\\$AAPL) (lang:en)", "max_results": "10", "tweet.fields": "created_at,lang", } r = requests.get( "https://api.twitter.com/2/tweets/search/recent", params=params, # type: ignore headers={"authorization": "Bearer " + cfg.API_TWITTER_BEARER_TOKEN}, ) if r.status_code == 200: key_dict["TWITTER"] = "defined, test passed" elif r.status_code in [401, 403]: key_dict["TWITTER"] = "defined, test failed" else: key_dict["TWITTER"] = "defined, test inconclusive" # Robinhood keys rh_keys = [cfg.RH_USERNAME, cfg.RH_PASSWORD] if "REPLACE_ME" in rh_keys: key_dict["ROBINHOOD"] = "Not defined" else: key_dict["ROBINHOOD"] = "defined, not tested" # Degiro keys dg_keys = [cfg.DG_USERNAME, cfg.DG_PASSWORD, cfg.DG_TOTP_SECRET] if "REPLACE_ME" in dg_keys: key_dict["DEGIRO"] = "Not defined" else: key_dict["DEGIRO"] = "defined, not tested" # OANDA keys oanda_keys = [cfg.OANDA_TOKEN, cfg.OANDA_ACCOUNT] if "REPLACE_ME" in oanda_keys: key_dict["OANDA"] = "Not defined" else: key_dict["OANDA"] = "defined, not tested" # Binance keys bn_keys = [cfg.API_BINANCE_KEY, cfg.API_BINANCE_SECRET] if "REPLACE_ME" in bn_keys: key_dict["BINANCE"] = "Not defined" else: key_dict["BINANCE"] = "defined, not tested" # SentimentInvestor keys si_keys = [cfg.API_SENTIMENTINVESTOR_KEY, cfg.API_SENTIMENTINVESTOR_TOKEN] if "REPLACE_ME" in si_keys: key_dict["SENTIMENT_INVESTOR"] = "Not defined" else: account = requests.get( f"https://api.sentimentinvestor.com/v4/account" f"?token={cfg.API_SENTIMENTINVESTOR_TOKEN}&key={cfg.API_SENTIMENTINVESTOR_KEY}" ) if account.ok and account.json().get("success", False): key_dict["SENTIMENT_INVESTOR"] = "Defined, test passed" else: key_dict["SENTIMENT_INVESTOR"] = "Defined, test unsuccessful" print( tabulate( pd.DataFrame(key_dict.items()), showindex=False, headers=[], tablefmt="fancy_grid", ), "\n", )
import pandas as pd import numpy as np import matplotlib.pyplot as plt import pyEX import os # from os.path import join, dirname import dotenv dotenv.load_dotenv() # dotenv_path = join(dirname(__file__), '.env') # load_dotenv(dotenv_path) API = os.getenv('API') p = pyEX.Client(API) ticker = 'TSLA' timeframe = '1y' df = p.chartDF(ticker, timeframe) # retrieve ticker data as a dataframe and store as df df = df[['close']] # want chart to be based off close price df.reset_index(level=0, inplace=True) df.columns=['ds','pri'] sma50 = df.pri.rolling(window=50).mean() # 50 day simple moving average sma200 = df.pri.rolling(window=200).mean() # 200 day simple moving average ema20 = df.pri.ewm(span=20, adjust=False).mean() # 20 day EMA plt.plot(df.ds, df.pri, label=ticker + ' ' + str(round(df.pri.iloc[-1], 2)), color = 'black') # Plots the price chart of the ticker plt.plot(df.ds, sma50, label='SMA(50) ' + str(round(sma50.iloc[-1], 2)), color = 'blue') # Plots the SMA(50) of the ticker
def __init__(self): self.secret = 'sk_fae174660924464996b77d14209a973b' self.public = 'pk_2f3691af11ad4df583c95f2a4d89d44a' p.Client(api_token=self.secret, version='v1', api_limit=5)
def load( ticker: str, start: datetime = (datetime.now() - timedelta(days=1100)), interval: int = 1440, end: datetime = datetime.now(), prepost: bool = False, source: str = "yf", iexrange: str = "ytd", ): """ Load a symbol to perform analysis using the string above as a template. Optional arguments and their descriptions are listed above. The default source is, yFinance (https://pypi.org/project/yfinance/). Alternatively, one may select either AlphaVantage (https://www.alphavantage.co/documentation/) or IEX Cloud (https://iexcloud.io/docs/api/) as the data source for the analysis. Please note that certain analytical features are exclusive to the source. To load a symbol from an exchange outside of the NYSE/NASDAQ default, use yFinance as the source and add the corresponding exchange to the end of the symbol. i.e. ‘BNS.TO’. BNS is a dual-listed stock, there are separate options chains and order books for each listing. Opportunities for arbitrage may arise from momentary pricing discrepancies between listings with a dynamic exchange rate as a second order opportunity in ForEx spreads. Find the full list of supported exchanges here: https://help.yahoo.com/kb/exchanges-data-providers-yahoo-finance-sln2310.html Certain analytical features, such as VWAP, require the ticker to be loaded as intraday using the ‘-i x’ argument. When encountering this error, simply reload the symbol using the interval argument. i.e. ‘load -t BNS -s YYYY-MM-DD -i 1 -p’ loads one-minute intervals, including Pre/After Market data, using the default source, yFinance. Certain features, such as the Prediction menu, require the symbol to be loaded as daily and not intraday. Parameters ---------- ticker: str Ticker to get data start: datetime Start date to get data from with interval: int Interval (in minutes) to get data 1, 5, 15, 30, 60 or 1440 end: datetime End date to get data from with prepost: bool Pre and After hours data source: str Source of data extracted iexrange: str Timeframe to get IEX data. Returns ------- df_stock_candidate: pd.DataFrame Dataframe of data """ # Daily if interval == 1440: # Alpha Vantage Source if source == "av": try: ts = TimeSeries(key=cfg.API_KEY_ALPHAVANTAGE, output_format="pandas") # pylint: disable=unbalanced-tuple-unpacking df_stock_candidate, _ = ts.get_daily_adjusted( symbol=ticker, outputsize="full" ) except Exception as e: console.print(e) return pd.DataFrame() df_stock_candidate.columns = [ val.split(". ")[1].capitalize() for val in df_stock_candidate.columns ] df_stock_candidate = df_stock_candidate.rename( columns={ "Adjusted close": "Adj Close", } ) # Check that loading a stock was not successful # pylint: disable=no-member if df_stock_candidate.empty: console.print("No data found.\n") return pd.DataFrame() df_stock_candidate.index = df_stock_candidate.index.tz_localize(None) # pylint: disable=no-member df_stock_candidate.sort_index(ascending=True, inplace=True) # Slice dataframe from the starting date YYYY-MM-DD selected df_stock_candidate = df_stock_candidate[ (df_stock_candidate.index >= start.strftime("%Y-%m-%d")) & (df_stock_candidate.index <= end.strftime("%Y-%m-%d")) ] # Yahoo Finance Source elif source == "yf": df_stock_candidate = yf.download( ticker, start=start, end=end, progress=False, ) # Check that loading a stock was not successful if df_stock_candidate.empty: console.print("") return pd.DataFrame() df_stock_candidate.index.name = "date" # IEX Cloud Source elif source == "iex": df_stock_candidate = pd.DataFrame() try: client = pyEX.Client(api_token=cfg.API_IEX_TOKEN, version="v1") df_stock_candidate = client.chartDF(ticker, timeframe=iexrange) # Check that loading a stock was not successful if df_stock_candidate.empty: console.print("No data found.\n") except Exception as e: if "The API key provided is not valid" in str(e): console.print("[red]Invalid API Key[/red]\n") else: console.print(e) return df_stock_candidate df_stock_candidate = df_stock_candidate[ ["close", "fHigh", "fLow", "fOpen", "fClose", "volume"] ] df_stock_candidate = df_stock_candidate.rename( columns={ "close": "Close", "fHigh": "High", "fLow": "Low", "fOpen": "Open", "fClose": "Adj Close", "volume": "Volume", } ) df_stock_candidate.sort_index(ascending=True, inplace=True) s_start = df_stock_candidate.index[0] s_interval = f"{interval}min" else: s_int = str(interval) + "m" s_interval = s_int + "in" d_granularity = {"1m": 6, "5m": 59, "15m": 59, "30m": 59, "60m": 729} s_start_dt = datetime.utcnow() - timedelta(days=d_granularity[s_int]) s_date_start = s_start_dt.strftime("%Y-%m-%d") df_stock_candidate = yf.download( ticker, start=s_date_start if s_start_dt > start else start.strftime("%Y-%m-%d"), progress=False, interval=s_int, prepost=prepost, ) # Check that loading a stock was not successful if df_stock_candidate.empty: console.print("") return pd.DataFrame() df_stock_candidate.index = df_stock_candidate.index.tz_localize(None) if s_start_dt > start: s_start = pytz.utc.localize(s_start_dt) else: s_start = start df_stock_candidate.index.name = "date" s_intraday = (f"Intraday {s_interval}", "Daily")[interval == 1440] console.print( f"\nLoading {s_intraday} {ticker.upper()} stock " f"with starting period {s_start.strftime('%Y-%m-%d')} for analysis.", ) return df_stock_candidate
import pyEX import json #client = pyEX.Client(api_token = 'Tpk_340be1708c104fc592c0af6497509731', version='sandbox') client = pyEX.Client(api_token='pk_432538e4010b4b11b081550c64338867') quote = {} def setQuote(symbol): global quote quote = getQuote(symbol) def getSymbol(symbol): return symbol def getAdvancedStats(symbol): return client.advancedStats(symbol) def getQuote(symbol): return client.quote(symbol) def getLogoLink(symbol): data = client.logo(symbol) return data['url'] def getPrice(symbol):
from .models import * import pyEX as p import quandl from django.conf import settings # set a global var for the client iex_client = p.Client(api_token=settings.IEX_TOKEN, version='v1') # TODO: Need to add better error handling ''' Get company data from IEX. Format it into a model object and return. ''' def get_equity_data(symbol): try: data = iex_client.company(symbol=symbol) if data: return Equity(symbol=data['symbol'], name=data['companyName'], exchange=data['exchange'], industry=data['industry'], sector=data['sector'], sic=data['primarySicCode']) except Exception as e: print("Exception: ", e.args[1]) return None def get_equity_dividend(equity): try: iex_data = iex_client.dividends(symbol=equity.symbol, timeframe='next')
def __init__(self): self.iex_token = 'pk_1ce76a7935184dc2b0c08b79973e8287' self.pyexClient = p.Client(api_token=self.iex_token)
def get_iex_ticker(ticker): c = p.Client(api_token=IEX_API_KEY) data = c.quote(ticker) return data
import backtrader as bt bt.__path__ # In[3]: import sys get_ipython().system('{sys.executable} -m pip install backtrader[plotting]') # In[4]: import sys get_ipython().system('{sys.executable} -m pip install pyEX') import pyEX import json import os strRoot = 'D:\\denbrige\\180 FxOption\\103 FxOptionVerBack\\083 FX-Git-Pull\\14docktrader\\config\\' with open(strRoot + 'iex.conf') as fJsn: jsnIEX = json.load(fJsn) strVersion = 'v1' objEx = pyEX.Client(api_token=jsnIEX['iextoken'], version=strVersion) objEx.companyDF('AAPL') # In[5]: objEx.earningsDF('AAPL') # In[29]: # unfortunately, pyex has the same issue as iexfinance where you cannot retrieve past historical earnings, cf, bs
# Make sure IEX_TOKEN is exported import os.path import pyEX as p import numpy as np import pandas as pd import matplotlib.pyplot as plt from os import path from datetime import datetime if not path.exists("amd-1y.csv"): print("fetching fresh data") ticker = 'AMD' timeframe = '1y' c = p.Client() df = c.chartDF(ticker, timeframe) df = df[['close']] df.reset_index(level=0, inplace=True) df.columns = ['ds', 'y'] if path.exists("amd-1y.csv"): print("using csv") df = pd.read_csv("amd-1y.csv") sma_20 = df.y.rolling(window=20).mean() sma_50 = df.y.rolling(window=50).mean() sma_200 = df.y.rolling(window=200).mean() plt.plot(df.ds, df.y, label='AMD') plt.plot(df.ds, sma_20, label='AMD 20 Day SMA', color='orange') plt.plot(df.ds, sma_50, label='AMD 50 Day SMA', color='magenta')