Exemple #1
0
def get_stock_current(ticker: str) -> StockCurrent:
    quote: Dict[str, Any] = http.get_json(
        f'https://api.iextrading.com/1.0/stock/{ticker}/quote')
    return StockCurrent(
        after_hours_price=quote['extendedPrice'],
        after_hours_updated_time=datetime.utcfromtimestamp(
            quote['extendedPriceTime'] / 1000),
        current_price=quote['latestPrice'],
        high=quote['high'],
        last_updated_time=datetime.utcfromtimestamp(quote['latestUpdate'] /
                                                    1000),
        low=quote['low'],
        open_=quote['open'],
        previous_close=quote['previousClose'],
        volume=quote['latestVolume'],
    )
Exemple #2
0
def get_stock_metadata(tickers):
    if len(tickers) > 100:
        raise Exception('More than 100 tickers is not supported.')

    symbols = ','.join(tickers)
    all_company_data = http.get_json(
        f'https://api.iextrading.com/1.0/stock/market/batch?symbols={symbols}&types=company,stats'
    )

    metadatas = []
    for symbol, data in all_company_data.items():
        metadatas.append(
            StockMetadata(symbol.upper(), data['company']['companyName'],
                          data['stats']['marketcap'],
                          data['company']['sector']))

    return metadatas
def get_sector_performances() -> List[SectorPerformance]:
    key_to_sector_id: Dict[str, SectorId] = {
        "Communication Services": SectorId.TELECOMMUNICATION_SERVICES,
        "Consumer Discretionary": SectorId.CONSUMER_DISCRETIONARY,
        "Consumer Staples": SectorId.CONSUMER_STAPLES,
        "Energy": SectorId.ENERGY,
        "Financials": SectorId.FINANCIALS,
        "Health Care": SectorId.HEALTH_CARE,
        "Industrials": SectorId.INDUSTRIALS,
        "Information Technology": SectorId.TECHNOLOGY,
        "Materials": SectorId.MATERIALS,
        "Real Estate": SectorId.REAL_ESTATE,
        "Utilities": SectorId.UTILITIES
    }

    key_to_time_window: Dict[str, TimeWindow] = {
        "Rank C: 5 Day Performance": TimeWindow.ONE_WEEK,
        "Rank D: 1 Month Performance": TimeWindow.ONE_MONTH,
        "Rank E: 3 Month Performance": TimeWindow.THREE_MONTHS,
        "Rank G: 1 Year Performance": TimeWindow.ONE_YEAR,
        "Rank H: 3 Year Performance": TimeWindow.THREE_YEARS,
        "Rank I: 5 Year Performance": TimeWindow.FIVE_YEARS
    }

    sector_json: Any = http.get_json(get_url('SECTOR'))

    sector_performances: List[SectorPerformance] = []
    for time_window_key in sector_json:
        if time_window_key not in key_to_time_window:
            continue

        for sector_key in sector_json[time_window_key]:
            if sector_key not in key_to_sector_id:
                continue

            sector_performances.append(
                SectorPerformance(
                    id=key_to_sector_id[sector_key],
                    time_window=key_to_time_window[time_window_key],
                    percent_change=float(
                        sector_json[time_window_key][sector_key].rstrip('%'))))

    return sector_performances
Exemple #4
0
def get_ticker_list():
    stock_array = http.get_json(
        'https://api.iextrading.com/1.0/ref-data/symbols')
    return [s['symbol'].upper() for s in stock_array if s['type'] == 'cs']
Exemple #5
0
def get_stock_dailies(tickers: List[str],
                      range_: str) -> Dict[str, List[StockDaily]]:
    """
    Gets a dictionary of ticker to list of StockDaily. If there is no data for the given ticker, then it will
    be omitted from the dictionary.
    :param range_: Supported values: '1m', '2y'
    """
    if len(tickers) > 100:
        raise Exception('More than 100 tickers is not supported.')

    symbols = ','.join(tickers)
    all_dailies = http.get_json(
        f'https://api.iextrading.com/1.0/stock/market/batch?symbols={symbols}&types=chart,quote&range={range_}'
    )

    dailies: Dict[str, List[StockDaily]] = {}
    for symbol, data in all_dailies.items():
        chart = data['chart']
        max_date = None
        dailies[symbol] = []
        for daily in chart:
            try:
                stock_daily = StockDaily(daily['date'], daily['open'],
                                         daily['high'], daily['low'],
                                         daily['close'], daily['volume'])

                max_date = stock_daily.date if not max_date else max(
                    max_date, stock_daily.date)

                if None in [
                        stock_daily.date, stock_daily.open, stock_daily.high,
                        stock_daily.low, stock_daily.close, stock_daily.volume
                ]:
                    continue

                dailies[symbol].append(stock_daily)
            except KeyError:
                # For some reason, sometimes IEX is missing some data.
                # Just skip the data for that date.
                print("Missed day of data for " + symbol)

        # Try to get the latest day from the quote if it wasn't already added
        # to the chart data.
        try:
            quote = data['quote']
            quote_datetime = datetime.utcfromtimestamp(quote['closeTime'] /
                                                       1000)
            open_datetime = datetime.utcfromtimestamp(quote['openTime'] / 1000)
            if open_datetime > quote_datetime:
                print('Open date > close date, skipping this quote')
            elif quote_datetime and max_date and quote_datetime.date(
            ) > max_date:
                formatted_date = quote_datetime.strftime('%Y-%m-%d')
                quote_daily = StockDaily(formatted_date, quote['open'],
                                         quote['high'], quote['low'],
                                         quote['close'],
                                         quote['avgTotalVolume'])

                if None in [
                        quote_daily.date, quote_daily.open, quote_daily.high,
                        quote_daily.low, quote_daily.close, quote_daily.volume
                ]:
                    raise ValueError("One of the values are None")

                dailies[symbol].append(quote_daily)
        except Exception as e:
            print("Could not parse quote for " + symbol)
            print(e)

    return dailies