def __init__(self): try: intrinio_sdk.ApiClient().configuration.api_key[ 'api_key'] = 'OmNiNGM1YmUyZTFhOGVhODgzMWIxZmNmZjdiYTllZWFj' self.security_api = intrinio_sdk.SecurityApi() self.company_api = intrinio_sdk.CompanyApi() except ApiException as e: print("Exception when establishing connection with api: %s\r\n" % e)
def company(request, company): company_api = intrinio_sdk.CompanyApi() # str | A Company identifier (Ticker, CIK, LEI, Intrinio ID) # identifier = 'AAPL' identifier = company[3:] try: api_response = company_api.get_company(identifier) # return render_to_response(datos.to_html()) return render(request, 'stock_tracker/company.html', {'company': api_response}) except ApiException as err: return HttpResponse('Ha ocurrido un error {}'.format(err))
def get_intrinio_fids(tkr_id, after_date, end_date='', sandbox=False): if sandbox == False: intrinio_sdk.ApiClient().configuration.api_key['api_key'] = config('INTRINIO_KEY') security_api = intrinio_sdk.SecurityApi() elif sandbox == True: intrinio_sdk.ApiClient().configuration.api_key['api_key'] = config('INTRINIO_SANDBOX_KEY') security_api = intrinio_sdk.SecurityApi() # Initialize api's capi = intrinio_sdk.CompanyApi() capi_params = { 'identifier' : tkr_id, 'filed_after' : '', 'filed_before' : '', 'reported_only' : False, # 'fiscal_year' : fiscal_year, 'statement_code' : 'income_statement', 'type' : 'QTR', 'start_date' : after_date, 'end_date' : end_date, 'page_size' : 500, 'next_page' : '' } # Set up dictionary to populate with financial report availibility information for attempt in range(5): try: fundamentals = capi.get_company_fundamentals(**capi_params) except: print("There was a server error. Retrying, attempt {}.".format(attempt)) sleep(5) else: break # n_results = len(fundamentals.fundamentals) # for i in range(n_results): # if fundamentals.fundamentals[i].filing_date != None: # fundamentals.fundamentals[i].filing_date = fundamentals.fundamentals[i].filing_date.strftime('%Y-%m-%d') return(fundamentals.fundamentals)
from __future__ import print_function import time import intrinio_sdk from intrinio_sdk.rest import ApiException intrinio_sdk.ApiClient().configuration.api_key[ 'api_key'] = 'OmI0YTRmNmFiYzI3NDQ5ZGY5MDRjYmE2NGYzNzZmNGZl' company_api = intrinio_sdk.CompanyApi() page_size = 100 # float | The number of results to return (optional) (default to 100) next_page = '' # str | Gets the next page of data from a previous API call (optional) try: api_response = company_api.get_all_company_news(page_size=page_size, next_page=next_page) print(api_response) except ApiException as e: print("Exception when calling CompanyApi->get_all_company_news: %s\n" % e)
def find_fundamentals(tkr_id, sandbox=False, nocomm=False): """ Returns a list of available fundamental financial indicators for the specified company. -- tkr_id: stock ticker name. 'AAPL' for Apple inc, 'XOM' for Exxon Mobile Corp. etc. (if using a developer sandbox key, only DOW 30 will be available) -- sandbox: Use this to turn sandbox mode on and off if you have a developers sandbox api key. Limited to DOW 30, but much less strict limits on api calls. *In .env file name main key INTRINIO_KEY and developer sandbox key INTRINIO_SANDBOX_KEY """ # Sandbox check and get env key if sandbox == False: intrinio_sdk.ApiClient().configuration.api_key['api_key'] = config( 'INTRINIO_KEY') security_api = intrinio_sdk.SecurityApi() elif sandbox == True: intrinio_sdk.ApiClient().configuration.api_key['api_key'] = config( 'INTRINIO_SANDBOX_KEY') security_api = intrinio_sdk.SecurityApi() # Initialize api's capi = intrinio_sdk.CompanyApi() fapi = intrinio_sdk.FundamentalsApi() # Set parameters to get most recent financial report fund_params = { 'identifier': tkr_id, 'filed_after': '2018-06-01', 'filed_before': '2018-11-01', 'reported_only': False, # 'fiscal_year' :fiscal_year, 'statement_code': 'income_statement', 'type': '', 'start_date': '', 'end_date': '', 'page_size': 1, 'next_page': '' } # Get most recent financials report fundamentals = capi.get_company_fundamentals(**fund_params) id_to_check = fundamentals.fundamentals[0].id fun_check = fapi.get_fundamental_standardized_financials(id_to_check) available_fun = [] common = ['date', 'fiscal_year', 'quarter'] # Make list of available fundamentals and add above for fun in fun_check.standardized_financials: available_fun.append(fun.data_tag.tag) if nocomm == False: for fun in common: available_fun.append(fun) else: available_fun.append('date') return (available_fun)
""" Created on Sun Apr 12 01:14:52 2020 @author: danielbartolomeo """ import pandas as pd import numpy as np import sys import intrinio_sdk from intrinio_sdk.rest import ApiException from pprint import pprint sandbox_key = 'Ojg5Y2Q0M2Y1YjVlNjdlMWMzYjY4M2NkZDc2MTQ0ODM3' colist = intrinio_sdk.CompanyApi().get_all_companies() intrinio_sdk.ApiClient().configuration.api_key['api_key'] = sandbox_key security_api = intrinio_sdk.SecurityApi() identifier = 'AAPL' # str | A Security identifier (Ticker, FIGI, ISIN, CUSIP, Intrinio ID) start_date = '2018-01-01' # date | Return prices on or after the date (optional) end_date = '2019-01-01' # date | Return prices on or before the date (optional) frequency = 'daily' # str | Return stock prices in the given frequency (optional) (default to daily) page_size = 100 # int | The number of results to return (optional) (default to 100) next_page = '' # str | Gets the next page of data from a previous API call (optional) try: api_response = security_api.get_security_stock_prices( identifier,
chunksize=None) # companies currently in the details sql table comp_dets = pd.read_sql( sql="select * from dbo.company_details where is_current = 1", con=conn, parse_dates=['insert_date', 'update_date'], chunksize=None) # connect to intrino intrinio_sdk.ApiClient().configuration.api_key['api_key'] = password_file.get( 'intrinio', {}).get('API_sandbox', '') # loop thru company list and make api calls while updating database for int_id in comp_list.loc[:, 'company_id'].to_list(): # make the api call to get the company info temp_dict = intrinio_sdk.CompanyApi().get_company( identifier=int_id).to_dict() # convert to dataframe and rename columns to match columns in database temp_pd = pd.DataFrame( temp_dict, index=[0]).rename(columns={ 'id': 'company_id', 'name': 'company', 'template': 'finstate_template' }).loc[:, comp_dets. columns[~comp_dets.columns. isin(['update_date', 'insert_date', 'is_current'])]] # if the company data is not in the database add it if len(comp_dets.loc[comp_dets['company_id'] == int_id, :]) == 0: # add insert update dates and current flag & insert into database temp_pd.assign(insert_date=dt.date.today()).assign( update_date=dt.date.today()).assign(is_current=1).to_sql( 'company_details',
port=password_file.get('postgres',{}).get('server',{}).get(dbname,{}).get('port','') # use sql alchemy conn string AND connect to database conn = sqlalchemy.create_engine('postgresql://'+user+':'+password+'@'+host+':'+port+'/'+dbname).connect() # get list of intrinio ids to pull the company info for comp_list = pd.read_sql(sql = "select distinct company_id from dbo.company_list where is_current = 1", con = conn, parse_dates=['insert_date', 'update_date'], chunksize=None) # connect to intrino intrinio_sdk.ApiClient().configuration.api_key['api_key'] = password_file.get('intrinio', {}).get('API_sandbox','') # loop thru company list and make api calls while updating database for int_id in comp_list.loc[:,'company_id'].to_list(): # make the api call to get the company info temp = pd.DataFrame(intrinio_sdk.CompanyApi().get_company_securities(identifier = int_id).to_dict().get('securities',{})).rename(columns = {'id':'intrinio_id', 'name':'company'}).reindex(['intrinio_id', 'company_id', 'company', 'code', 'currency', 'ticker', 'composite_ticker', 'figi', 'composite_figi', 'share_class_figi'], axis = 'columns') # loop over the values in the API pull and check against what is stored in the database for sec in temp.loc[:,'intrinio_id']: # get the security from that database sec_list = pd.read_sql(sql = "select intrinio_id, company_id, company, code, currency, ticker, composite_ticker, figi, composite_figi, share_class_figi from dbo.security_list where is_current = 1 and intrinio_id = '"+sec+"'", con = conn, chunksize=None) # Nothing found if len(sec_list) == 0: # insert the API pull temp.loc[temp['intrinio_id'] == sec,:].assign(insert_date = dt.date.today()).assign(update_date = dt.date.today()).assign(is_current = 1).to_sql('security_list', schema = 'dbo', con = conn, index = False, if_exists = 'append') # the API = data base elif temp.loc[temp['intrinio_id'] == sec,:].reset_index(drop = True).equals(sec_list): # update the update date conn.execute("update dbo.security_list set update_date = '"+dt.date.today().strftime("%Y-%m-%d")+"' where intrinio_id = '"+sec+"' and is_current = 1") # the API = data base else: # the update date
def stock_exchange_company(request, company): company_api = intrinio_sdk.CompanyApi() # str | A Company identifier (Ticker, CIK, LEI, Intrinio ID) # identifier = 'AAPL' identifier = company[3:] # str | An Intrinio data tag ID or code (<a href='https://data.intrinio.com/data-tags'>reference</a>) tag = 'close_price' # close_price # str | Return historical data in the given frequency (optional) (default to daily) frequency = 'daily' # str | Return historical data for given fiscal period type (optional) type = '' # date | Return historical data on or after this date (optional) start_date = datetime.today() - timedelta(days=200) # date | Return historical data on or before this date (optional) end_date = datetime.today() - timedelta(days=1) # str | Sort by date `asc` or `desc` (optional) (default to desc) sort_order = 'desc' # int | The number of results to return (optional) (default to 100) page_size = 100 # str | Gets the next page of data from a previous API call (optional) next_page = '' try: api_response = company_api.get_company_historical_data( identifier, tag, frequency=frequency, type=type, start_date=start_date, end_date=end_date, sort_order=sort_order, page_size=page_size, next_page=next_page) stock_prices = api_response.historical_data_dict company_info = api_response.company datos = pd.DataFrame(stock_prices) f = plt.figure() ax = f.add_subplot(111) # TENGO QUE CAMBIAR LA FORMA EN LA QUE MUESTRA LAS FECHAS EL GRÁFICO ax.plot(datos['date'], datos['value']) ax.xaxis.set_major_locator(plt.MaxNLocator(8)) ax.legend(['Stock value for {}'.format(company_info.name)]) plt.ylabel('Value', fontsize=10) plt.xlabel('Date', fontsize=10) ax.tick_params(labelsize=7, width=3) # plt.tight_layout() # Como enviaremos la imagen en bytes la guardaremos en un buffer buf = io.BytesIO() canvas = FigureCanvasAgg(f) canvas.print_png(buf) # Creamos la respuesta enviando los bytes en tipo imagen png response = HttpResponse(buf.getvalue(), content_type='image/png') # Limpiamos la figura para liberar memoria f.clear() # Añadimos la cabecera de longitud de fichero para más estabilidad response['Content-Length'] = str(len(response.content)) # Devolvemos la response return response except ApiException as err: return HttpResponse('Ha ocurrido un error {}'.format(err))
del pass_file # connect to intrino intrinio_sdk.ApiClient().configuration.api_key['api_key'] = password_file.get( 'intrinio', {}).get('API_sandbox', '') # make api calls # create a dummy dict of the company list to store the 'next_page' key colist = {'next_page': ''} # blank dataframe to append the data into companies = pd.DataFrame() # make api calls and loop until entire file is pulled while colist.get('next_page') is not None: # api call colist = intrinio_sdk.CompanyApi().get_all_companies( page_size=100, next_page=colist.get('next_page')).to_dict() try: # merge with previous companies = pd.concat( [companies, pd.DataFrame(colist['companies'])], axis='index') except: # if there is an issue break out of loop break # if you can not reached the end of file sleep if colist.get('next_page') is not None: # ensure no more than 100 API calls per sec time.sleep(0.01) # reset the index companies = companies.reset_index(drop=True).rename(columns={ 'id': 'company_id',
from exception.exceptions import DataError, ValidationError from connectors import intrinio_util from support.financial_cache import cache from datetime import timedelta log = logging.getLogger() try: API_KEY = os.environ['INTRINIO_API_KEY'] except KeyError as ke: raise ValidationError("INTRINIO_API_KEY was not set", None) intrinio_sdk.ApiClient().configuration.api_key['api_key'] = API_KEY FUNDAMENTALS_API = intrinio_sdk.FundamentalsApi() COMPANY_API = intrinio_sdk.CompanyApi() SECURITY_API = intrinio_sdk.SecurityApi() INTRINIO_CACHE_PREFIX = 'intrinio' ''' Testing APIs using requests package ''' def retry_server_errors(func): ''' decorator that will retry intrinio server side errors, and let others pass through. Retries the error up to 5 times and sleeps 2 seconds between retries '''