Exemple #1
0
def collect_company_index():
    """
        This method will collect an index of all available companies.

        Args:
            None

        Returns:
            company index DataFrame
    """
    type_dict = {
        "ad": "ADR",
        "re": "REIT",
        "ce": "Closed end fund",
        "si": "Secondary Issue",
        "lp": "Limited Partnerships",
        "cs": "Common Stock",
        "et": "ETF",
        "wt": "Warrant",
        "oef": "Open Ended Fund",
        "cef": "Closed Ended Fund",
        "ps": "Preferred Stock",
        "ut": "Unit",
        "temp": "Temporary"
    }
    symbols = get_symbols(output_format='pandas')
    symbols["type_name"] = symbols["type"].apply(
        lambda x: x if x is None or x == "struct" else type_dict[x])

    return symbols
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the sensor platform."""
    from iexfinance.refdata import get_symbols
    from iexfinance.stocks import Stock

    os.environ['IEX_TOKEN'] = config.get(CONF_API_KEY)

    avail = get_symbols()

    symbols = config.get(CONF_SYMBOLS, [])

    dev = []

    for symbol in symbols:

        symbol_found = next(
            (item for item in avail if item["symbol"] == symbol[CONF_SYMBOL]),
            None)
        if symbol_found is not None:
            stock = Stock(symbol[CONF_SYMBOL])
            dev.append(IEXSensor(stock, symbol))
            _LOGGER.debug("Device created for symbol %s", symbol[CONF_SYMBOL])
        else:
            _LOGGER.warn("No sensor created for unsupported symbol %s",
                         symbol[CONF_SYMBOL])

    add_devices(dev, True)
    _LOGGER.debug("Setup completed")
Exemple #3
0
 def search_stock_name(name):
     ret = []
     f = get_symbols(output_format="json", token=API_KEY)
     for s in f:
         if name in s['name'].lower():
             ret.append(s['symbol'])
     return ret
Exemple #4
0
	def refresh_iexc_index():
		try:
			stockSymbols = get_symbols(token=os.environ["IEXC_KEY"])
			for index, stock in stockSymbols.iterrows():
				if stock["exchange"] not in TickerParserServer.exchanges:
					TickerParserServer.exchanges[stock["exchange"]] = Exchange(stock["exchange"])
				tickerId = stock["symbol"] if stock["iexId"] is None else stock["iexId"]
				TickerParserServer.iexcStocksIndex[stock["symbol"]] = {"id": tickerId, "name": stock["name"], "base": stock["symbol"], "quote": stock["currency"], "exchange": stock["exchange"]}
				TickerParserServer.exchanges[stock["exchange"]].properties.symbols.append(stock["symbol"])
			
			forexSymbols = requests.get("https://cloud.iexapis.com/stable/ref-data/fx/symbols?token={}".format(os.environ["IEXC_KEY"])).json()
			derivedCurrencies = set()
			for pair in forexSymbols["pairs"]:
				derivedCurrencies.add(pair["fromCurrency"])
				derivedCurrencies.add(pair["toCurrency"])
				TickerParserServer.iexcForexIndex[pair["symbol"]] = {"id": pair["symbol"], "name": pair["symbol"], "base": pair["fromCurrency"], "quote": pair["toCurrency"], "reversed": False}
				TickerParserServer.iexcForexIndex[pair["toCurrency"] + pair["fromCurrency"]] = {"id": pair["symbol"], "name": pair["toCurrency"] + pair["fromCurrency"], "base": pair["toCurrency"], "quote": pair["fromCurrency"], "reversed": True}
			for fromCurrency in derivedCurrencies:
				for toCurrency in derivedCurrencies:
					symbol = fromCurrency + toCurrency
					if fromCurrency != toCurrency and symbol not in TickerParserServer.iexcForexIndex:
						TickerParserServer.iexcForexIndex[symbol] = {"id": symbol, "name": symbol, "base": fromCurrency, "quote": toCurrency, "reversed": False}

			otcSymbols = requests.get("https://cloud.iexapis.com/stable/ref-data/otc/symbols?token={}".format(os.environ["IEXC_KEY"])).json()
			for stock in otcSymbols:
				if stock["exchange"] not in TickerParserServer.exchanges:
					TickerParserServer.exchanges[stock["exchange"]] = Exchange(stock["exchange"])
				tickerId = stock["symbol"] if stock["iexId"] is None else stock["iexId"]
				TickerParserServer.iexcOtcIndex[stock["symbol"]] = {"id": tickerId, "name": stock["name"], "base": stock["symbol"], "quote": stock["currency"], "exchange": stock["exchange"]}

		except Exception:
			print(traceback.format_exc())
Exemple #5
0
        def iterate_append_df(table):

            # reset to non-formated df
            tickers_df = get_symbols(output_format="pandas")

            # clear terminal window
            clear = lambda: os.system("clear")
            clear()

            with tqdm(total=int(len(tickers_df)), ncols=1) as pbar:

                # format tqdm progress bar
                pbar.set_description("Fetching iexfinance API Data")

                for i in range(0, len(tickers_df)):

                    row_values = [
                        tickers_df.loc[i][7], tickers_df.loc[i][5],
                        tickers_df.loc[i][6], tickers_df.loc[i][2],
                        tickers_df.loc[i][0]
                    ]

                    table.add_row(row_values)

                    #update tqdm progress bar
                    pbar.update(1)
def verify_api_key(api_key, api_key_path, get_references=False):
    """
    Used by get_api to ensure the key is valid
    Does this by attempting a call to get stock_references or AAPL price
    """
    try:
        if get_references:
            stock_references = get_symbols(output_format="pandas",
                                           token=api_key)
            writer = pd.ExcelWriter(api_key_path +
                                    "\\stock_references_iexcloud.xlsx")  # pylint: disable=abstract-class-instantiated
            stock_references.to_excel(writer, sheet_name="Stock References")
            writer.save()
            writer.close()
            print("[SS]-[API] Wrote stock references to api filepath.")
        else:
            verify_datetime = dt.datetime(2020, 9, 1)
            get_historical_data("AAPL",
                                verify_datetime,
                                close_only=True,
                                token=api_key)
    except Exception as e:
        print(e)
        return False
    return True
Exemple #7
0
    def get(self):
        try:
            stocks = get_symbols()

            return {'stocks': stocks}, 200
        except Exception as e:
            print('Error while retrieving list of stocks:', e, file=sys.stderr)

            return {'message': 'Error while retrieving list  of stocks'}, 500
Exemple #8
0
    def parse_symbols(self, output_format):
        all_tcks = get_symbols(output_format=output_format, token=self.token)
        return all_tcks


# all_tck = StockInfo().parse_symbols(output_format = 'json')

# with open('All_tickers.txt', 'w') as fh:
#     fh.write(json.dumps(all_tck))
Exemple #9
0
def symbol(request):
    from iexfinance.refdata import get_symbols
    symbols = get_symbols(output_format='pandas',
                          token="pk_5a6bfc8f3d3d405f910aec024cc2bc14")
    export = symbols.to_csv(r'C:\Users\James\Desktop\export_symbols.csv',
                            index=None,
                            header=True)

    return render(request, 'symbol.html', {"symbols": symbols})
Exemple #10
0
def get_us_symbols():
    all_symbols = get_symbols()
    us_symbols = []
    for symbol_dict in all_symbols:
        if symbol_dict['isEnabled'] is not True:
            continue
        if symbol_dict['region'] != 'US' or symbol_dict['currency'] != 'USD':
            continue
        us_symbols.append(symbol_dict)
    return us_symbols
def store_symbols():
    """Store IEX symbols to PyStore cache."""
    s = get_symbols()

    metadata = {
        "source": PYSTORE.datastore.name,
        "api": "refdata.get_symbols",
    }

    IEX_COLLECTION.write(_SYMBOLS, s, metadata, overwrite=True)
def load_symbols():
    """Loads in all the symbols"""
    token = ""
    with open(IEX_KEYFILE) as f:
        token = f.read().strip()

    if VERBOSE:
        print("First four of token: ", token[:4])
    SYMBOLS = get_symbols(token=token)
    return SYMBOLS
Exemple #13
0
def get_filtered_symbols(symbol_types: list) -> dict:
    format_type: str = "json"
    filtered_symbols = {}
    if symbol_types is None:
        symbol_types = ['cs', 'etf']
    supported_symbols = get_symbols(output_format=format_type)
    for symbol in supported_symbols:
        if symbol['type'] in symbol_types:
            ticker = symbol['symbol']
            filtered_symbols[ticker] = symbol
    return filtered_symbols
def seedSymbols():
    symbols = get_symbols(token=token)
    # print(len(symbols))
    # print(symbols[1])
    for value in symbols:
        # print(value)
        symbol = value['symbol']
        name = value['name']
        # print(symbol, ' ', name)
        # if symbol and name:
        # print('worked')
        company = Company(symbol, name)
        db.session.add(company)
        db.session.commit()
Exemple #15
0
def get_ticker_list(file_name):
    nyse_file = open(file_name)
    target_pairs = nyse_file.readlines()
    target_tickers = []
    available_tickers = []
    available_companies = get_symbols()
    for company in available_companies:
        if company['isEnabled'] is True:
            available_tickers.append(company['symbol'])
    for pair in target_pairs:
        if pair.split()[0] in available_tickers:
            target_tickers.append(pair.split()[0])

    return target_tickers
Exemple #16
0
    def handle(self, *args, **options):
        token = os.getenv('IEX_TOKEN')
        df = get_symbols(token=token)

        ticker_id = 1
        start_at_ticker_id = int(os.getenv('START_AT', -1))

        for i in range(len(df)):
            if ticker_id < start_at_id:
                ticker_id += 1
                continue

            print("Symbol: " + df[i]['symbol'] + "\tName: " + df[i]['name'])
            Ticker.objects.create(symbol=df[i]['symbol'],
                                  company=df[i]['name'])
Exemple #17
0
def get_tickers_IEX():
    """
    Returns a dataframe with all the tickers available in IEX Cloud.
    token is stored in environment key IEX_TOKEN as sugested by IEX. 
    In this way, it is not necessary to call os.getenv() function
    """
    iex_token = os.getenv("IEX_TOKEN")

    if type(iex_token) == str:
        print("IEX Key found successfully ...getting data")
    else:
        return "Error: IEX Key NOT found"

    tickers = pd.DataFrame(get_symbols(output_format='pandas',
                                       token=iex_token))
    return tickers
Exemple #18
0
def initialize_stocks():
    '''Clear and initialize database.'''
    # Clear db.Stocks
    db.Stocks.delete_many({})
    # Insert exchange, symbol, and name for stocks
    for s in get_symbols():
        db.Stocks.insert_one({
            StockColumn.Exchange.name: s['exchange'],
            StockColumn.Symbol.name: s['symbol'],
            StockColumn.Name.name: s['name'],
            StockColumn.Records.name: []
        })
    # Remove all with exchanges that are not Nasdaq or NYSE
    db.Stocks.delete_many({
        StockColumn.Exchange.name: {
            '$nin': [Exchange.Nasdaq.value[0], Exchange.Nyse.value[0]]
        }
    })
Exemple #19
0
rules = [
    'symbol:(.*)-|symbol:(.*)', 'name:(.*)-|name:(.*)',
    'description:(.*)-|description(.*)'
]

# Create a Rasa_NLU systiom
# Create a trainer that uses this config
trainer = Trainer(config.load("./training_data/config_spacy.yml"))
# Load the training data
training_data = load_data('./training_data/rasa_dataset_training.json')
# Create an interpreter by training the model
interpreter = trainer.train(training_data)

# mapping stocks' symbols to their names
Token = IEXTOKEN
a = get_symbols(token=Token)
symbol_map = {}
symbol_map_reverse = {}
for i in a:
    symbol_map[i['symbol']] = i['name']
    symbol_map_reverse[i['name']] = i['symbol']

# Initiate a telegram robot
bot = telebot.TeleBot(TOKEN)
apihelper.proxy = {'https': 'socks5h://127.0.0.1:1080'}
erase_all()


@bot.message_handler(commands=['start'])
def send_welcome(message):
    msg = "I'm ready for our talk"
Exemple #20
0
from typing import Any, Text, Dict, List

from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher
from rasa_sdk.events import SlotSet
from iexfinance.refdata import get_symbols
from iexfinance.stocks import Stock
# from iexfinance.stocks import get_company_name
import numpy as np
import pandas as pd
import json
import os

my_token = "sk_0811f15ee8374e6290f7bf0a5aebc83f"
stock_list = get_symbols(output_format='pandas', token="sk_0811f15ee8374e6290f7bf0a5aebc83f")['symbol'].tolist()
# company_list = get_company_name(output_format='pandas', token="sk_0811f15ee8374e6290f7bf0a5aebc83f")['companyName'].tolist()

def get_stock_price(stock_sticker):
    a = Stock(stock_sticker, token=my_token)
    return a.get_quote()['latestPrice']

#df = pd.read_json("https://api.iextrading.com/1.0/ref-data/symbols")
#df1 = df[['symbol','name']]


script_dir = os.path.dirname(__file__)
file_path = os.path.join(script_dir, './stockTickerCompany.csv')
df2 = pd.read_csv(file_path)
# original list
company_list1 = df2['name'].tolist()
# simpliefied capital list
Exemple #21
0
 def test_get_symbols(self):
     d = get_symbols()
     assert isinstance(d, pd.DataFrame)
Exemple #22
0
 def get_symbol_detail(symbol):
     f = get_symbols(output_format='json', token=API_KEY)
     for s in f:
         if s['symbol'] == symbol:
             return s
     return None
def trial2():
    df = get_symbols(output_format='pandas', token=secret_key)
    for index, row in df.iterrows():
        print(row['symbol'])
Exemple #24
0
def list_symbols():
    return [symbol['symbol'] for symbol in refdata.get_symbols()]
Exemple #25
0
def get_all_symbols():
    temp = get_symbols(output_format='pandas')
    # temp.to_excel("all available company.xlsx")
    return temp[['symbol', 'name']]
Exemple #26
0
def main():

    # prerequisits
    tickers_df = get_symbols(output_format="pandas")

    df_headers = list(tickers_df.columns.values)

    np.asarray(df_headers)

    def assemble_html_table(tickers_df):

        tickers_df = tickers_df[[
            df_headers[7],
            df_headers[5],
            df_headers[6],
            df_headers[2],
            df_headers[0],
        ]]

        # rename df column headers
        tickers_df.columns = [
            "Ticker", "Company Name", "Country", "Exchange", "Currency"
        ]

        html_table = tickers_df.to_html("tickers_table.html",
                                        classes="",
                                        border="",
                                        justify="unset")

        def modify_html():

            with open("tickers_table.html", "r") as file:
                file_data = file.read()

            targets = [
                [
                    """<table border="" class="dataframe">""",
                    """<table id="tickers-table">"""
                ],
                [
                    "<tr>",
                    """<tr class="ticker-table-tr" onclick="on(this); display_progress_bar();">"""
                ], ["<thead>", """<thead id="tickers-table-head">"""]
            ]

            # iterate and append
            for i in range(0, len(targets)):

                sub_array = targets[i]

                file_data = file_data.replace(sub_array[0], sub_array[1])

            with open("tickers_table.html", "w") as file:
                file.write(file_data)

        modify_html()

        # export html table as pdf
        pdfkit.from_file('tickers_table.html', 'tickers_table.pdf')

    assemble_html_table(tickers_df)

    def assemble_ascii_table(tickers_df):

        # format table of possible ticker symbols
        table = PrettyTable()
        table.field_names = [
            "ticker", "name", "region", "exchange", "currency"
        ]

        table.align["name"] = "l"
        table.align["ticker"] = "l"

        # iterate through tickers_df and add_rows to table referenced above
        def iterate_append_df(table):

            # reset to non-formated df
            tickers_df = get_symbols(output_format="pandas")

            # clear terminal window
            clear = lambda: os.system("clear")
            clear()

            with tqdm(total=int(len(tickers_df)), ncols=1) as pbar:

                # format tqdm progress bar
                pbar.set_description("Fetching iexfinance API Data")

                for i in range(0, len(tickers_df)):

                    row_values = [
                        tickers_df.loc[i][7], tickers_df.loc[i][5],
                        tickers_df.loc[i][6], tickers_df.loc[i][2],
                        tickers_df.loc[i][0]
                    ]

                    table.add_row(row_values)

                    #update tqdm progress bar
                    pbar.update(1)

        iterate_append_df(table)
        return table
import alpaca_trade_api as tradeapi
from iexfinance.refdata import get_symbols
import random

# Gets account.txt as a list of lists
account = open('account.txt', 'r').read().splitlines()
api = tradeapi.REST(account[0].split()[1], account[1].split()[1],
                    account[2].split()[1])

account = api.get_account()
print("$" + account.buying_power + " left in purchasing power.")

while True:
    try:
        api.submit_order(
            random.choice(get_symbols())["symbol"], 1, "buy", "market", "gtc")
        print("Order submitted.")
    except:
        print("Something went wrong.")

print("Done. Good luck!")
Exemple #28
0
def import_stocks():
    items = refdata.get_symbols()
    Stock.objects.bulk_create([
        Stock(symbol=item.get("symbol"), name=item.get("name"))
        for item in items
    ])
 def get_all_tickers(self):
     """Get all tickers from IEX."""
     print("Calling ticker data from IEX Cloud...")
     all_symbols = get_symbols(token=self.token)
     return all_symbols[["symbol", "name"]]
Exemple #30
0
 def test_get_symbols(self):
     d = get_symbols()
     assert isinstance(d, list)
     assert isinstance(d[0], dict)