Beispiel #1
0
def fundamentals_from_fids(fids_list, 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
    fapi = intrinio_sdk.FundamentalsApi()

    fund_dict = {}
    for id in fids_list:
        for attempt in range(5):
            try:
                fundamentals_ret = fapi.get_fundamental_standardized_financials(id)
            except:
                print('Connection error. Retry attempt {}'.format(attempt))
                sleep(2)
            else:
                break
        fund_get = fundamentals_ret.standardized_financials_dict
        fund_info = fundamentals_ret.fundamental_dict
        funds = {}
        funds['date'] = fund_info['filing_date']
        funds['fiscal_year'] = fund_info['fiscal_year']
        funds['quarter'] = fund_info['fiscal_period']
        for f in fund_get:
            funds[f['data_tag']['tag'].lower()] = f['value']
        fund_dict[id] = funds
    return fund_dict
Beispiel #2
0
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)
Beispiel #3
0
 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)
Beispiel #4
0
 def __init__(self, identifier):
     intrinio_sdk.ApiClient(
     ).configuration.api_key['api_key'] = 'YOUR API KEY'
     self.identifier = identifier
     self.start_date = days_ago
     self.end_date = today
     self.frequency = frequency
     self.page_size = page_size
     self.next_page = next_page
     X = []
     self.original_data = X
Beispiel #5
0
def get_connection():
    with open(config_file_name, 'r') as f:
        vals = yaml.safe_load(f)

    if not ('PRODUCTION_API_KEY' in vals.keys() and 'SANDBOX_API_KEY'
            in vals.keys() and 'USE_PRODUCTION' in vals.keys()):
        raise Exception('Bad config file: ' + config_file_name)

    intrinio_sdk.ApiClient(
    ).configuration.api_key['api_key'] = vals['PRODUCTION_API_KEY'] if vals[
        'USE_PRODUCTION'] else vals['SANDBOX_API_KEY']

    return intrinio_sdk
Beispiel #6
0
def get_stonks():
    intrinio_sdk.ApiClient().configuration.api_key['api_key'] = 'API-KEY'
    security_api = intrinio_sdk.SecurityApi()
    identifiers = ['AAPL', 'MSFT', 'GS', 'NKE']
    price_list = list()
    try:
        for identifier in identifiers:
            api_response = security_api.get_security_realtime_price(identifier)
            price_list.append((identifier, api_response.ask_price))
    except ApiException as e:
        print(
            "Exception when calling SecurityApi->get_security_realtime_price: %s\r\n"
            % e)
    finally:
        return price_list
def Getstock(name):
    intrinio_sdk.ApiClient(
    ).configuration.api_key['api_key'] = '[your-intrino-api-key]'

    security_api = intrinio_sdk.SecurityApi()

    identifier = name  # str | A Security identifier (Ticker, FIGI, ISIN, CUSIP, Intrinio ID)
    #returns info on stock in json format
    try:
        api_response = security_api.get_security_realtime_price(identifier)
        high = api_response.high_price
        low = api_response.low_price
        opn = api_response.open_price
        exc = api_response.exchange_volume
        stock = [high, low, opn, exc]
        return (stock)

    except ApiException as e:
        zip = (
            "Exception when calling SecurityApi->get_security_realtime_price: %s\n"
            % e)
Beispiel #8
0
def get_data_intrinio(ticker):
    import intrinio_sdk
    from pprint import pprint
    from intrinio_sdk.rest import ApiException

    intrinio_sdk.ApiClient(
    ).configuration.api_key['api_key'] = globals.INTRINIO_API_KEYS[0]
    security_api = intrinio_sdk.SecurityApi()
    identifier = ticker  # str | A Security identifier (Ticker, FIGI, ISIN, CUSIP, Intrinio ID)

    try:
        start_date = '2019-08-01'  # date | Return intraday prices starting at the specified date (optional)
        end_date = '2019-08-04'  # date | Return intraday prices stopping at the specified date (optional)
        api_response1 = security_api.get_security_realtime_price(
            identifier, start_date=start_date, end_date=end_date)
        api_response2 = security_api.get_security_realtime_price(
            identifier)  #, start_date=start_date, end_date=end_date)
        pprint(api_response1)
        pprint(api_response2)
    except ApiException as e:
        print(
            "Exception when calling SecurityApi->get_security_intraday_prices: %s\n"
            % e)
# [NAME: library.py]

# [IMPORTS]
from __future__ import print_function
import csv
import time
import json
import pickle
import intrinio_sdk
from pprint import pprint
from urllib.request import urlopen
from finviz.screener import Screener
from intrinio_sdk.rest import ApiException

# [PRE-SCRIPTING DIRECTIVES & CONSTANT CREATION]
intrinio_sdk.ApiClient().configuration.api_key['api_key'] = 'Ojg1Y2IzMzFlNjcxY2U3YmYwNzc5MjgyNTgwMjEyM2Jh'
company_api = intrinio_sdk.CompanyApi()

# [PRIMARY SCREEN FOR COMPANIES WITH M_CAPS GREATER THAN 3B.]
def compilepimary():
	dictionary_ticker_mc = {}
	filters = ['cap_midover','geo_usa']
	stock_list = Screener(filters=filters, table='Valuation', order='market cap')  # Get the performance table and sort it by price ascending
	for stock in stock_list:
		dictionary_ticker_mc[stock['Ticker']] = stock['Market Cap']
	remove = [k for k,v in dictionary_ticker_mc.items() if v == '-']
	for k in remove: 
		del dictionary_ticker_mc[k]
	return dictionary_ticker_mc

# [PULLS INFORMATION ABOUT EBIT AND ENTERPROSE VALUE. CALCULATE RATIO AND SAVES TO PICKLE FILE]
Beispiel #10
0
def gather_financial_statement_time_series(
        api_key, ticker, statement, year, period, output_format='pddf'):
    """
    Given the tickers, statement, year and period returns the complete
    financial information from the Intrinio API stock data
    Parameters
    -----------
    api_key : str
      API key (sandbox or production) from Intrinio
    ticker : str
      the ticker symbol you would like to get information for
    statement : str
      the statement that you want to study
      options: 'income_statement', 'cash_flow_statement',
      'balance_sheet_statement'
    year : list
      the list containing the years as strings
    period : list
      the list of quarters (as strings) for which you want information
    output_format : str (optional, default = 'pddf')
      the output format for the data, options are 'dict' for dictionary
      or 'pddf' for pandas dataframe
    Returns
    -----------
    object of type output_format
      information about the given statement for the given ticker
      at the given times in the specified output format
    Example
    -----------
    >>> gather_financial_statement_time_series(api_key, ticker='AAPL',
    statement='income_statement', year=['2018', '2019'],
    period=['Q1'], output_format='dict')
    """
    # https://data.intrinio.com/data-tags
    available_statements = [
        'income_statement', 'cash_flow_statement', 'balance_sheet_statement'
    ]
    inputs = {'api_key': api_key, 'ticker': ticker, 'statement': statement}
    # Check if api_key, ticker and statement are strings
    for inst in inputs.keys():
        if isinstance(inputs[inst], int):
            raise TypeError(
                "Invalid data format: " + inst +
                " must be a string")
        elif isinstance(inputs[inst], float):
            raise TypeError(
                "Invalid data format: " + inst +
                " must be a string")
        elif not isinstance(inputs[inst], str):
            raise NameError("Invalid data format: " + inst +
                            " must be a string")
    # Check if the output_format is either 'dict' or 'pddf'
    if output_format not in ['dict', 'pddf']:
        raise Exception(
            "Invalid data format: output_format" +
            "must be 'dict' or 'pddf'")
    # Check that the value of statement is valid
    if statement not in available_statements:
        raise Exception(
            "Invalid data format: statement must be one of" +
            "'income_statement', 'cash_flow_statement' or " +
            "'balance_sheet_statement'")
    # Check that year is a list
    if isinstance(year, int):
        raise TypeError("Invalid data format: year must be a string")
    elif isinstance(year, float):
        raise TypeError("Invalid data format: year must be a string")
    if not type(year) is list:
        raise NameError("Invalid data format: year must be a list of strings")
    # Check that period is a list
    if not type(period) is list:
        raise NameError(
            "Invalid data format: " +
            "period must be a list of strings")
    # Check that the length of year is 4
    for y in year:
        if not len(y) == 4:
            raise Exception(
                "Invalid data format: " +
                "year must be a string of 4 digits")
    # Initialize API key
    intrinio_sdk.ApiClient().configuration.api_key['api_key'] = api_key
    fundamentals_api = intrinio_sdk.FundamentalsApi()
    # Empty list to store results: reformat later to dataframe
    results = []
    # Outer loop over years, inner loop over quarters
    for i in year:
        for j in period:
            # define key to obtain relevant information
            key = str(ticker) + '-' + str(statement) + \
                '-' + str(i) + '-' + str(j)
            # Obtain req. object from API
            try:
                # put stock prices into a variable
                funda = fundamentals_api.get_fundamental_reported_financials(
                    key)
            except Exception:
                print(
                    "Invalid API Key: please input a valid API key as a string"
                )
                return
            my_fund = funda.reported_financials
            # Empty dictionary to append the results : convert to df at the
            # last stage
            my_dict = {}
            my_dict['ticker'] = ticker
            my_dict['statement'] = statement
            my_dict['year'] = i
            my_dict['period'] = j
            for n in range(0, len(my_fund)):
                my_dict[str(my_fund[n].xbrl_tag.tag)] = []
            # add values to the dictionary
            for k in range(0, len(my_fund)):
                for key, val in my_dict.items():
                    if my_fund[k].xbrl_tag.tag == key:
                        my_dict[key].append(my_fund[k].value)
                        my_dict[key] = [sum(my_dict[key])]
            results.append(my_dict)
    final_df = pd.DataFrame(results)
    # if_else for output format
    if output_format == 'pddf':
        return final_df
    else:
        return results
Beispiel #11
0
from __future__ import print_function
import time
import intrinio_sdk
from intrinio_sdk.rest import ApiException
from pprint import pprint, pformat
import json

intrinio_sdk.ApiClient().configuration.api_key[
    'api_key'] = 'OjMwMDZjOWUwNjMzY2FlZjhlNjdkY2NkMTMzZmFhZDhj'
company_api = intrinio_sdk.CompanyApi()

identifier = '$SIC.20'  # str | A Security identifier (Ticker, FIGI, ISIN, CUSIP, Intrinio ID)

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:
    companyInfo = company_api.get_company(identifier)
    #stockInfo = security_api.get_security_stock_prices(identifier, start_date=start_date, end_date=end_date, frequency=frequency, page_size=page_size, next_page=next_page)
    f = open("Company Info.json", "w")
    pprint(companyInfo)
    f.write(str(pformat(companyInfo)))
    #s = open("Stock Info.json", "w")
    #s.write(str(pformat(stockInfo)))
    f.close()
Beispiel #12
0
def gather_stock_time_series(
        api_key, ticker, start_date=None, end_date=None, output_format='dict',
        allow_max_rows=False):
    """
    Given the ticker, start date, and end date, return from the Intrinio API
        stock data for that time frame in either a dictionary or a pandas
        dataframe format.

    Parameters
    -----------
    api_key : str
        API key (sandbox or production) from Intrinio
    ticker : str
        the ticker symbol you would like to get stock data for
    start_date : str (optional)
        the earliest date in the format of "%Y-%m-%d", e.g. "2019-12-31" to
        get data for
    end_date : str (optional)
        the most recent date in the format of "%Y-%m-%d", e.g. "2019-12-31" to
        get data for
    output_format : str (optional, default = 'dict')
        the output format for the data, options are 'dict' for dictionary or
        'pddf' for pandas dataframe
    allow_max_rows : bool (optional, default = False)
        if False, then only 100 rows will show in the output, otherwise up to
        10000 rows will show (based on dates)

    Returns
    -----------
    object of type output_format
        stock data for the specific timeframe in the specified output format

    Example
    -----------
    >>> gather_stock_time_series(api_key, 'AAPL', start_date="2020-01-15",
    end_date="2020-01-30", output_format="pddf")
    """
    # error messages
    msg1 = "Invalid data format: ticker must be a string"
    msg2 = "Invalid Date format: date must be a string in the format %Y-%m-%d"
    msg3 = "Invalid Input: end_date must be later than start_date"
    msg4 = "Invalid API Key: please input a valid API key as a string"

    # ensure the type of the ticker is a string
    if type(ticker) != str:
        return msg1

    try:
        # change dates to datetime objects
        if start_date is not None:
            start_date = datetime.strptime(start_date, '%Y-%m-%d').date()
        if end_date is not None:
            end_date = datetime.strptime(end_date, '%Y-%m-%d').date()
    except Exception:
        return msg2

    if start_date is not None and end_date is not None:
        if start_date >= end_date:
            return msg3

    # initialize API key
    intrinio_sdk.ApiClient().configuration.api_key['api_key'] = api_key

    # initialize security API
    security_api = intrinio_sdk.SecurityApi()

    # if allow_max_rows=False
    if allow_max_rows is False:
        rows = 100
    else:
        rows = 10000

    try:
        # put stock prices into a variable
        stock_prices = security_api.get_security_stock_prices(
            ticker, start_date=start_date, end_date=end_date,
            page_size=rows).stock_prices
    except Exception:
        return msg4

    # initialize a results dictionary
    results = {'date': [], 'close': [], 'adj_close': [], 'high': [],
               'adj_high': [], 'low': [], 'adj_low': [], 'open': [],
               'adj_open': [], 'volume': [], 'adj_volume': [], 'frequency': [],
               'intraperiod': []}

    # fill in dictionary
    for i in list(range(0, len(stock_prices), 1)):
        results['date'].append(stock_prices[i].date)
        results['close'].append(stock_prices[i].close)
        results['adj_close'].append(stock_prices[i].adj_close)
        results['high'].append(stock_prices[i].high)
        results['adj_high'].append(stock_prices[i].adj_high)
        results['low'].append(stock_prices[i].low)
        results['adj_low'].append(stock_prices[i].adj_low)
        results['open'].append(stock_prices[i].open)
        results['adj_open'].append(stock_prices[i].adj_open)
        results['volume'].append(stock_prices[i].volume)
        results['adj_volume'].append(stock_prices[i].adj_volume)
        results['frequency'].append(stock_prices[i].frequency)
        results['intraperiod'].append(stock_prices[i].intraperiod)

    # if the ouput format is a dataframe, change to that
    if output_format == 'pddf':
        results = pd.DataFrame(results)

    return results
Beispiel #13
0
def gather_financial_statement_company_compare(api_key, ticker, statement,
                                               year, period,
                                               output_format='dict'):
    """
    Given the tickers, statement, year and period returns all the
        information from the Intrinio API fundamental reported financials
        for that time and those tickers in either a dictionary or a pandas
        dataframe format.

    Parameters
    -----------
    api_key : str
        API key (sandbox or production) from Intrinio
    ticker : list
        a list of the ticker symbols you would like to study
    statement : str
        the statement that you want to study
        options: 'income_statement', 'cash_flow_statement',
        'balance_sheet_statement'
    year : str
        the year you want the information from
    period : str
        the period you want the information from
    output_format : str (optional, default = 'dict')
        the output format for the data, options are 'dict' for dictionary or
        'pddf' for pandas dataframe

    Returns
    -----------
    object of type output_format
        information about the given statement for the given tickers at the
        given time in the specified output format

    Example
    -----------
    >>> gather_financial_statement_company_compare(api_key,
    ['AAPL', 'CSCO'], 'income_statement', '2019', 'Q1')
    """
    statements = ['income_statement', 'balance_sheet_statement',
                  'cash_flow_statement']

    inputs = {'api_key': api_key, 'statement': statement, 'year': year,
              'period': period}

    intrinio_sdk.ApiClient().configuration.api_key['api_key'] = api_key
    fundamentals_api = intrinio_sdk.FundamentalsApi()

    # Check if api_key, statement, year, period are strings
    for inst in inputs.keys():
        if not isinstance(inputs[inst], str):
            raise TypeError("Invalid data format: " + inst +
                            " must be a string")

    # test if the API Key works
    try:
        fundamentals_api.get_fundamental_reported_financials(
            'AAPL-income_statement-2019-Q1')
    except Exception:
        msg_apy = "Invalid API Key: please input a valid API key as a string"
        return msg_apy

    # Check if ticker is a list

    if not isinstance(ticker, list):
        raise TypeError("Invalid data format: ticker must be a list")

    # Check if the elements in the ticker list are strings
    for comp in ticker:
        if not isinstance(comp, str):
            raise TypeError(
                'Invalid data format: ticker must be a list of strings')

    # Check if the year is a 4-digits number
    if not len(year) == 4:
        raise Exception(
            "Invalid data format: year must be a string of 4 digits")

    # Check if the output_format is either 'dict' or 'pddf'
    if output_format not in ['dict', 'pddf']:
        raise Exception(
            "Invalid data format: output_format must be 'dict' or 'pddf'"
        )

    # Check if the statement is valid
    if statement not in statements:
        raise Exception(
            "Invalid data format: statement must be a valid type"
        )

    # link with the API
    intrinio_sdk.ApiClient().configuration.api_key['api_key'] = api_key
    fundamentals_api = intrinio_sdk.FundamentalsApi()

    # result will contain a dictionnary for each company.
    # This dictionnary will contain all the information for one company
    result = []

    # for every company
    for comp in ticker:
        # key is the appropriate key to select the information we want
        key = comp + '-' + str(statement) + '-' + str(year) + '-' + str(period)
        try:
            # get the object that we want from the API
            fund = fundamentals_api.get_fundamental_reported_financials(
                key)
        except Exception:
            msg = "Invalid agruments: please make sure that your statement"
            msg = msg + "/year/period are valid"
            return msg

        my_fund = fund.reported_financials

        # This dictionary will contain all the information for one company
        dict = {}
        dict['ticker'] = comp
        dict['statement'] = statement
        dict['year'] = year
        dict['period'] = period

        # we store all the values, balances, names and the tags
        for i in range(len(my_fund)):
            value = my_fund[i].value
            tag_dic = my_fund[i].xbrl_tag
            balance = tag_dic.balance
            name = tag_dic.name
            tag = tag_dic.tag
            # tag is a key of this dictionnary

            # if the tag is several times in the original object, we keep
            # one tag and the value is the sum or the substraction of
            # all the values of this tag (depending on the value of balance)
            if tag in dict.keys():
                if balance == 'credit':
                    value = dict[tag]['value'] - value
                else:
                    value = dict[tag]['value'] + value
            dict[tag] = {'value': value, 'balance': balance, 'name': name}
        result.append(dict)

    if output_format == 'dict':
        return result

    # if the wanted type of the output is a dataframe
    else:
        # initialize a new empty dictionnary that we will convert into a
        # dataframe
        # this dictionnary will have the following structure
        # {'name': [name1, name2], 'revenue' :
        # [revenu_company_1, revenue_company_2], ...}
        df = {}

        # for every company
        for i in range(len(result)):

            # select all the information about this company
            sub_dict = result[i]

            # For all the tags that we have for this company
            for val in sub_dict.keys():

                # if the key is already in the df dictionary
                if val in df.keys():

                    # if the value that corresponds to the key is a string
                    # which means that the key is 'ticker', 'statement',
                    # 'year' or 'period'
                    if type(sub_dict[val]) == str:

                        # We append the value of the key
                        df[val].append(sub_dict[val])

                    # if the value of the key is a dictionary
                    else:

                        # only take the value that corresponds to the key
                        # 'value'
                        df[val].append(sub_dict[val]['value'])

                # This step is to make sure that all the values in this
                # dictionary (which are lists) are the same length
                # if the tag of the company is not already in the df dictionary
                else:

                    if type(sub_dict[val]) == str:
                        # We have to put as many 'None' as the number of
                        # companies for which we already collected the
                        # information
                        df[val] = [None for j in range(i)] + [sub_dict[val]]
                    else:
                        df[val] = [None for j in range(
                            i)] + [sub_dict[val]['value']]
                        # We add some 'None' to make sure that all the values
                        # are the same length in this dictionary
            for val in df.keys():
                # The length of each value should be i+1
                # (=number of companies we studied)
                if len(df[val]) != i+1:
                    df[val].append(None)

    return pd.DataFrame(df)
Beispiel #14
0
Created on Thu Jun 18 14:38:41 2020

@author: Max
"""

import numpy as np
import pandas as pd
import yfinance as yf
import quandl

#Yahoo
df_yahoo = yf.download(['AAPL', 'MSFT'], actions='inline', progress=True)
print(df_yahoo)

#Intrinsio set-up
import intrinio_sdk

intrinio_sdk.ApiClient().configuration.api_key[
    'api_key'] = "OjZkMThlZjVjOWUyMjk1ZjBmMDhjNGVjZTRhOTYzYjUw"
security_api = intrinio_sdk.SecurityApi()
#Intrinsio call
r = security_api.get_security_stock_prices(identifier='AAPL',
                                           start_date='2000-01-01',
                                           end_date='2010-12-31',
                                           frequency='daily',
                                           page_size=1000)
response_list = [x.to_dict() for x in r.stock_prices]
df_intrinio = pd.DataFrame(response_list).sort_values('date')
df_intrinio.set_index('date', inplace=True)
print(df_intrinio)
import os
import requests
import pandas as pd

import sqlalchemy

from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())

import intrinio_sdk
from intrinio_sdk.rest import ApiException
intrinio_sdk.ApiClient().configuration.api_key['api_key'] = os.getenv(
    'INTRINIO_PROD_KEY')
security_api = intrinio_sdk.SecurityApi()

from helper import (ingest_security)

# open sqllite db
engine = sqlalchemy.create_engine('sqlite:///securities.db')
db_session = sqlalchemy.orm.Session(bind=engine)

# Ingest  ETF Data
for ETF in ['SPY', 'IEF', 'GLD']:
    ingest_security(intrinio_security=security_api,
                    db_session=db_session,
                    ticker=ETF,
                    name=None,
                    type='etf')

# write s&p 500 companies
resp = requests.get('https://datahub.io/core/s-and-p-500-companies/r/0.csv')
Beispiel #16
0
from future import print_function
import time
import intrinio_sdk
from intrinio_sdk.rest import ApiException
intrinio_sdk.ApiClient(
).configuration.api_key['api_key'] = 'OjE3ZWZmZjFhMGJkMmI2ZjQ0ZjcwMDdjMGVjNjA4ZDQw'
fundamentals_api = intrinio_sdk.FundamentalsApi()
identifier = 'DIS'
statement_code = 'income_statement'  # str | The statement code
fiscal_year = 2017  # int | The fiscal year
fiscal_period = 'FY'  # str | The fiscal period
try:
    api_response = fundamentals_api.lookup_fundamental(
        identifier, statement_code, fiscal_year, fiscal_period)
with open('outputfile.json', 'w') as outf:
    outf.write(str(api_response).replace("\'", "\"").replace('None', '"None"').replace(
        'False', '"False"').replace("datetime.date", "\"datetime.date").replace(")", ")\""))
except ApiException as e:
    print("Exception when calling IndexApi->get_economic_index_by_id: %s\n" % e)
Beispiel #17
0
from __future__ import print_function
import time
import intrinio_sdk as intrinio
from intrinio_sdk.rest import ApiException

intrinio.ApiClient().configuration.api_key[
    'api_key'] = 'OjUwYjk1NjVhZTY4YWFmODRkOGZmZTAwNmQ2N2ExMzli'


class StockIndex:
    def __init__(self, ticker):
        pass


def main():
    identifier = '^GSPC'
    start_date = '2018-01-01'
    end_date = '2019-01-01'
    frequency = 'daily'
    page_size = 100
    next_page = ''
    response = intrinio.SecurityApi().get_security_stock_prices(
        identifier,
        start_date=start_date,
        end_date=end_date,
        frequency=frequency,
        page_size=page_size,
        next_page=next_page)
    print(response)

Beispiel #18
0
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)
Beispiel #19
0
import csv
import intrinio_sdk

APIKEY = 'YOUR_API_KEY'

# List sourced from DOW30
# https://docs.intrinio.com/developer-sandbox

STOCKS = [
    'AAPL', 'AXP', 'BA', 'CAT', 'CSCO', 'CVX', 'DIS', 'DWDP', 'GE', 'GS', 'HD',
    'IBM', 'INTC', 'JNJ', 'JPM', 'KO', 'MCD', 'MMM', 'MRK', 'MSFT', 'NKE',
    'PFE', 'PG', 'TRV', 'UNH', 'UTX', 'V', 'VZ', 'WMT', 'XOM'
]

intrinio_sdk.ApiClient().configuration.api_key['api_key'] = APIKEY,
security_api = intrinio_sdk.SecurityApi()

for stock in STOCKS:
    # Loop through the API response creating a list in the format we need.
    print(stock)
    api_response = security_api.get_security_stock_prices(stock)
    prices = []
    for row in api_response.stock_prices_dict:
        date = row['date']
        o = row['adj_open']
        h = row['adj_high']
        l = row['adj_low']
        c = row['adj_close']
        v = row['adj_volume']
        prices.append([date, o, h, l, c, v])
from __future__ import print_function
import time
import intrinio_sdk
from intrinio_sdk.rest import ApiException
from pprint import pprint

intrinio_sdk.ApiClient().configuration.api_key['api_key'] = 'YOUR_API_KEY'

crypto_api = intrinio_sdk.CryptoApi()
exchange = 'gemini'  # str | Returns stats for Crypto Currencies that trade on the specified Crypto Exchange. (optional)

currency = 'BTC'  # str | Returns stats for the specified Crypto Currency. (optional)

try:
    api_response = crypto_api.get_crypto_stats(exchange=exchange,
                                               currency=currency)
    stats = api_response.stats
    print("%s stats found!" % (len(stats)))

    for stat in stats:
        print("Name:             %s" % (stat.name))
        print("Code:             %s" % (stat.code))
        print("Symbol:           %s" % (stat.symbol))
        print("Market cap(USD):  %s" % (stat.market_cap_usd))
        print("Available supply: %s" % (stat.available_supply))
        print("Total supply:     %s" % (stat.total_supply))
        print("Max supply:       %s" % (stat.max_supply))
        print("Last updated:     %s" % (stat.last_updated))
        print("")
except ApiException as e:
    print("Exception when calling CryptoApi->get_crypto_stats: %s\n" % e)
Beispiel #21
0
# 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)
# 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.
Beispiel #22
0
def gather_stock_returns(api_key, ticker, buy_date, sell_date):
    """
    Given the tickers, buy-in date, sell-out date, returns the historical
    prices and profit/loss (based on the adjusted closing prices).

    Parameters
    -----------
    api_key : str
        API key (sandbox or production) from Intrinio
    tickers : list or str
        a single ticker or a list containing tickers. e.g. 'AAPL' or
        ['AAPL', 'CSCO']
    buy_date : str
        the buy-in date in the format of "%Y-%m-%d", e.g. "2019-12-31". If the
        input date is not a trading day, it will be automatically changed to
        the next nearest trading day.
    sell_date : str
        the sell-out date in the format of "%Y-%m-%d", e.g. "2019-12-31". If
        the input date is not a trading day, it will be automatically changed
        to the last nearest trading day.

    Returns
    -----------
    pandas.core.frame.DataFrame
        a dataframe that contains the companies, historical prices and
        corresponding profit/loss

    Example
    -----------
    >>> gather_stock_returns(api_key, ['AAPL', 'CSCO'], "2017-12-31",
    "2019-03-01")
    """

    msg1 = "Invalid Input: sell_date must be later than buy_date"
    msg2 = "Invalid Date format: date must be a string in the format %Y-%m-%d"
    msg3 = "Invalid API Key: please input a valid API key as a string"

    # test whether the input dates are in the right format
    try:
        buy_date = datetime.strptime(buy_date, '%Y-%m-%d').date()
        sell_date = datetime.strptime(sell_date, '%Y-%m-%d').date()
        if buy_date >= sell_date:
            return msg1
    except Exception:
        return msg2

    if type(ticker) == str:  # if user gives just one ticker
        ticker = [ticker]

    # initialize API key
    intrinio_sdk.ApiClient().configuration.api_key['api_key'] = api_key

    # initialize security API
    security_api = intrinio_sdk.SecurityApi()

    # test if the API Key works
    try:
        security_api.get_security_stock_prices(ticker[0], start_date=buy_date,
                                               end_date=sell_date)
    except Exception:
        return msg3

    # create the result DataFrame to record and report
    results = pd.DataFrame(columns=['Stock', 'Buy date', 'Buy price',
                                    'Sell date', 'Sell price', 'Return (%)'],
                           index=range(len(ticker)))

    # iterate through all the tickers and record the results
    i = 0
    # if buy_date it not a trading day (holiday), we'll get the nearest next
    # trading day instead
    buy_date_upper = buy_date + timedelta(days=10)
    # the same idea for sell_date, but we'll get the nearest **last** trading
    # day instead.
    sell_date_lower = sell_date - timedelta(days=10)

    for ticker in ticker:
        api_response = security_api.get_security_stock_prices(
            ticker,
            start_date=buy_date,
            end_date=buy_date_upper
        )
        buy_price = api_response.stock_prices[-1].adj_close
        buy_date = api_response.stock_prices[-1].date.strftime("%Y-%m-%d")

        api_response = security_api.get_security_stock_prices(
            ticker, start_date=sell_date_lower, end_date=sell_date)
        sell_price = api_response.stock_prices[0].adj_close
        sell_date = api_response.stock_prices[0].date.strftime("%Y-%m-%d")
        rtn = ((sell_price - buy_price) / buy_price)*100
        rtn = round(rtn, 2)

        results.iloc[i, :] = [ticker, buy_date, buy_price, sell_date,
                              sell_price, rtn]
        i += 1

    return results
import requests
import json
import intrinio_sdk
from intrinio_sdk.rest import ApiException
from pprint import pprint

intrinio_sdk.ApiClient().configuration.api_key[
    'api_key'] = 'OmFlZDI5OGJlZjY0YzkzNTk5OGIwYTZlZWQ3NWQwZjY5'
security_api = intrinio_sdk.SecurityApi()


def writeHTML(data):
    myfile = open("playerAPI.html", "w")  # use "a" to "append"

    ############### CSS

    myfile.write("""
    <html>

      <head>
        <title> MY PAGE </title>
      </head>

      <body>
        <font size="3" color="red">This is some text!</font>
        <font size="2" color="blue">This is some text!</font>
        <font face="verdana" color="green">This is some text!</font>
        <h1>Welcome to My Soccer Home Page</h1>

        <p>Go to <a href='https://apilist.fun/api/the-sports-db'>The Sports DB</a> for API Info.</p>
Beispiel #24
0
from dateutil.parser import parse
from stock_price.models import Stock
from stock_price.imgloader import draw_line_chart, make_bar_chart

from django.http import FileResponse
from reportlab.lib import colors
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle




tag = ''
start_date = ''
order = ''
identifier_group = []
intrinio_sdk.ApiClient().configuration.api_key['api_key'] = ''
filename = 'stock_price/initiation.json'
historical_data_api = None
company_api = None


with open(os.path.abspath(filename), 'r') as f:
	datastore = json.load(f)
	intrinio_sdk.ApiClient().configuration.api_key['api_key'] = datastore["api_key"]
	identifier_group = datastore["default_identifiers"]
	tag = datastore["tag"]
	start_date = datastore["default_date"]
	order = datastore["order"]


historical_data_api = intrinio_sdk.HistoricalDataApi()
import pandas as pd
import intrinio_sdk

intrinio_sdk.ApiClient().configuration.api_key[
    'api_key'] = 'OjJiZDM3OWU0ZTI0YmM5YTdhNzY1NjIwZjczZGRjMjg0'
security_api = intrinio_sdk.SecurityApi()
company_api = intrinio_sdk.CompanyApi()
fundamentals_api = intrinio_sdk.FundamentalsApi()


def get_intrinio_hp(query):
    identifier = str(query).upper()
    tag = 'adj_close_price'
    api_response = security_api.get_security_historical_data(identifier,
                                                             tag,
                                                             page_size=100)
    hist_prices = pd.DataFrame(api_response.historical_data_dict)
    return hist_prices


def get_intrinio_volume(query):
    identifier = str(query).upper()
    api_response = security_api.get_security_price_technicals_adtv(identifier,
                                                                   page_size=1,
                                                                   period=20)
    volume = pd.DataFrame(api_response.technicals_dict)
    return volume


def get_intrinio_wr(query):
    identifier = str(query).upper()
Beispiel #26
0
@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,
        start_date=start_date,
        end_date=end_date,
from __future__ import print_function
import time
from datetime import datetime, date, timedelta
import intrinio_sdk
from intrinio_sdk.rest import ApiException
from pprint import pprint

intrinio_sdk.ApiClient().configuration.api_key[
    'api_key'] = 'OmNhZTYyZjhlZTc4MTc5MTg5ZTMzYzg1NTYzZGJhOWZj'

security_api = intrinio_sdk.SecurityApi()

identifier = 'AAPL'  # str | A Security identifier (Ticker, FIGI, ISIN, CUSIP, Intrinio ID)
start_date = str(date.today() - timedelta(
    days=90))  # date | Get historical data on or after this date (optional)
end_date = str(date.today(
))  # date | Get historical date on or before this date (optional)
frequency = 'daily'  # str | Sort by date `asc` or `desc` (optional)
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,
        start_date=start_date,
        end_date=end_date,
        frequency=frequency)
    pprint(api_response)
except ApiException as e:
    print(
        "Exception when calling SecurityApi->get_security_historical_data: %s\n"
        % e)
Beispiel #28
0
# prep the sql call
dbname='stockmaster'
host=password_file.get('postgres',{}).get('server',{}).get(dbname,{}).get('host','')
user=password_file.get('postgres',{}).get('server',{}).get(dbname,{}).get('user','')
password=password_file.get('postgres',{}).get('server',{}).get(dbname,{}).get('password','')
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 security (US ONLY) price data for
sec_list = pd.read_sql(sql = "select distinct intrinio_id from dbo.security_list where is_current = 1 and composite_ticker like '%%:US'", con = conn, chunksize=None)

# connect to intrino
intrinio_sdk.ApiClient().configuration.api_key['api_key'] = password_file.get('intrinio', {}).get('API_sandbox','')

# a place to store errors from API CALLS
err = pd.DataFrame(columns = ['identifier', 'start_date', 'end_date', 'frequency', 'page_size', 'next_page', 'err_msg'])

# loop over the secuirties to get the proce info
for sec in sec_list.loc[:,'intrinio_id'].to_list():
    # all the dates in the table for the security // will be used to set the start date and to avoid duplicates being added into the database
    dates_in_table = pd.read_sql(sql = "select asofdate from dbo.security_price where intrinio_id = '"+sec+"'", parse_dates = ['asofdate'],con = conn).loc[:,'asofdate']
    # id comes for security list // intrinio_id
    identifier = sec
    # use the max in the database or the min in the API
    start_date = dt.datetime.strftime(dates_in_table.max() + dt.timedelta(days = 1), '%Y-%m-%d') if len(dates_in_table) != 0 else ''
    # set end date as most recent date
    end_date = dt.datetime.strftime(dt.date.today(),'%Y-%m-%d')
    # data freq --> 'daily' is the most granular
Beispiel #29
0
import intrinio_sdk
import pandas as pd

intrinio_sdk.ApiClient().configuration.api_key[
    'api_key'] = '{OjBkNDgwZTRhODgwMzgzNzU0OWI1NTM0YTA4NGNhYjI1}'
security_api = intrinio_sdk.SecurityApi()

r = security_api.get_security_stock_prices(identifier='AAPL',
                                           start_date='2000-01-01',
                                           end_date='2010-12-31',
                                           frequency='daily',
                                           page_size=10000)

response_list = [x.to_dict() for x in r.stock_prices]
df_intrinio = pd.DataFrame(response_list).sort_values('date')
df_intrinio.set_index('date', inplace=True)

df_intrinio.to_csv('/Users/chelseaw/Desktop/intrinio.csv')

fileIntrinio = open('/Users/chelseaw/Desktop/intrinio.csv')

print(fileIntrinio.read())
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)