Exemple #1
0
def quote(l_args, s_ticker):
    parser = argparse.ArgumentParser(prog='quote', 
                                     description="""Prints actual information about the company which is, among 
                                     other things, the day high, market cap, open and close price and price-to-equity 
                                     ratio. The following fields are expected: Avg volume, Change, Changes percentage, 
                                     Day high, Day low, Earnings announcement, Eps, Exchange, Market cap, Name, Open, 
                                     Pe, Previous close, Price, Price avg200, Price avg50, Shares outstanding, Symbol, 
                                     Timestamp, Volume, Year high, and Year low. [Source: Financial Modeling Prep]""")
    (ns_parser, l_unknown_args) = parser.parse_known_args(l_args)

    if l_unknown_args:
        print(f"The following args couldn't be interpreted: {l_unknown_args}\n")
        return

    df_fa = fa.quote(s_ticker, cfg.API_KEY_FINANCIALMODELINGPREP)
    df_fa.index = [''.join(' ' + char if char.isupper() else char.strip() for char in idx).strip() for idx in df_fa.index.tolist()]
    df_fa.index = [s_val.capitalize() for s_val in df_fa.index]
    df_fa.loc['Market cap'][0] = long_number_format(df_fa.loc['Market cap'][0])
    df_fa.loc['Shares outstanding'][0] = long_number_format(df_fa.loc['Shares outstanding'][0])
    df_fa.loc['Volume'][0] = long_number_format(df_fa.loc['Volume'][0])
    earning_announcment = datetime.datetime.strptime(df_fa.loc['Earnings announcement'][0][0:19],"%Y-%m-%dT%H:%M:%S")
    df_fa.loc['Earnings announcement'][0] = f"{earning_announcment.date()} {earning_announcment.time()}"
    print(df_fa.to_string(header=False))

    print("")
def shareholders(l_args, s_ticker):
    parser = argparse.ArgumentParser(
        prog='shrs',
        description=
        """Print Major, institutional and mutualfunds shareholders. [Source: Yahoo Finance]"""
    )

    (ns_parser, l_unknown_args) = parser.parse_known_args(l_args)

    if l_unknown_args:
        print(
            f"The following args couldn't be interpreted: {l_unknown_args}\n")
        return

    stock = yf.Ticker(s_ticker)
    pd.set_option('display.max_colwidth', -1)

    # Major holders
    print("Major holders")
    df_major_holders = stock.major_holders
    df_major_holders[1] = df_major_holders[1].apply(
        lambda x: x.replace('%', 'Percentage'))
    print(df_major_holders.to_string(index=False, header=False))
    print("")

    # Institutional holders
    print("Institutional holders")
    df_institutional_shareholders = stock.institutional_holders
    df_institutional_shareholders.columns = df_institutional_shareholders.columns.str.replace(
        '% Out', 'Stake')
    df_institutional_shareholders['Shares'] = df_institutional_shareholders[
        'Shares'].apply(lambda x: long_number_format(x))
    df_institutional_shareholders['Value'] = df_institutional_shareholders[
        'Value'].apply(lambda x: long_number_format(x))
    df_institutional_shareholders['Stake'] = df_institutional_shareholders[
        'Stake'].apply(lambda x: str("{:.2f}".format(100 * x)) + ' %')
    print(df_institutional_shareholders.to_string(index=False))
    print("")

    # Mutualfunds holders
    print("Mutualfunds holders")
    df_mutualfund_shareholders = stock.mutualfund_holders
    df_mutualfund_shareholders.columns = df_mutualfund_shareholders.columns.str.replace(
        '% Out', 'Stake')
    df_mutualfund_shareholders['Shares'] = df_mutualfund_shareholders[
        'Shares'].apply(lambda x: long_number_format(x))
    df_mutualfund_shareholders['Value'] = df_mutualfund_shareholders[
        'Value'].apply(lambda x: long_number_format(x))
    df_mutualfund_shareholders['Stake'] = df_mutualfund_shareholders[
        'Stake'].apply(lambda x: str("{:.2f}".format(100 * x)) + ' %')
    print(df_mutualfund_shareholders.to_string(index=False))

    print("")
Exemple #3
0
def enterprise(l_args, s_ticker):
    parser = argparse.ArgumentParser(prog='enterprise', 
                                     description="""Prints stock price, number of shares, market capitalization and 
                                     enterprise value over time. The following fields are expected: Add total debt, 
                                     Enterprise value, Market capitalization, Minus cash and cash equivalents, Number 
                                     of shares, Stock price, and Symbol. [Source: Financial Modeling Prep]""")

    parser.add_argument('-n', "--num", action="store", dest="n_num", type=check_positive, default=1, 
                        help='Number of latest years/quarters.')
    parser.add_argument('-q', "--quarter", action="store_true", default=False, dest="b_quarter", 
                        help='Quarter fundamental data flag.')

    (ns_parser, l_unknown_args) = parser.parse_known_args(l_args)

    if l_unknown_args:
        print(f"The following args couldn't be interpreted: {l_unknown_args}\n")
        return

    if ns_parser.n_num == 1:
        pd.set_option('display.max_colwidth', -1)
    else:
        pd.options.display.max_colwidth = 40

    if ns_parser.b_quarter:
        df_fa = fa.enterprise(s_ticker, cfg.API_KEY_FINANCIALMODELINGPREP, period='quarter')
    else:
        df_fa = fa.enterprise(s_ticker, cfg.API_KEY_FINANCIALMODELINGPREP)

    df_fa = df_fa.iloc[:, 0:ns_parser.n_num]
    df_fa = df_fa.applymap(lambda x: long_number_format(x))
    df_fa.index = [''.join(' ' + char if char.isupper() else char.strip() for char in idx).strip() for idx in df_fa.index.tolist()]
    df_fa.index = [s_val.capitalize() for s_val in df_fa.index]
    print(df_fa)

    print("")
Exemple #4
0
def discounted_cash_flow(l_args, s_ticker):
    parser = argparse.ArgumentParser(prog='dcf', 
                                     description="""Prints the discounted cash flow of a company over time including 
                                     the DCF of today. The following fields are expected: DCF, Stock price, and Date. 
                                     [Source: Financial Modeling Prep]""")
    parser.add_argument('-n', "--num", action="store", dest="n_num", type=check_positive, default=1, 
                        help='Number of latest years/quarters.')
    parser.add_argument('-q', "--quarter", action="store_true", default=False, dest="b_quarter", 
                        help='Quarter fundamental data flag.')

    (ns_parser, l_unknown_args) = parser.parse_known_args(l_args)

    if l_unknown_args:
        print(f"The following args couldn't be interpreted: {l_unknown_args}\n")
        return

    if ns_parser.n_num == 1:
        pd.set_option('display.max_colwidth', -1)
    else:
        pd.options.display.max_colwidth = 40

    if ns_parser.b_quarter:
        df_fa = fa.discounted_cash_flow(s_ticker, cfg.API_KEY_FINANCIALMODELINGPREP, period='quarter')
    else:
        df_fa = fa.discounted_cash_flow(s_ticker, cfg.API_KEY_FINANCIALMODELINGPREP)

    df_fa = df_fa.iloc[:, 0:ns_parser.n_num]
    df_fa = df_fa.applymap(lambda x: long_number_format(x))
    df_fa.index = [''.join(' ' + char if char.isupper() else char.strip() for char in idx).strip() for idx in df_fa.index.tolist()]
    df_fa.index = [s_val.capitalize() for s_val in df_fa.index]
    df_fa = df_fa.rename(index={"D c f": "DCF"})
    print(df_fa)

    print("")
def calendar_earnings(l_args, s_ticker):
    parser = argparse.ArgumentParser(
        prog='calendar_earnings',
        description=
        """Calendar earnings of the company. Including revenue and earnings estimates.
                                     [Source: Yahoo Finance]""")

    (ns_parser, l_unknown_args) = parser.parse_known_args(l_args)

    if l_unknown_args:
        print(
            f"The following args couldn't be interpreted: {l_unknown_args}\n")
        return

    stock = yf.Ticker(s_ticker)
    df_calendar = stock.calendar
    df_calendar.iloc[0, 0] = df_calendar.iloc[0, 0].date().strftime("%d/%m/%Y")
    df_calendar.iloc[:, 0] = df_calendar.iloc[:, 0].apply(
        lambda x: long_number_format(x))

    print(f"Earnings Date: {df_calendar.iloc[:, 0]['Earnings Date']}")
    print(
        f"Earnings Estimate Avg: {df_calendar.iloc[:, 0]['Earnings Average']} [{df_calendar.iloc[:, 0]['Earnings Low']}, {df_calendar.iloc[:, 0]['Earnings High']}]"
    )
    print(
        f"Revenue Estimate Avg:  {df_calendar.iloc[:, 0]['Revenue Average']} [{df_calendar.iloc[:, 0]['Revenue Low']}, {df_calendar.iloc[:, 0]['Revenue High']}]"
    )
    print("")
Exemple #6
0
def balance_sheet(l_args, s_ticker):
    parser = argparse.ArgumentParser(prog='bal', 
                                     description="""Prints a complete balance sheet statement over time. This can be 
                                     either quarterly or annually. The following fields are expected: Accepted date, 
                                     Account payables, Accumulated other comprehensive income loss, Cash and cash 
                                     equivalents, Cash and short term investments, Common stock, Deferred revenue, 
                                     Deferred revenue non current, Deferred tax liabilities non current, Filling date, 
                                     Final link, Goodwill, Goodwill and intangible assets, Intangible assets, Inventory, 
                                     Link, Long term debt, Long term investments, Net debt, Net receivables, Other assets, 
                                     Other current assets, Other current liabilities, Other liabilities, Other non current 
                                     assets, Other non current liabilities, Othertotal stockholders equity, Period, Property 
                                     plant equipment net, Retained earnings, Short term debt, Short term investments, Tax assets, 
                                     Tax payables, Total assets, Total current assets, Total current liabilities, Total debt, 
                                     Total investments, Total liabilities, Total liabilities and stockholders equity, Total 
                                     non current assets, Total non current liabilities, and Total stockholders equity. 
                                     [Source: Financial Modeling Prep]""")

    parser.add_argument('-n', "--num", action="store", dest="n_num", type=check_positive, default=1, 
                        help='Number of latest years/quarters.')
    parser.add_argument('-q', "--quarter", action="store_true", default=False, dest="b_quarter", 
                        help='Quarter fundamental data flag.')

    (ns_parser, l_unknown_args) = parser.parse_known_args(l_args)

    if l_unknown_args:
        print(f"The following args couldn't be interpreted: {l_unknown_args}\n")
        return

    if ns_parser.n_num == 1:
        pd.set_option('display.max_colwidth', -1)
    else:
        pd.options.display.max_colwidth = 40

    if ns_parser.b_quarter:
        df_fa = fa.balance_sheet_statement(s_ticker, cfg.API_KEY_FINANCIALMODELINGPREP, period='quarter')
    else:
        df_fa = fa.balance_sheet_statement(s_ticker, cfg.API_KEY_FINANCIALMODELINGPREP)

    df_fa = df_fa.iloc[:, 0:ns_parser.n_num]
    df_fa = df_fa.mask(df_fa.astype(object).eq(ns_parser.n_num*['None'])).dropna()
    df_fa = df_fa.mask(df_fa.astype(object).eq(ns_parser.n_num*['0'])).dropna()
    df_fa = df_fa.applymap(lambda x: long_number_format(x))
    df_fa.index = [''.join(' ' + char if char.isupper() else char.strip() for char in idx).strip() for idx in df_fa.index.tolist()]
    df_fa.index = [s_val.capitalize() for s_val in df_fa.index]
    df_fa.columns.name = "Fiscal Date Ending"
    print(df_fa.drop(index=['Final link', 'Link']).to_string())

    pd.set_option('display.max_colwidth', -1)
    print("")
    print(df_fa.loc['Final link'].to_frame().to_string())
    print("")
    print(df_fa.loc['Link'].to_frame().to_string())

    print("")
Exemple #7
0
def key(l_args, s_ticker):
    parser = argparse.ArgumentParser(
        prog='key',
        description=
        """Gives main key metrics about the company (it's a subset of the 
                                     Overview data from Alpha Vantage API). The following fields are expected: 
                                     Market capitalization, EBITDA, EPS, PE ratio, PEG ratio, Price to book ratio, 
                                     Return on equity TTM, Payout ratio, Price to sales ratio TTM, Dividend yield, 
                                     50 day moving average, Analyst target price, Beta [Source: Alpha Vantage API]"""
    )

    (ns_parser, l_unknown_args) = parser.parse_known_args(l_args)

    if l_unknown_args:
        print(
            f"The following args couldn't be interpreted: {l_unknown_args}\n")
        return

    # Request OVERVIEW data
    s_req = f"https://www.alphavantage.co/query?function=OVERVIEW&symbol={s_ticker}&apikey={cfg.API_KEY_ALPHAVANTAGE}"
    result = requests.get(s_req, stream=True)

    # If the returned data was successful
    if result.status_code == 200:
        df_fa = json_normalize(result.json())
        df_fa = df_fa[list(result.json().keys())].T

        df_fa = df_fa.applymap(lambda x: long_number_format(x))
        df_fa.index = [
            ''.join(' ' + char if char.isupper() else char.strip()
                    for char in idx).strip() for idx in df_fa.index.tolist()
        ]
        df_fa.index = [s_val.capitalize() for s_val in df_fa.index]
        df_fa = df_fa.rename(
            index={
                "E b i t d a": "EBITDA",
                "P e ratio": "PE ratio",
                "P e g ratio": "PEG ratio",
                "E p s": "EPS",
                "Return on equity t t m": "Return on equity TTM",
                "Price to sales ratio t t m": "Price to sales ratio TTM"
            })
        as_key_metrics = [
            "Market capitalization", "EBITDA", "EPS", "PE ratio", "PEG ratio",
            "Price to book ratio", "Return on equity TTM", "Payout ratio",
            "Price to sales ratio TTM", "Dividend yield",
            "50 day moving average", "Analyst target price", "Beta"
        ]
        print(df_fa.loc[as_key_metrics].to_string(header=False))
        print("")
    else:
        print(f"Error: {result.status_code}")

    print("")
Exemple #8
0
def financial_ratios(l_args, s_ticker):
    parser = argparse.ArgumentParser(prog='ratios', 
                                     description="""Prints in-depth ratios of a company over time. This can be either 
                                     quarterly or annually. This contains, among other things, Price-to-Book Ratio, Payout 
                                     Ratio and Operating Cycle. The following fields are expected: Asset turnover, Capital 
                                     expenditure coverage ratio, Cash conversion cycle, Cash flow coverage ratios, Cash flow 
                                     to debt ratio, Cash per share, Cash ratio, Company equity multiplier, Current ratio, 
                                     Days of inventory outstanding, Days of payables outstanding, Days of sales outstanding, 
                                     Debt equity ratio, Debt ratio, Dividend paid and capex coverage ratio, Dividend payout ratio, 
                                     Dividend yield, Ebit per revenue, Ebt per ebit, Effective tax rate, Enterprise value multiple, 
                                     Fixed asset turnover, Free cash flow operating cash flow ratio, Free cash flow per share, Gross 
                                     profit margin, Inventory turnover, Long term debt to capitalization, Net income per EBT, Net 
                                     profit margin, Operating cash flow per share, Operating cash flow sales ratio, Operating cycle, 
                                     Operating profit margin, Payables turnover, Payout ratio, Pretax profit margin, Price book value 
                                     ratio, Price cash flow ratio, Price earnings ratio, Price earnings to growth ratio, Price fair value, 
                                     Price sales ratio, Price to book ratio, Price to free cash flows ratio, Price to operating cash flows 
                                     ratio, Price to sales ratio, Quick ratio, Receivables turnover, Return on assets, Return on capital 
                                     employed, Return on equity, Short term coverage ratios, and Total debt to capitalization. 
                                     [Source: Financial Modeling Prep]""")

    parser.add_argument('-n', "--num", action="store", dest="n_num", type=check_positive, default=1, 
                        help='Number of latest years/quarters.')
    parser.add_argument('-q', "--quarter", action="store_true", default=False, dest="b_quarter", 
                        help='Quarter fundamental data flag.')

    (ns_parser, l_unknown_args) = parser.parse_known_args(l_args)

    if l_unknown_args:
        print(f"The following args couldn't be interpreted: {l_unknown_args}\n")
        return

    if ns_parser.n_num == 1:
        pd.set_option('display.max_colwidth', -1)
    else:
        pd.options.display.max_colwidth = 40

    if ns_parser.b_quarter:
        df_fa = fa.financial_ratios(s_ticker, cfg.API_KEY_FINANCIALMODELINGPREP, period='quarter')
    else:
        df_fa = fa.financial_ratios(s_ticker, cfg.API_KEY_FINANCIALMODELINGPREP)

    df_fa = df_fa.iloc[:, 0:ns_parser.n_num]
    df_fa = df_fa.mask(df_fa.astype(object).eq(ns_parser.n_num*['None'])).dropna()
    df_fa = df_fa.mask(df_fa.astype(object).eq(ns_parser.n_num*['0'])).dropna()
    df_fa = df_fa.applymap(lambda x: long_number_format(x))
    df_fa.index = [''.join(' ' + char if char.isupper() else char.strip() for char in idx).strip() for idx in df_fa.index.tolist()]
    df_fa.index = [s_val.capitalize() for s_val in df_fa.index]
    df_fa.columns.name = "Fiscal Date Ending"
    df_fa = df_fa.rename(index={"Net income per e b t": "Net income per EBT"})
    print(df_fa)

    print("")
Exemple #9
0
def key_metrics(l_args, s_ticker):
    parser = argparse.ArgumentParser(prog='metrics', 
                                     description="""Prints a list of the key metrics of a company over time. This can be either 
                                     quarterly or annually. This includes, among other things, Return on Equity (ROE), 
                                     Working Capital, Current Ratio and Debt to Assets. The following fields are expected: 
                                     Average inventory, Average payables, Average receivables, Book value per share, Capex 
                                     per share, Capex to depreciation, Capex to operating cash flow, Capex to revenue, Cash 
                                     per share, Current ratio, Days of inventory on hand, Days payables outstanding, Days sales 
                                     outstanding, Debt to assets, Debt to equity, Dividend yield, Earnings yield, Enterprise value, 
                                     Enterprise value over EBITDA, Ev to free cash flow, Ev to operating cash flow, Ev to sales, 
                                     Free cash flow per share, Free cash flow yield, Graham net net, Graham number, Income quality, 
                                     Intangibles to total assets, Interest debt per share, Inventory turnover, Market cap, Net 
                                     current asset value, Net debt to EBITDA, Net income per share, Operating cash flow per share, 
                                     Payables turnover, Payout ratio, Pb ratio, Pe ratio, Pfcf ratio, Pocfratio, Price to sales ratio, 
                                     Ptb ratio, Receivables turnover, Research and ddevelopement to revenue, Return on tangible assets, 
                                     Revenue per share, Roe, Roic, Sales general and administrative to revenue, Shareholders equity per 
                                     share, Stock based compensation to revenue, Tangible book value per share, and Working capital.
                                     [Source: Financial Modeling Prep]""")

    parser.add_argument('-n', "--num", action="store", dest="n_num", type=check_positive, default=1, 
                        help='Number of latest years/quarters.')
    parser.add_argument('-q', "--quarter", action="store_true", default=False, dest="b_quarter", 
                        help='Quarter fundamental data flag.')

    (ns_parser, l_unknown_args) = parser.parse_known_args(l_args)

    if l_unknown_args:
        print(f"The following args couldn't be interpreted: {l_unknown_args}\n")
        return

    if ns_parser.n_num == 1:
        pd.set_option('display.max_colwidth', -1)
    else:
        pd.options.display.max_colwidth = 50

    if ns_parser.b_quarter:
        df_fa = fa.key_metrics(s_ticker, cfg.API_KEY_FINANCIALMODELINGPREP, period='quarter')
    else:
        df_fa = fa.key_metrics(s_ticker, cfg.API_KEY_FINANCIALMODELINGPREP)

    df_fa = df_fa.iloc[:, 0:ns_parser.n_num]
    df_fa = df_fa.mask(df_fa.astype(object).eq(ns_parser.n_num*['None'])).dropna()
    df_fa = df_fa.mask(df_fa.astype(object).eq(ns_parser.n_num*['0'])).dropna()
    df_fa = df_fa.applymap(lambda x: long_number_format(x))
    df_fa.index = [''.join(' ' + char if char.isupper() else char.strip() for char in idx).strip() for idx in df_fa.index.tolist()]
    df_fa.index = [s_val.capitalize() for s_val in df_fa.index]
    df_fa.columns.name = "Fiscal Date Ending"
    df_fa = df_fa.rename(index={"Enterprise value over e b i t d a": "Enterprise value over EBITDA"})
    df_fa = df_fa.rename(index={"Net debt to e b i t d a": "Net debt to EBITDA"})
    print(df_fa)

    print("")
Exemple #10
0
def cash_flow(l_args, s_ticker):
    parser = argparse.ArgumentParser(prog='cash', 
                                     description="""Prints a complete cash flow statement over time. This can be either 
                                     quarterly or annually. The following fields are expected: Accepted date, Accounts payables, 
                                     Accounts receivables, Acquisitions net, Capital expenditure, Cash at beginning of period, 
                                     Cash at end of period, Change in working capital, Common stock issued, Common stock repurchased, 
                                     Debt repayment, Deferred income tax, Depreciation and amortization, Dividends paid, 
                                     Effect of forex changes on cash, Filling date, Final link, Free cash flow, Inventory, 
                                     Investments in property plant and equipment, Link, Net cash provided by operating activities, 
                                     Net cash used for investing activities, Net cash used provided by financing activities, Net 
                                     change in cash, Net income, Operating cash flow, Other financing activities, Other investing 
                                     activities, Other non cash items, Other working capital, Period, Purchases of investments, 
                                     Sales maturities of investments, Stock based compensation. [Source: Financial Modeling Prep]""")

    parser.add_argument('-n', "--num", action="store", dest="n_num", type=check_positive, default=1, 
                        help='Number of latest years/quarters.')
    parser.add_argument('-q', "--quarter", action="store_true", default=False, dest="b_quarter", 
                        help='Quarter fundamental data flag.')

    (ns_parser, l_unknown_args) = parser.parse_known_args(l_args)

    if l_unknown_args:
        print(f"The following args couldn't be interpreted: {l_unknown_args}\n")
        return

    if ns_parser.n_num == 1:
        pd.set_option('display.max_colwidth', -1)
    else:
        pd.options.display.max_colwidth = 40

    if ns_parser.b_quarter:
        df_fa = fa.cash_flow_statement(s_ticker, cfg.API_KEY_FINANCIALMODELINGPREP, period='quarter')
    else:
        df_fa = fa.cash_flow_statement(s_ticker, cfg.API_KEY_FINANCIALMODELINGPREP)

    df_fa = df_fa.iloc[:, 0:ns_parser.n_num]
    df_fa = df_fa.mask(df_fa.astype(object).eq(ns_parser.n_num*['None'])).dropna()
    df_fa = df_fa.mask(df_fa.astype(object).eq(ns_parser.n_num*['0'])).dropna()
    df_fa = df_fa.applymap(lambda x: long_number_format(x))
    df_fa.index = [''.join(' ' + char if char.isupper() else char.strip() for char in idx).strip() for idx in df_fa.index.tolist()]
    df_fa.index = [s_val.capitalize() for s_val in df_fa.index]
    df_fa.columns.name = "Fiscal Date Ending"
    print(df_fa.drop(index=['Final link', 'Link']).to_string())

    pd.set_option('display.max_colwidth', -1)
    print("")
    print(df_fa.loc['Final link'].to_frame().to_string())
    print("")
    print(df_fa.loc['Link'].to_frame().to_string())

    print("")
Exemple #11
0
def income_statement(l_args, s_ticker):
    parser = argparse.ArgumentParser(prog='inc', 
                                     description="""Prints a complete income statement over time. This can be either quarterly 
                                     or annually. The following fields are expected: Accepted date, Cost and expenses, Cost of 
                                     revenue, Depreciation and amortization, Ebitda, Ebitdaratio, Eps, Epsdiluted, Filling date, 
                                     Final link, General and administrative expenses, Gross profit, Gross profit ratio, Income 
                                     before tax, Income before tax ratio, Income tax expense, Interest expense, Link, Net income, 
                                     Net income ratio, Operating expenses, Operating income, Operating income ratio, Other expenses, 
                                     Period, Research and development expenses, Revenue, Selling and marketing expenses, Total other 
                                     income expenses net, Weighted average shs out, Weighted average shs out dil 
                                     [Source: Financial Modeling Prep]""")

    parser.add_argument('-n', "--num", action="store", dest="n_num", type=check_positive, default=1, 
                        help='Number of latest years/quarters.')
    parser.add_argument('-q', "--quarter", action="store_true", default=False, dest="b_quarter", 
                        help='Quarter fundamental data flag.')

    (ns_parser, l_unknown_args) = parser.parse_known_args(l_args)

    if l_unknown_args:
        print(f"The following args couldn't be interpreted: {l_unknown_args}\n")
        return

    if ns_parser.n_num == 1:
        pd.set_option('display.max_colwidth', -1)
    else:
        pd.options.display.max_colwidth = 40

    if ns_parser.b_quarter:
        df_fa = fa.income_statement(s_ticker, cfg.API_KEY_FINANCIALMODELINGPREP, period='quarter')
    else:
        df_fa = fa.income_statement(s_ticker, cfg.API_KEY_FINANCIALMODELINGPREP)

    df_fa = df_fa.iloc[:, 0:ns_parser.n_num]
    df_fa = df_fa.mask(df_fa.astype(object).eq(ns_parser.n_num*['None'])).dropna()
    df_fa = df_fa.mask(df_fa.astype(object).eq(ns_parser.n_num*['0'])).dropna()
    df_fa = df_fa.applymap(lambda x: long_number_format(x))
    df_fa.index = [''.join(' ' + char if char.isupper() else char.strip() for char in idx).strip() for idx in df_fa.index.tolist()]
    df_fa.index = [s_val.capitalize() for s_val in df_fa.index]
    df_fa.columns.name = "Fiscal Date Ending"
    print(df_fa.drop(index=['Final link', 'Link']).to_string())

    pd.set_option('display.max_colwidth', -1)
    print("")
    print(df_fa.loc['Final link'].to_frame().to_string())
    print("")
    print(df_fa.loc['Link'].to_frame().to_string())

    print("")
Exemple #12
0
def financial_statement_growth(l_args, s_ticker):
    parser = argparse.ArgumentParser(prog='growth', 
                                     description="""Prints the growth of several financial statement items and ratios over time. This can be
                                     either annually and quarterly. These are, among other things, Revenue Growth (3, 5 and 10 years), 
                                     inventory growth and operating cash flow growth (3, 5 and 10 years). The following fields 
                                     are expected: Asset growth, Book valueper share growth, Debt growth, Dividendsper share growth, 
                                     Ebitgrowth, Epsdiluted growth, Epsgrowth, Five y dividendper share growth per share, Five y net 
                                     income growth per share, Five y operating c f growth per share, Five y revenue growth per share, 
                                     Five y shareholders equity growth per share, Free cash flow growth, Gross profit growth, Inventory 
                                     growth, Net income growth, Operating cash flow growth, Operating income growth, Rdexpense growth, 
                                     Receivables growth, Revenue growth, Sgaexpenses growth, Ten y dividendper share growth per share, 
                                     Ten y net income growth per share, Ten y operating c f growth per share, Ten y revenue growth per 
                                     share, Ten y shareholders equity growth per share, Three y dividendper share growth per share, 
                                     Three y net income growth per share, Three y operating c f growth per share, Three y revenue growth 
                                     per share, Three y shareholders equity growth per share, Weighted average shares diluted growth, 
                                     and Weighted average shares growth [Source: Financial Modeling Prep]""")

    parser.add_argument('-n', "--num", action="store", dest="n_num", type=check_positive, default=1, 
                        help='Number of latest years/quarters.')
    parser.add_argument('-q', "--quarter", action="store_true", default=False, dest="b_quarter", 
                        help='Quarter fundamental data flag.')

    (ns_parser, l_unknown_args) = parser.parse_known_args(l_args)

    if l_unknown_args:
        print(f"The following args couldn't be interpreted: {l_unknown_args}\n")
        return

    if ns_parser.n_num == 1:
        pd.set_option('display.max_colwidth', -1)
    else:
        pd.options.display.max_colwidth = 50

    if ns_parser.b_quarter:
        df_fa = fa.financial_statement_growth(s_ticker, cfg.API_KEY_FINANCIALMODELINGPREP, period='quarter')
    else:
        df_fa = fa.financial_statement_growth(s_ticker, cfg.API_KEY_FINANCIALMODELINGPREP)

    df_fa = df_fa.iloc[:, 0:ns_parser.n_num]
    df_fa = df_fa.mask(df_fa.astype(object).eq(ns_parser.n_num*['None'])).dropna()
    df_fa = df_fa.mask(df_fa.astype(object).eq(ns_parser.n_num*['0'])).dropna()
    df_fa = df_fa.applymap(lambda x: long_number_format(x))
    df_fa.index = [''.join(' ' + char if char.isupper() else char.strip() for char in idx).strip() for idx in df_fa.index.tolist()]
    df_fa.index = [s_val.capitalize() for s_val in df_fa.index]
    df_fa.columns.name = "Fiscal Date Ending"
    print(df_fa)

    print("")
def info(l_args, s_ticker):
    parser = argparse.ArgumentParser(
        prog='info',
        description=
        """Print information about the company. The following fields are expected: 
                                     Zip, Sector, Full time employees, Long business summary, City, Phone, State, Country, 
                                     Website, Max age, Address, Industry, Previous close, Regular market open, Two hundred 
                                     day average, Payout ratio, Regular market day high, Average daily volume 10 day, 
                                     Regular market previous close, Fifty day average, Open, Average volume 10 days, Beta, 
                                     Regular market day low, Price hint, Currency, Trailing PE, Regular market volume, 
                                     Market cap, Average volume, Price to sales trailing 12 months, Day low, Ask, Ask size, 
                                     Volume, Fifty two week high, Forward PE, Fifty two week low, Bid, Tradeable, Bid size, 
                                     Day high, Exchange, Short name, Long name, Exchange timezone name, Exchange timezone 
                                     short name, Is esg populated, Gmt off set milliseconds, Quote type, Symbol, Message board id, 
                                     Market, Enterprise to revenue, Profit margins, Enterprise to ebitda, 52 week change, 
                                     Forward EPS, Shares outstanding, Book value, Shares short, Shares percent shares out, 
                                     Last fiscal year end, Held percent institutions, Net income to common, Trailing EPS, 
                                     Sand p52 week change, Price to book, Held percent insiders, Next fiscal year end, 
                                     Most recent quarter, Short ratio, Shares short previous month date, Float shares, 
                                     Enterprise value, Last split date, Last split factor, Earnings quarterly growth, 
                                     Date short interest, PEG ratio, Short percent of float, Shares short prior month, 
                                     Regular market price, Logo_url. [Source: Yahoo Finance]"""
    )

    (ns_parser, l_unknown_args) = parser.parse_known_args(l_args)

    if l_unknown_args:
        print(
            f"The following args couldn't be interpreted: {l_unknown_args}\n")
        return

    stock = yf.Ticker(s_ticker)
    df_info = pd.DataFrame(stock.info.items(), columns=['Metric', 'Value'])
    df_info = df_info.set_index('Metric')

    df_info.index = [
        ''.join(' ' + char if char.isupper() else char.strip()
                for char in idx).strip() for idx in df_info.index.tolist()
    ]
    df_info.index = [s_val.capitalize() for s_val in df_info.index]

    df_info.loc['Last split date'].values[0] = datetime.fromtimestamp(
        df_info.loc['Last split date'].values[0]).strftime('%d/%m/%Y')

    df_info = df_info.mask(df_info['Value'].astype(str).eq('[]')).dropna()
    df_info = df_info.applymap(lambda x: long_number_format(x))

    df_info = df_info.rename(
        index={
            "Address1": "Address",
            "Average daily volume10 day": "Average daily volume 10 day",
            "Average volume10days": "Average volume 10 days",
            "Price to sales trailing12 months":
            "Price to sales trailing 12 months"
        })
    df_info.index = df_info.index.str.replace('eps', 'EPS')
    df_info.index = df_info.index.str.replace('p e', 'PE')
    df_info.index = df_info.index.str.replace('Peg', 'PEG')

    pd.set_option('display.max_colwidth', -1)
    print(
        df_info.drop(index=['Long business summary']).to_string(header=False))
    print("")
    print(df_info.loc['Long business summary'].values[0])
    print("")
Exemple #14
0
def overview(l_args, s_ticker):
    parser = argparse.ArgumentParser(
        prog='overview',
        description=
        """Prints an overview about the company. The following fields are expected: 
                                     Symbol, Asset type, Name, Description, Exchange, Currency, Country, Sector, Industry, 
                                     Address, Full time employees, Fiscal year end, Latest quarter, Market capitalization, 
                                     EBITDA, PE ratio, PEG ratio, Book value, Dividend per share, Dividend yield, EPS, 
                                     Revenue per share TTM, Profit margin, Operating margin TTM, Return on assets TTM, 
                                     Return on equity TTM, Revenue TTM, Gross profit TTM, Diluted EPS TTM, Quarterly earnings growth YOY, 
                                     Quarterly revenue growth YOY, Analyst target price, Trailing PE, Forward PE, 
                                     Price to sales ratio TTM, Price to book ratio, EV to revenue, EV to EBITDA, Beta, 52 week high, 
                                     52 week low, 50 day moving average, 200 day moving average, Shares outstanding, Shares float, 
                                     Shares short, Shares short prior month, Short ratio, Short percent outstanding, Short percent float, 
                                     Percent insiders, Percent institutions, Forward annual dividend rate, Forward annual dividend yield, 
                                     Payout ratio, Dividend date, Ex dividend date, Last split factor, and Last split date. 
                                     [Source: Alpha Vantage]""")

    (ns_parser, l_unknown_args) = parser.parse_known_args(l_args)

    if l_unknown_args:
        print(
            f"The following args couldn't be interpreted: {l_unknown_args}\n")
        return

    # Request OVERVIEW data from Alpha Vantage API
    s_req = f"https://www.alphavantage.co/query?function=OVERVIEW&symbol={s_ticker}&apikey={cfg.API_KEY_ALPHAVANTAGE}"
    result = requests.get(s_req, stream=True)

    # If the returned data was successful
    if result.status_code == 200:
        # Parse json data to dataframe
        df_fa = json_normalize(result.json())
        # Keep json data sorting in dataframe
        df_fa = df_fa[list(result.json().keys())].T
        df_fa = df_fa.applymap(lambda x: long_number_format(x))
        df_fa.index = [
            ''.join(' ' + char if char.isupper() else char.strip()
                    for char in idx).strip() for idx in df_fa.index.tolist()
        ]
        df_fa.index = [s_val.capitalize() for s_val in df_fa.index]
        df_fa = df_fa.rename(
            index={
                "E b i t d a": "EBITDA",
                "P e ratio": "PE ratio",
                "P e g ratio": "PEG ratio",
                "E p s": "EPS",
                "Revenue per share t t m": "Revenue per share TTM",
                "Operating margin t t m": "Operating margin TTM",
                "Return on assets t t m": "Return on assets TTM",
                "Return on equity t t m": "Return on equity TTM",
                "Revenue t t m": "Revenue TTM",
                "Gross profit t t m": "Gross profit TTM",
                "Diluted e p s t t m": "Diluted EPS TTM",
                "Quarterly earnings growth y o y":
                "Quarterly earnings growth YOY",
                "Quarterly revenue growth y o y":
                "Quarterly revenue growth YOY",
                "Trailing p e": "Trailing PE",
                "Forward p e": "Forward PE",
                "Price to sales ratio t t m": "Price to sales ratio TTM",
                "E v to revenue": "EV to revenue",
                "E v to e b i t d a": "EV to EBITDA",
            })

        pd.set_option('display.max_colwidth', -1)

        print(df_fa.drop(index=['Description']).to_string(header=False))
        print(f"Description: {df_fa.loc['Description'][0]}")
        print("")
    else:
        print(f"Error: {result.status_code}")
    print("")
Exemple #15
0
def short_interest(l_args, s_ticker, s_start):
    parser = argparse.ArgumentParser(
        prog='short',
        description=
        """Plots the short interest of a stock. This corresponds to the number of shares that
                                     have been sold short but have not yet been covered or closed out. Either NASDAQ or NYSE [Source: Quandl]"""
    )

    parser.add_argument('-n',
                        "--nyse",
                        action="store_true",
                        default=False,
                        dest="b_nyse",
                        help='data from NYSE flag.')
    parser.add_argument('-d',
                        "--days",
                        action="store",
                        dest="n_days",
                        type=check_positive,
                        default=10,
                        help='number of latest days to print data.')

    (ns_parser, l_unknown_args) = parser.parse_known_args(l_args)

    if l_unknown_args:
        print(
            f"The following args couldn't be interpreted: {l_unknown_args}\n")
        return

    quandl.ApiConfig.api_key = cfg.API_KEY_QUANDL

    if ns_parser.b_nyse:
        df_short_interest = quandl.get(f"FINRA/FNYX_{s_ticker}")
    else:
        df_short_interest = quandl.get(f"FINRA/FNSQ_{s_ticker}")

    df_short_interest = df_short_interest[s_start:]
    df_short_interest.columns = [
        ''.join(' ' + char if char.isupper() else char.strip()
                for char in idx).strip()
        for idx in df_short_interest.columns.tolist()
    ]
    df_short_interest['% of Volume Shorted'] = round(
        100 * df_short_interest['Short Volume'] /
        df_short_interest['Total Volume'], 2)

    fig, ax = plt.subplots()
    ax.bar(df_short_interest.index,
           df_short_interest['Short Volume'],
           0.3,
           color='r')
    ax.bar(df_short_interest.index,
           df_short_interest['Total Volume'] -
           df_short_interest['Short Volume'],
           0.3,
           bottom=df_short_interest['Short Volume'],
           color='b')
    ax.set_ylabel('Shares')
    ax.set_xlabel('Date')

    if s_start:
        ax.set_title(
            f"{('NASDAQ', 'NYSE')[ns_parser.b_nyse]} Short Interest on {s_ticker} from {s_start.date()}"
        )
    else:
        ax.set_title(
            f"{('NASDAQ', 'NYSE')[ns_parser.b_nyse]} Short Interest on {s_ticker}"
        )

    ax.legend(labels=['Short Volume', 'Total Volume'])
    ax.tick_params(axis='both', which='major')
    ax.yaxis.set_major_formatter(ticker.EngFormatter())
    ax_twin = ax.twinx()
    ax_twin.tick_params(axis='y', colors='green')
    ax_twin.set_ylabel('Percentage of Volume Shorted', color='green')
    ax_twin.plot(df_short_interest.index,
                 df_short_interest['% of Volume Shorted'],
                 color='green')
    ax_twin.tick_params(axis='y', which='major', color='green')
    ax_twin.yaxis.set_major_formatter(ticker.FormatStrFormatter('%.0f%%'))
    plt.xlim([df_short_interest.index[0], df_short_interest.index[-1]])

    df_short_interest['% of Volume Shorted'] = df_short_interest[
        '% of Volume Shorted'].apply(lambda x: f'{x/100:.2%}')
    df_short_interest = df_short_interest.applymap(
        lambda x: long_number_format(x)).sort_index(ascending=False)

    pd.set_option('display.max_colwidth', 70)
    print(df_short_interest.head(n=ns_parser.n_days).to_string())
    print("")

    plt.show()