def profile(l_args, s_ticker):
    parser = argparse.ArgumentParser(
        add_help=False,
        prog="profile",
        description="""
            Prints information about, among other things, the industry, sector exchange and company
            description. The following fields are expected: Address, Beta, Ceo, Changes, Cik, City
            Company name, Country, Currency, Cusip, Dcf, Dcf diff, Default image, Description,
            Exchange, Exchange short name, Full time employees, Image, Industry, Ipo date, Isin,
            Last div, Mkt cap, Phone, Price, Range, Sector, State, Symbol, Vol avg, Website, Zip.
            [Source: Financial Modeling Prep]
        """,
    )

    try:
        ns_parser = parse_known_args_and_warn(parser, l_args)
        if not ns_parser:
            return

        df_fa = fa.profile(s_ticker, cfg.API_KEY_FINANCIALMODELINGPREP)
        clean_df_index(df_fa)

        print(
            df_fa.drop(index=["Description", "Image"]).to_string(header=False))
        print(f"\nImage: {df_fa.loc['Image'][0]}")
        print(f"\nDescription: {df_fa.loc['Description'][0]}")
        print("")

    except Exception as e:
        print(e)
        print("")
        return
def clean_fundamentals_df(df_fa: pd.DataFrame, num: int) -> pd.DataFrame:
    # pylint: disable=no-member
    df_fa = df_fa.set_index("fiscalDateEnding")
    df_fa = df_fa.head(n=num).T
    df_fa = df_fa.mask(df_fa.astype(object).eq(num * ["None"])).dropna()
    df_fa = df_fa.mask(df_fa.astype(object).eq(num * ["0"])).dropna()
    df_fa = df_fa.applymap(lambda x: long_number_format(x))
    clean_df_index(df_fa)
    df_fa.columns.name = "Fiscal Date Ending"
    return df_fa
예제 #3
0
def quote(other_args: List[str], ticker: str):
    """Financial Modeling Prep ticker quote

    Parameters
    ----------
    other_args : List[str]
        argparse other args
    ticker : str
        Fundamental analysis ticker symbol
    """

    parser = argparse.ArgumentParser(
        add_help=False,
        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]
        """,
    )

    try:
        ns_parser = parse_known_args_and_warn(parser, other_args)
        if not ns_parser:
            return

        df_fa = fa.quote(ticker, cfg.API_KEY_FINANCIALMODELINGPREP)

        clean_df_index(df_fa)

        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])
        # Check if there is a valid earnings announcement
        if df_fa.loc["Earnings announcement"][0]:
            earning_announcement = datetime.strptime(
                df_fa.loc["Earnings announcement"][0][0:19],
                "%Y-%m-%dT%H:%M:%S")
            df_fa.loc["Earnings announcement"][
                0] = f"{earning_announcement.date()} {earning_announcement.time()}"
        print(df_fa.to_string(header=False))
        print("")

    except Exception as e:
        print(e)
        print("")
        return
def sustainability(l_args, s_ticker):
    parser = argparse.ArgumentParser(
        add_help=False,
        prog="sust",
        description="""
            Print sustainability values of the company. The following fields are expected:
            Palmoil, Controversialweapons, Gambling, Socialscore, Nuclear, Furleather, Alcoholic,
            Gmo, Catholic, Socialpercentile, Peercount, Governancescore, Environmentpercentile,
            Animaltesting, Tobacco, Totalesg, Highestcontroversy, Esgperformance, Coal, Pesticides,
            Adult, Percentile, Peergroup, Smallarms, Environmentscore, Governancepercentile,
            Militarycontract. [Source: Yahoo Finance]
        """,
    )

    try:
        ns_parser = parse_known_args_and_warn(parser, l_args)
        if not ns_parser:
            return

        stock = yf.Ticker(s_ticker)
        pd.set_option("display.max_colwidth", None)

        df_sustainability = stock.sustainability

        if not df_sustainability:
            print(f"No sustainability information in Yahoo for {s_ticker}")
            print("")
            return

        clean_df_index(df_sustainability)

        df_sustainability = df_sustainability.rename(
            index={
                "Controversialweapons": "Controversial Weapons",
                "Socialpercentile": "Social Percentile",
                "Peercount": "Peer Count",
                "Governancescore": "Governance Score",
                "Environmentpercentile": "Environment Percentile",
                "Animaltesting": "Animal Testing",
                "Highestcontroversy": "Highest Controversy",
                "Environmentscore": "Environment Score",
                "Governancepercentile": "Governance Percentile",
                "Militarycontract": "Military Contract",
            })

        print(df_sustainability.to_string(header=False))
        print("")

    except Exception as e:
        print(e)
        print("")
        return
def clean_metrics_df(df_fa: pd.DataFrame,
                     num: int,
                     mask: bool = True) -> pd.DataFrame:
    df_fa = df_fa.iloc[:, 0:num]
    if mask:
        df_fa = df_fa.mask(df_fa.astype(object).eq(num * ["None"])).dropna()
        df_fa = df_fa.mask(df_fa.astype(object).eq(num * ["0"])).dropna()
    df_fa = df_fa.applymap(lambda x: long_number_format(x))
    clean_df_index(df_fa)
    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",
            "Net debt to e b i t d a": "Net debt to EBITDA",
            "D c f": "DCF",
            "Net income per e b t": "Net income per EBT",
        })
    return df_fa
예제 #6
0
def clean_metrics_df(df_fa: pd.DataFrame,
                     num: int,
                     mask: bool = True) -> pd.DataFrame:
    """Clean metrics data frame

    Parameters
    ----------
    df_fa : pd.DataFrame
        Metrics data frame
    num : int
        Number of columns to clean
    mask : bool, optional
        Apply mask, by default True

    Returns
    -------
    pd.DataFrame
        Cleaned metrics data frame
    """

    df_fa = df_fa.iloc[:, 0:num]
    if mask:
        df_fa = df_fa.mask(df_fa.astype(object).eq(num * ["None"])).dropna()
        df_fa = df_fa.mask(df_fa.astype(object).eq(num * ["0"])).dropna()
    df_fa = df_fa.applymap(lambda x: long_number_format(x))
    clean_df_index(df_fa)
    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",
            "Net debt to e b i t d a": "Net debt to EBITDA",
            "D c f": "DCF",
            "Net income per e b t": "Net income per EBT",
        })
    return df_fa
def overview(other_args: List[str], ticker: str):
    """Alpha Vantage stock ticker overview

    Parameters
    ----------
    other_args : List[str]
        argparse other args
    ticker : str
        Fundamental analysis ticker symbol
    """

    parser = argparse.ArgumentParser(
        add_help=False,
        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]
        """,
    )

    try:
        ns_parser = parse_known_args_and_warn(parser, other_args)
        if not ns_parser:
            return

        # Request OVERVIEW data from Alpha Vantage API
        s_req = f"https://www.alphavantage.co/query?function=OVERVIEW&symbol={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 = pd.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))
            clean_df_index(df_fa)
            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", None)

            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("")

    except Exception as e:
        print(e)
        print("")
        return
def key(other_args: List[str], ticker: str):
    """Alpha Vantage key metrics

    Parameters
    ----------
    other_args : List[str]
        argparse other args
    ticker : str
        Fundamental analysis ticker symbol
    """

    parser = argparse.ArgumentParser(
        add_help=False,
        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]
        """,
    )

    try:
        ns_parser = parse_known_args_and_warn(parser, other_args)
        if not ns_parser:
            return

        # Request OVERVIEW data
        s_req = f"https://www.alphavantage.co/query?function=OVERVIEW&symbol={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 = pd.json_normalize(result.json())
            df_fa = df_fa[list(result.json().keys())].T
            df_fa = df_fa.applymap(lambda x: long_number_format(x))
            clean_df_index(df_fa)
            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("")

    except Exception as e:
        print(e)
        print("")
        return
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]
        """,
    )

    try:
        parse_known_args_and_warn(parser, l_args)

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

        clean_df_index(df_info)

        if ("Last split date" in df_info.index
                and df_info.loc["Last split date"].values[0]):
            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)

        if "Long business summary" in df_info.index:
            print(
                df_info.drop(index=["Long business summary"]).to_string(
                    header=False))
            print("")
            print(df_info.loc["Long business summary"].values[0])
            print("")
        else:
            print(df_info.to_string(header=False))
            print("")

    except Exception as e:
        print(e)
        print("")
        return