Exemple #1
0
def main():
    # Setup client
    finnhub_client = finnhub.Client(api_key="btcplnn48v6svpql9uo0")

    # Create a client to interact with the Google Drive API
    scope = [
        'https://www.googleapis.com/auth/spreadsheets',
        'https://www.googleapis.com/auth/drive'
    ]
    creds = ServiceAccountCredentials.from_json_keyfile_name(
        'C:/Users/Abhinav/PycharmProjects/stock_api/credentials.json', scope)
    client = gspread.authorize(creds)

    # Current date time in local system
    d = str(datetime.date(datetime.now())).split("-")
    date = d[2] + " " + d[1] + " " + d[0]

    # day of the week
    born = datetime.strptime(date, '%d %m %Y').weekday()
    day = calendar.day_name[born]

    if day == "Monday":
        categories(3, 1, client, finnhub_client)
    if day == "Tuesday":
        categories(10, 1, client, finnhub_client)
    if day == "Wednesday":
        categories(17, 1, client, finnhub_client)
    if day == "Thursday":
        categories(3, 7, client, finnhub_client)
    if day == "Friday":
        categories(10, 7, client, finnhub_client)
Exemple #2
0
def Add_SymbolData(record, resolution, symbol, table_name):
    # set the start time is 60 seconds after the latest time stamp
    if record is not None:
        start_time = int(record[1]) + 60
        # Get current date as end_date
        end_time = util.convertDate_Unix(datetime.datetime.utcnow())
        # call Finnhub candle
        finnhub_client = finnhub.Client(api_key="bv4f2qn48v6qpatdiu3g")
        res = finnhub_client.stock_candles(symbol, resolution, int(start_time),
                                           int(end_time))
        time.sleep(1)
        # check if return value is no_data
        if res['s'] == 'no_data':
            print("The symbol " + symbol + " has no data")
        else:
            # remove stat column from df
            res.pop('s', None)

            df = pd.DataFrame(res)
            # insert symbol as first column in df
            df.insert(0, 'symbol', symbol, allow_duplicates=True)

            util.copyfrom_stringIO(df, table_name)
    else:
        print(symbol + "has no data")
Exemple #3
0
def stocks_view(request):
    api_key = os.getenv('API_KEY')

    finnhub_client = finnhub.Client(api_key=api_key)

    aapl = finnhub_client.quote('AAPL')['c']
    tsla = finnhub_client.quote('TSLA')['c']
    amzn = finnhub_client.quote('AMZN')['c']
    gme = finnhub_client.quote('GME')['c']
    msft = finnhub_client.quote('MSFT')['c']
    sbux = finnhub_client.quote('SBUX')['c']
    amc = finnhub_client.quote('AMC')['c']
    nflx = finnhub_client.quote('NFLX')['c']
    ba = finnhub_client.quote('BA')['c']
    prty = finnhub_client.quote('PRTY')['c']

    return render(request, "index.html", {
        'aapl': aapl,
        'tsla': tsla, 
        'amzn': amzn, 
        'gme': gme, 
        'msft': msft,
        'sbux': sbux, 
        'amc': amc, 
        'nflx': nflx, 
        'ba': ba, 
        'prty': prty
        })
Exemple #4
0
def stock_candles(api_key, symbol, start_time, end_time, resolution='D'):
    """
    get Stock candles as a dataframe from symbols using finnhub-python
    :param api_key:string
    :param start_time: timestamp int
    :param end_time: timestamp int
    :param resolution: string Supported resolution includes 1, D, W, M. Default D
    :return: candles_df as a pd.dataframe or None
    """
    import finnhub
    import pandas as pd
    import time
    import requests

    #candles_df = pd.DataFrame(columns=['c', 'h', 'l', 'o', 't', 'v', 'symbol'])
    finnhub_client = finnhub.Client(api_key=api_key)
    time.sleep(1)
    try:
        res = finnhub_client.stock_candles(symbol, resolution, start_time,
                                           end_time)
        # only put records with status in 's'
        if res.get('s') == 'ok':
            candles_df = pd.DataFrame.from_dict(res).drop(columns='s')
            # rename columns for the db table
            candles_df.columns = [
                'close', 'high', 'low', 'open', 'date', 'volume'
            ]
            candles_df['symbol'] = symbol
            candles_df['volume'] = candles_df['volume'].astype(int)
            candles_df['date'] = pd.to_datetime(candles_df['date'], unit='s')
            return candles_df

    except (requests.exceptions.RequestException, ValueError) as e:
        time.sleep(120)
        pass
def get_company_news(
    ticker: str,
    s_start: str,
    s_end: str,
) -> List[Dict]:
    """Get news from a company. [Source: Finnhub]

    Parameters
    ----------
    ticker : str
        company ticker to look for news articles
    s_start: str
        date to start searching articles, with format YYYY-MM-DD
    s_end: str
        date to end searching articles, with format YYYY-MM-DD

    Returns
    ----------
    articles : List
        term to search on the news articles
    """
    try:
        finnhub_client = finnhub.Client(api_key=cfg.API_FINNHUB_KEY)
        articles = finnhub_client.company_news(ticker.upper(),
                                               _from=s_start,
                                               to=s_end)
        return articles

    except Exception as e:
        console.print(f"[red]{e}\n[/red]")
        return [{}]
Exemple #6
0
  def get_stock_data(self, stock_name, days, period):
      '''
        Returns a dictionary of timestamps, closing prices and status response for the given stock symbol

          Parameters:
                  stock_name (string): symbol of the stock
                  days (int): Number of days to collect data for (going back from today)
                  period (string): Options are by minute: ('1' , '5', '15', '30', '60') and by day/week/month ('D', 'W', 'M')

          Returns:
                  c: List of close prices for returned candles.
                  t: List of timestamp for returned candles.
                  s: Status of the response, either 'ok' or 'no_data'.

      '''

      ## TODO: Delete imported WMA as we calculate manually below?
      current_time = calendar.timegm(time.gmtime())  # seconds since Unix epoch
      finnhub_client = finnhub.Client(api_key=self.api_key)
      res = finnhub_client.technical_indicator(symbol=stock_name, resolution=period, _from=self.x_days_ago(days),
                                              to=current_time, indicator='wma',
                                              indicator_fields={"timeperiod": 3})  # wma = weighted moving average
      if res['s'] == 'ok':
        df = pd.DataFrame.from_dict(res)
        df['t'] = pd.to_datetime(df['t'], unit='s')
        return df
      else:
          raise Exception(f'No data found for ticker = {stock_name}, days = {days}, period = {period}! Aborting StockData init')
Exemple #7
0
def connect_to_finnhub():
    try:
        finnhub_client = finnhub.Client(api_key=FINNHUB_CONFIG["FINNHUB_API"])
        return finnhub_client
    except Exception:
        error_sms()
        raise
Exemple #8
0
def get_stock_data(stock_name, days, period, finnhub_api_key):
    '''
      Returns a dictionary of timestamps, closing prices and status response for the given stock symbol

        Parameters:
                stock_name (string): symbol of the stock
                days (int): Number of days to collect data for (going back from today)
                period (string): Options are by minute: ('1' , '5', '15', '30', '60') and by day/week/month ('D', 'W', 'M')

        Returns:
                c: List of close prices for returned candles.
                t: List of timestamp for returned candles.
                s: Status of the response, either 'ok' or 'no_data'.

    '''
    current_time = calendar.timegm(time.gmtime())  # seconds since Unix epoch
    finnhub_client = finnhub.Client(api_key=finnhub_api_key)
    res = finnhub_client.technical_indicator(
        symbol=stock_name,
        resolution=period,
        _from=x_days_ago(days),
        to=current_time,
        indicator='wma',
        indicator_fields={"timeperiod": 3})  # wma = weighted moving average

    if res['s'] == 'ok':
        return res
    else:
        return 'no data found for given parameters!'
Exemple #9
0
def getStockCandles(key, symbol, resolution, start_time, end_time):
    # setup finnhub client
    finnhub_client = finnhub.Client(api_key=key)
    # retrieve stock candle
    res = finnhub_client.stock_candles(symbol, resolution, start_time,
                                       end_time)
    return res
def get_stock_info(stock, start_months):
    finnub_data = {"s": "no_data"}  # Just so the stupid error will go away
    start = int(time.time()) - (start_months * 30 * 24 * 60 * 60)
    end = int(time.time())
    finnhub_client = finnhub.Client(api_key=current_token)
    try:
        finnub_data = finnhub_client.stock_candles(symbol=stock,
                                                   resolution='D',
                                                   _from=start,
                                                   to=end)
    except Exception as e:
        try:
            exception_status = e.status_code
        except AttributeError:
            return False
        if exception_status == 429:
            change_token()
            get_stock_info(stock, start_months)
        else:
            # print(e)
            # print(exception_status)
            return False
    if finnub_data["s"] == "no_data":
        return False
    del finnub_data["s"]
    finnub_data["Close"] = finnub_data.pop("c")
    finnub_data["High"] = finnub_data.pop("h")
    finnub_data["Low"] = finnub_data.pop("l")
    finnub_data["Open"] = finnub_data.pop("o")
    finnub_data["Volume"] = finnub_data.pop("v")
    finnub_data["Time"] = finnub_data.pop("t")
    return pd.DataFrame(finnub_data)
Exemple #11
0
def get_quote(symbol):
    '''
    Return {'c': 132.05, 'h': 132.63, 'l': 130.23, 'o': 132.43, 'pc': 130.92, 't': 1610150400}
    '''
    with finnhub.Client(api_key=finnhub_token) as fc:
        res = fc.quote(symbol)
    return res
Exemple #12
0
def get_stock_history(stock,
                      start_day=None,
                      end_day=None,
                      period='D',
                      api_key='bvqgjjf48v6qg460kugg'):
    import finnhub
    import datetime
    import pandas as pd

    finhub_client = finnhub.Client(api_key=api_key)
    if end_day is None:
        end_day = int(datetime.datetime.today().timestamp())
    else:
        end_day = int(
            datetime.datetime.strptime(end_day, '%Y-%M-%d').timestamp())
    if start_day is None:
        start_day = int((datetime.datetime.today() -
                         datetime.timedelta(days=365)).timestamp())
    else:
        start_day = int(
            datetime.datetime.strptime(start_day, '%Y-%M-%d').timestamp())

    res = finhub_client.stock_candles(stock, period, start_day, end_day)

    res_pd = pd.DataFrame(res)
    res_pd.t = pd.to_datetime(res_pd.t, unit='s')
    res_pd.columns = ['close', 'high', 'low', 'open', 's', 'time', 'volume']

    return res_pd
Exemple #13
0
def get_tickers():
    """
    ## This function is for cleaning the original list of tickers. There are some items from the list that are either not legit tickers that we remove here.
    ## The last part of this function is creating a dataframe that we then use to create some additional features to help with searching.
    """

    # Setup client
    finnhub_client = finnhub.Client(api_key="c3qcjnqad3i9vt5tl68g")

    symbols_df = pd.DataFrame(finnhub_client.stock_symbols('US'))
    symbols_df_short = symbols_df[['displaySymbol', 'description']]

    ## creating a couple new columns to create a link and full searchable stock name plus ticker to help with app search.
    symbols_df_short['full'] = symbols_df_short[
        'displaySymbol'] + " - " + symbols_df_short['description']
    symbols_df_short[
        'url'] = "https://stockanalysis.com/stocks/" + symbols_df_short[
            'displaySymbol'] + "/"
    symbols_df_short = symbols_df_short.rename(columns={
        'displaySymbol': 'ticker',
        'description': 'company_name'
    })
    symbols_df_short['group'] = symbols_df_short.groupby(
        np.arange(len(symbols_df_short.index)) // (len(symbols_df_short) / 10),
        axis=0).ngroup() + 1
    symbols_df_short['full'] = symbols_df_short['full'].astype('str')
    symbols_df_short['ticker'] = symbols_df_short.ticker.str.strip()
    print("Big DataFrame Cleaned...")

    ## create csv to use for streamlit app
    symbols_df_short.to_csv(r'data/tickers_only.csv')
    print("DataFrame saved as csv :)")

    return symbols_df_short
def list_from_finnhub() -> {str: [str]}:
    api_client = fh.Client(api_key='btpvg6v48v6v5kvo1r10')
    raw_data = api_client.stock_symbols(exchange='US')
    initial_list = defaultdict(list)
    for i in raw_data:
        if i['type'] == "EQS":
            initial_list['ticker'].append(i['symbol'])
    return initial_list
def finnhub_client_setup(finnhub_client=None):
    try:
        finnhub_client = finnhub.Client(
            api_key=finnhub_api_key
        ) if finnhub_client is None else finnhub_client
        return finnhub_client
    except:
        print("Finnhub client is not setup")
Exemple #16
0
    def __init__(self):
        self.dbh = DBHandler.DBHandler('sexystonks.db')
        self.finhubClient = finnhub.Client(api_key=config('API_TOKEN'))

        self.initBalance = config('INITIAL_BALANCE')

        if (not self.dbh.checkTable('config')):
            self.dbh.initializeTables(self.initBalance)
Exemple #17
0
def get_us_symbols():
    '''
    Return df with columns of 'symbol', 'type', 'mic', 'displaySymbol', 'description', 'figi'
    '''
    with finnhub.Client(api_key=finnhub_token) as fc:
        res = fc.stock_symbols('US')
    df = pd.DataFrame(res, columns=['symbol', 'type', 'mic', 'displaySymbol', 'description', 'figi'])
    return df
Exemple #18
0
def finnhub_connection(api_key):
    try:
        finnhub_client = finnhub.Client(api_key=api_key)
        yield finnhub_client
    except Exception as e:
        logger.error(e)
        raise
    finally:
        finnhub_client.close()
Exemple #19
0
def get_split(symbol):
    '''
    Return DataFrame[symbol, date, fromFactor, toFactor]
    '''
    with finnhub.Client(api_key=finnhub_token) as fc:
        res = fc.stock_splits(symbol, '1970-01-01', '2030-01-01')
    df = pd.DataFrame(res, columns=['symbol', 'date', 'fromFactor', 'toFactor'])
    df['date'] = pd.to_datetime(df['date'])
    return df
def create_api_objects(api_key_file) -> [fh.Client]:
    """Get the API keys from the FinnhubAPIkey.txt
    and create a list of CLient objects using those keys.
    There are multiple Client objects since an
    API key can only perform 60 calls/minute."""
    api_objects = []
    for key in api_key_file:
        api_objects.append(fh.Client(api_key=key.rstrip()))
    return api_objects
Exemple #21
0
 def __init__(self):
     """
     holds all the values that we want to right to the JSON file
     """
     self.client = finnhub.Client(config.api_key)
     self.symbol = None
     self.company = None
     self.buy_or_trade = None
     self.amount = None
     self.current = None
def get_stock_quote(ticker):
    try:
        finnhub_client = finnhub.Client(api_key=constants.FINNHUBKEY)
        res = finnhub_client.quote(ticker)
        with open('out/{}_quote.csv'.format(ticker), 'a') as write_csvfile:
            writer = csv.writer(write_csvfile, dialect='excel')
            writer.writerow(res.values())
        return res
    except Exception as e:
        logging.error(e)
Exemple #23
0
def symbol_lookup():
    if request.method == 'GET':
        return render_template('symbol_lookup.html', response_data=[])
    if request.method == 'POST':
        finnhub_client = finnhub.Client(api_key="c14lb8f48v6st2753nig")
        res = finnhub_client.symbol_lookup(request.form['symbol'])
        print(res)
        response_data = dict(symbol=res['result'])
        return render_template('symbol_lookup.html',
                               response_data=response_data)
Exemple #24
0
class FinnhubConnector:
    finnhub_client = finnhub.Client(api_key='btakssf48v6vivh8r4ag')

    def __init__(self, ticker):
        self.ticker = ticker

    def get_company_financials(self, statement_type, frequency):
        company_financial = self.finnhub_client.financials(
            symbol=self.ticker, statement=statement_type, freq=frequency)

        company_financial = pd.DataFrame(company_financial['financials'])
        company_financial = company_financial[:5]
        company_financial = company_financial.dropna(axis=1, how='all')
        company_financial = company_financial.set_index('period')
        company_financial = company_financial.sort_index()
        return company_financial

    def get_economic_data(self, codename):
        codedata = self.finnhub_client.economic_data(codename)
        df = pd.DataFrame(codedata['data'])
        return df

    # ---------------------------------------------
#   COME BACK TO THIS

    def get_stock_candles(self):
        d = datetime.date(2000, 1, 1)
        d = time.mktime(d.timetuple())
        stock = self.finnhub_client.stock_candles(
            symbol=self.ticker,
            resolution='D',
            _from=d,
            to=time.mktime(datetime.date.today().timetuple()))
        stock = pd.DataFrame(stock)
        return stock

    def get_stock_quote(self):
        codedata = self.finnhub_client.quote(self.ticker)
        return codedata

    #   COME BACK TO THIS
#---------------------------------------------

    def metrics(self):
        metrics = self.finnhub_client.company_basic_financials(
            symbol=self.ticker, metric="all")
        metrics = metrics['series']
        stats = pd.read_csv("financialstatementaccounts.csv")
        stats = stats[stats['statement'] == 'bf']
        for name in stats["accountName"]:
            try:
                y = pd.DataFrame(metrics['annual'][name])
            except:
                pass
        return y
Exemple #25
0
def test():
    finnhub_client = finnhub.Client("btclgpv48v6rudshgts0")

    # symbol, period, from, to (dates as unix values)
    current_time = datetime.datetime.now()
    stock_data = finnhub_client.stock_candles('A', '60',
                                              toUnix(getPastDate(60)),
                                              toUnix(current_time))
    data = pd.DataFrame(stock_data)
    row = data.iloc[0, :]
    print(row.loc['s'] == 'ok')
Exemple #26
0
def get_stock_info(stock, token="c43om8iad3if0j0su4og"):
    # end = int(time.time())
    start_date = "07/01/2021"
    # end_date = "9/2/2021"

    start = int(time.mktime(datetime.datetime.strptime(start_date, '%d/%m/%Y').timetuple()))
    # end = int(time.mktime(datetime.datetime.strptime(end_date, '%d/%m/%Y').timetuple()))
    end = int(time.time())
    finnhub_client = finnhub.Client(api_key=token)

    return finnhub_client.stock_candles(symbol=stock, resolution='D', _from=start, to=end)
Exemple #27
0
def test_insertDataFrame():
    CH2.stevenli.HW2.DB_BestPractice.FinnhubDB_practice.drop_table()
    # Setup client
    finnhub_client = finnhub.Client(api_key="bv4f2qn48v6qpatdiu3g")

    # Stock candles
    res = finnhub_client.stock_candles('AAPL', 'D', 1590988249, 1591852249)

    # Convert to Pandas Dataframe
    import pandas as pd
    CH2.stevenli.HW2.DB_BestPractice.FinnhubDB_practice.insertDataFrameIntoTable(
        pd.DataFrame(res))
Exemple #28
0
def download_data_from_finnhub(security_symbol, interval, start_time,
                               end_time):
    api_key_finn = API_KEY_FINN["API_KEY_FINN"]
    finnhub_client = finnhub.Client(api_key=api_key_finn)
    try:
        raw_data = finnhub_client.stock_candles(security_symbol, interval,
                                                start_time, end_time)
        raw_data_df = pandas.DataFrame(data=raw_data)
        return raw_data_df
    except Exception as errors:
        print(errors, security_symbol, "api fetching failed")
        logging.error("api fetching failed", exc_info=True)
        return None
Exemple #29
0
def basic_stock_return(name_of_company):
    stonk = Stock()
    client = finnhub.Client(api_key="bssmob748v6thfcovci0")
    quote_data  = client.quote(name_of_company)
    company_profile = client.company_profile(symbol=name_of_company)
    stonk.name = company_profile["name"]
    stonk.current_price = quote_data["c"]
    stonk.open_price = quote_data["o"]
    stonk.high_price = quote_data["h"]
    stonk.low_price = quote_data["l"]
    stonk.image = company_profile["logo"]
    stonk.high_price = quote_data["h"]
    return stonk
Exemple #30
0
def extract_candles(symbol, dt_start, dt_end, resolution='D'):
    """
    Extract stack candles data through Finnhub API

    :param symbol: (str) Stack abbreviation
    :param dt_start: (datetime)
    :param dt_end: (datetime)
    :param resolution: Supported resolution includes 1, 5, 15, 30, 60, D, W, M.
    Some time frames might not be available depending on the exchange.
    :return: (DataFrame) empty dataframe if false to download
    """
    finnhub_client = finnhub.Client(api_key=FINNHUB_CONFIG["API_KEY"])
    # Download the historical daily data from Finnhub:
    try:
        res = finnhub_client.stock_candles(symbol, resolution,
                                           convert_datetime(dt_start),
                                           convert_datetime(dt_end))
        # print('api called time{}'.format(datetime.today().strftime("%H:%M:%S")))
    except Exception as e:
        print('Sorry, when extract {0} candles, because of {1}, '
              'your request cannot be finished.'.format(symbol, e.__class__))
        return pd.DataFrame()
    else:
        if res['s'] == 'no_data':
            if resolution == '1':
                return pd.DataFrame()
            else:
                print('{0} has no data returned from {1} to {2}.'.format(
                    symbol, dt_start, dt_end))
                return pd.DataFrame()
        else:
            finnhub_data = pd.DataFrame(res)
            finnhub_data["symbol"] = symbol
            # Convert the timestamp column to readable form:
            finnhub_data["t"] = finnhub_data["t"].apply(
                lambda x: datetime.fromtimestamp(x).astimezone(timezone.utc))
            # Make sure the volume column are all integers:
            finnhub_data["v"] = finnhub_data["v"].apply(lambda x: int(x))
            # Rename the columns:
            finnhub_data = finnhub_data.rename(
                {
                    'c': 'close_price',
                    'h': 'high_price',
                    'l': 'low_price',
                    'o': 'open_price',
                    's': 'status',
                    't': 'timestamp',
                    'v': 'volume'
                },
                axis=1)
            return finnhub_data