def test_invalid_symbol_or_symbols(self):
     with pytest.raises(IEXSymbolError):
         a = Stock(["TSLA", "BAD SYMBOL", "BAD SYMBOL"])
         a.get_price()
Example #2
0
class TestFieldMethod(object):
    def setup_class(self):
        self.a = Stock("AAPL")
        self.b = Stock(["AAPL", "TSLA"])
        self.c = Stock("BADSYMBOL")
        self.d = Stock(["AAPL", "BADSYMBOL"])
        self.aj = Stock("AAPL", output_format="json")

    def test_get_field_single_bad_symbol(self):
        with pytest.raises(IEXQueryError):
            self.c._get_field("company", "exchange")

    def test_get_field_batch_bad_symbol(self):
        data = self.d._get_field("company", "exchange")

        assert isinstance(data, pd.DataFrame)
        assert "AAPL" in data.index

        assert "BADSYMBOL" not in data.index

    def test_get_bad_field(self):
        with pytest.raises(KeyError):
            self.a._get_field("company", "BADFIELD")

        with pytest.raises(KeyError):
            self.b._get_field("company", "BADFIELD")

        with pytest.raises(KeyError):
            self.aj._get_field("company", "BADFIELD")

    def test_get_bad_endpoint(self):
        with pytest.raises(NotImplementedError):
            self.a._get_field("BADFIELD", "NULL")

        with pytest.raises(NotImplementedError):
            self.b._get_field("BADFIELD", "NULL")

        with pytest.raises(NotImplementedError):
            self.aj._get_field("BADFIELD", "NULL")
Example #3
0
def get_now_price(msg):
    stock = Stock(msg)
    price = stock.get_price()
    return price
F:Ford Motor Company
NLLSF:Nel ASA
NOK:Nokia Corporation
VLKAF:Volkswagen AG
SNAP:Snap Inc.
IBM:International Business Machines Corporation
""".split("\n")]





while True:

    ticker = input("Enter ticker\n>  ")
    batch = Stock(ticker, token="pk_e2e1c058fb4649f8ab69035f86d2e84a")
    data = batch.get_quote()
    print(data)






sys.exit()


with open("tickers.txt", "w") as file:
    for ticker in tickers:
        file.write(ticker+"\n")
Example #5
0
class TestFieldMethods(object):
    def setup_class(self):
        self.a = Stock("AAPL")
        self.b = Stock(["AAPL", "TSLA"])

    def test_company_name(self):
        data = self.a.get_company_name()

        assert isinstance(data, str)
        assert data == "Apple, Inc."

    def test_primary_exchange(self):
        data = self.a.get_primary_exchange()

        assert isinstance(data, str)
        assert len(data) == 6

    def test_sector(self):
        data = self.a.get_sector()

        assert isinstance(data, str)
        assert len(data) == 21

    def test_open(self):
        data = self.a.get_open()

        assert isinstance(data, np.float64)

    def test_close(self):
        data = self.a.get_close()

        assert isinstance(data, np.float64)

    def test_years_high(self):
        data = self.a.get_years_high()

        assert isinstance(data, np.float64)

    def test_years_low(self):
        data = self.a.get_years_low()

        assert isinstance(data, np.float64)

    def test_ytd_change(self):
        data = self.a.get_ytd_change()

        assert isinstance(data, np.float64)

    def test_volume(self):
        data = self.a.get_volume()

        assert isinstance(data, np.int64)

    def test_market_cap(self):
        data = self.a.get_market_cap()

        assert isinstance(data, np.int64)

    def test_beta(self):
        data = self.a.get_beta()

        assert isinstance(data, np.float64)

    def test_shares_outstanding(self):
        data = self.a.get_shares_outstanding()

        assert isinstance(data, np.int64)

    def test_float(self):
        data = self.a.get_float()

        assert isinstance(data, np.int64)
Example #6
0
def stock_etf():
    return Stock("SPY", pause=3)
Example #7
0
# from iexfinance.stocks import Stock
#
# aapl = Stock("AAPL")
#
# aapl.get_price()

from iexfinance.stocks import Stock

# a = Stock("AAPL", token="sk_f280b00195434cae97cfba1993b8265c") # pk_84f41691aceb46d2b6ef5e2909f9affd
a = Stock("AAPL")  #

print(a.get_quote())
print(a.get_price())
Example #8
0
def get_stock_price(stock_sticker):
    a = Stock(stock_sticker, token=my_token)
    return a.get_quote()['latestPrice']
def get_current_stock_price(ticker):
    print(ticker)
    price = Stock(ticker)
    stockPrice = price.get_price()
    return float(stockPrice)
Example #10
0
def search_stock(symbol):
    stock = Stock(symbol, token='sk_c8589e5108e741ad8d4c98a2b003bf3b')
    company_name = stock.get_company_name()
    quote = stock.get_quote()
    price = quote['latestPrice']
    return price, company_name
def update_fig(n_clicks, input_value):
    from iexfinance.stocks import Stock
    stocks = Stock(input_value,
    token='pk_94a745eade1449549ca177ec47571a90')
    df = pd.DataFrame(stocks.get_historical_prices())

    trace_line = go.Scatter(x=list(df.index),
                                y=list(df.close),
                                #visible=False,
                                name="Close",
                                showlegend=False)

    trace_candle = go.Candlestick(x=df.index,
                           open=df.open,
                           high=df.high,
                           low=df.low,
                           close=df.close,
                           #increasing=dict(line=dict(color="#00ff00")),
                           #decreasing=dict(line=dict(color="white")),
                           visible=False,
                           showlegend=False)

    trace_bar = go.Ohlc(x=df.index,
                           open=df.open,
                           high=df.high,
                           low=df.low,
                           close=df.close,
                           #increasing=dict(line=dict(color="#888888")),
                           #decreasing=dict(line=dict(color="#888888")),
                           visible=False,
                           showlegend=False)

    data = [trace_line, trace_candle, trace_bar]

    updatemenus = list([
        dict(
            buttons=list([
                dict(
                    args=[{'visible': [True, False, False]}],
                    label='Line',
                    method='update'
                ),
                dict(
                    args=[{'visible': [False, True, False]}],
                    label='Candle',
                    method='update'
                ),
                dict(
                    args=[{'visible': [False, False, True]}],
                    label='Bar',
                    method='update'
                ),
            ]),
            direction='down',
            pad={'r': 10, 't': 10},
            showactive=True,
            x=0,
            xanchor='left',
            y=1.05,
            yanchor='top'
        ),
    ])

    layout = dict(
        title=input_value,
        updatemenus=updatemenus,
        autosize=False,
        xaxis=list(df.index)
        )

    return {
        "data": data,
        "layout": layout
    }
 def test_get_splits_params(self):
     afl = Stock("AAPL")
     data = afl.get_splits(range="1m")
     data2 = afl.get_splits(range="5y")
     assert len(data2) > len(data)
class TestShareDefault(object):
    def setup_class(self):
        self.cshare = Stock("AAPL")
        self.cshare2 = Stock("AAPL", output_format='pandas')
        self.cshare3 = Stock("SVXY")
        self.cshare4 = Stock("AAPL",
                             json_parse_int=Decimal,
                             json_parse_float=Decimal)
        self.cshare5 = Stock("GIG^")

    def test_get_endpoints(self):
        data = self.cshare.get_endpoints(["price"])
        assert list(data) == ["price"]

    def test_get_endpoints_bad_endpoint(self):
        with pytest.raises(IEXEndpointError):
            self.cshare.get_endpoints(["BAD ENDPOINT", "quote"])

        with pytest.raises(IEXEndpointError):
            self.cshare.get_endpoints("BAD ENDPOINT")

    def test_get_chart_params(self):
        data = self.cshare.get_chart()
        # Test chart ranges
        data2 = self.cshare.get_chart(range='1y')
        assert 15 < len(data) < 35
        assert 240 < len(data2) < 260

        # Test chartSimplify
        data4 = self.cshare.get_chart(chartSimplify=True)[0]
        assert "simplifyFactor" in list(data4)

        data5 = self.cshare.get_chart(range='1y', chartInterval=5)
        assert 45 < len(data5) < 55

    @pytest.mark.xfail(reason="This test only runs correctly between 00:00 and"
                       "09:30 EST")
    def test_get_chart_reset(self):
        # Test chartReset
        data3 = self.cshare.get_chart(range='1d', chartReset=True)
        assert data3 == []

    def test_get_dividends_params(self):
        data = self.cshare.get_dividends()
        data2 = self.cshare.get_dividends(range='2y')
        data3 = self.cshare.get_dividends(range='5y')
        assert len(data) < len(data2) < len(data3)

    @pytest.mark.xfail(reason="Provider error. Awaiting patch.")
    def test_get_news_params(self):
        data = self.cshare.get_news(last=15)
        assert len(data) == 15

    def test_get_quote_params(self):
        data = self.cshare.get_quote()
        data2 = self.cshare.get_quote(displayPercent=True)

        assert (abs(data2["ytdChange"]) > abs(data["ytdChange"]))

    @pytest.mark.xfail(reason="May not have splits")
    def test_get_splits_params(self):
        afl = Stock("AAPL")
        data = afl.get_splits(range="1m")
        data2 = afl.get_splits(range="5y")
        assert len(data2) > len(data)

    def test_filter(self):
        data = self.cshare.get_quote(filter_='ytdChange')
        assert isinstance(data, dict)
        assert isinstance(data["ytdChange"], (int, float))

        data4 = self.cshare4.get_quote(filter_='ytdChange')
        assert isinstance(data4, dict)
        assert isinstance(data4["ytdChange"], Decimal)
 def test_symbol_list_too_long(self):
     with pytest.raises(ValueError):
         x = ["tsla"] * 102
         Stock(x)
Example #15
0
def stock_single():
    return Stock("AAPL", pause=3)
Example #16
0
LTC_PRICE_REQ = requests.get('https://api.coinbase.com/v2/prices/LTC-USD/buy')

BTC_PRICE = BTC_PRICE_REQ.json()['data']['amount']
ETH_PRICE = ETH_PRICE_REQ.json()['data']['amount']
LTC_PRICE = LTC_PRICE_REQ.json()['data']['amount']

print('BTC: $' + BTC_PRICE \
     + ' & ETH: $' + ETH_PRICE \
     + ' & LTC: $' + LTC_PRICE)

# Grab our favorite stocks and format them to String.
# The get_price() func returns a float
# This can also be done using a list of stocks.
# e.g. batch = Stock(['TSLA', 'AAPL', 'GOOGL'])

TSLA = Stock('TSLA')
AAPL = Stock('AAPL')
GOOGL = Stock('GOOGL')

TSLA_PRICE = str(TSLA.get_price())
AAPL_PRICE = str(AAPL.get_price())
GOOGL_PRICE = str(GOOGL.get_price())

print('TESLA: $' + TSLA_PRICE \
     + ' & APPLE: $' + AAPL_PRICE \
     + ' & GOOGLE: $' + GOOGL_PRICE)

# Get today's date and format it!
# One for master and the other for individual

DATE = datetime.datetime.today()
Example #17
0
def stock_multiple():
    return Stock(["AAPL", "TSLA"], pause=3)
def speed_layer_stock_data(ticker):
    stock = Stock(ticker, output_format='json')
    return stock.get_quote()
Example #19
0
def stock_special_char():
    return Stock("GIG^", pause=3)
Example #20
0
        yfinance_df = yfinance_df.append(
            {
                'Ticker': tickers.tickers[0].ticker.upper(),
                'Name': tickers.tickers[0].info['shortName'],
                'Sector': tickers.tickers[0].info['sector'],
                'Open': tickers.tickers[0].info['open'],
                'Close': get_current_price(tickers.tickers[0]),
                'Volume': tickers.tickers[0].info['volume'],
                'SharesOutstanding':
                tickers.tickers[0].info['sharesOutstanding']
            },
            ignore_index=True)

    iexfinance_df = pandas.DataFrame([], columns=get_df_columns())
    for ticker in get_tickers():
        iex_stock_info = Stock(ticker, TOKEN=iex_token)
        iexfinance_df = iexfinance_df.append(
            {
                'Ticker': ticker.upper(),
                'Name': iex_stock_info.get_company_name(),
                'Sector': iex_stock_info.get_sector(),
                'Open': iex_stock_info.get_previous_day_prices()['open'][0],
                'Close': iex_stock_info.get_previous_day_prices()['close'][0],
                'Volume':
                iex_stock_info.get_previous_day_prices()['volume'][0],
                'SharesOutstanding': iex_stock_info.get_shares_outstanding()
            },
            ignore_index=True)

    yfinance_df.to_csv('./yfinance.csv', index=False)
    iexfinance_df.to_csv('./iexfinance.csv', index=False)
Example #21
0
from iexfinance.stocks import get_earnings_today, Stock

appl = Stock("AAPL")

print(appl.get_earnings())
Example #22
0
def _get_realtime_price(sym):
    p = Stock(sym, output_format='json').get_price()
    return float(p)
Example #23
0
 def __init__(self, stock_symbols):
     self._stock_symbols = stock_symbols
     self._iex_stock_obj = Stock(stock_symbols)
     self._company_names = self._iex_stock_obj.get_company_name()
     self._final_analysis_str = '\n\n'
def get_stock(stock_name: str, token: str):
    stock = Stock(stock_name.upper(), token=token)
    print(stock.get())
Example #25
0
 def setup_class(self):
     self.a = Stock("AAPL")
     self.b = Stock(["AAPL", "TSLA"])
Example #26
0
def receive():
    data = request.form.get('msg')
    stock = Stock(data, token='pk_63c229409ff14b67a6cc81e38927f1c4').get_quote()
    company_name = stock['companyName']
    latest_price = stock['iexRealtimePrice']
    return render_template("receive.html", c_name=company_name, l_price=latest_price)
Example #27
0
 def setup_class(self):
     self.a = Stock("AAPL")
     self.b = Stock(["AAPL", "TSLA"])
     self.c = Stock("BADSYMBOL")
     self.d = Stock(["AAPL", "BADSYMBOL"])
     self.aj = Stock("AAPL", output_format="json")
Example #28
0
def hello():
    a = Stock("AAPL", token="sk_5f01a41d887241bfb8c3675938eedfc9")
    print(os.environ)
    return "hi"
Example #29
0
 def test_stock_quote_fails_no_key(self, block_keys):
     with pytest.raises(IEXAuthenticationError):
         a = Stock("AAPL")
         a.get_quote()
 def setup_class(self):
     self.cbatch = Stock(["aapl", "tsla"])
     self.cbatch2 = Stock(["aapl", "tsla"], output_format='pandas')
     self.cbatch3 = Stock(["uvxy", "svxy"])