Exemplo n.º 1
0
def fundamentalData(API_key, ticker):
  from alpha_vantage.fundamentaldata import FundamentalData
  import matplotlib.pyplot as plt

  fd=FundamentalData(key=API_key, output_format='pandas')
  option=input('1. Company Overview\n2. Earnings\n3. Income Statement\n4. Balance Sheet\n5. Cash Flow\n6. Listing Status\n7. Earnings Calendar\n8. IPO calandar\n').lower()
  
  if option=='company overview' or option=='1':
    data=fd.get_company_overview(symbol=ticker)[0]
    return data

  elif option=='earnings' or option=='2':
    data=fd.get_earnings(symbol=ticker)
    return data

  elif option=='income statement' or option=='3':
    period=input("1. Annual\n2. Quaterly\n").lower()
    if period=='annual' or period=='1':
      data=fd.get_income_statement_annual(symbol=ticker)[0].T
      return data
    elif period=='quaterly' or period=='2':
      data=fd.get_income_statement_quaterly(symbol=ticker)[0].T
      return data
    else:
      print("No data available")

  elif option=='balance sheet' or option=='4':
    period=input("1. Annual\n2. Quaterly\n").lower()
    if period=='annual' or period=='1':
      data=fd.get_balance_sheet_annual(symbol=ticker)[0].T
      return data
    elif period=='quaterly' or period=='2':
      data=fd.get_balance_sheet_quaterly(symbol=ticker)[0].T
      return data
    else:
      print("No data available")

  elif option=='cash flow' or option=='5':
    period=input("1. Annual\n2. Quaterly\n").lower()
    if period=='annual' or period=='1':
      data=fd.get_cash_flow_annual(symbol=ticker)[0].T
      return data
    elif period=='quaterly' or period=='2':
      data=fd.get_cash_flow_quaterly(symbol=ticker)[0].T
      return data
    else:
      print("No data available")

  elif option=='listing status' or option=='6':
    data=fd.get_listing_status()
    return data

  elif option=='earnings calendar' or option=='7':
    data=fd.get_earnings_calendar()

  elif option=='ipo calendar' or option=='8':
    data=fd.get_ipo_calendar()

  else:
    print("CANNOT RECOGNIZE")
Exemplo n.º 2
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: Alpha Vantage]"""
    )

    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.')

    try:
        (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

        fd = FundamentalData(key=cfg.API_KEY_ALPHAVANTAGE,
                             output_format='pandas')
        if ns_parser.b_quarter:
            df_fa, d_fd_metadata = fd.get_cash_flow_quarterly(symbol=s_ticker)
        else:
            df_fa, d_fd_metadata = fd.get_cash_flow_annual(symbol=s_ticker)

        df_fa = df_fa.set_index('fiscalDateEnding')
        df_fa = df_fa.head(n=ns_parser.n_num).T
        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("")

    except:
        print("")
        return
def cash_flow(other_args: List[str], ticker: str):
    """Alpha Vantage cash flow

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

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

    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.",
    )

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

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

        fd = FundamentalData(key=cfg.API_KEY_ALPHAVANTAGE,
                             output_format="pandas")
        if ns_parser.b_quarter:
            # pylint: disable=unbalanced-tuple-unpacking
            df_fa, _ = fd.get_cash_flow_quarterly(symbol=ticker)
        else:
            # pylint: disable=unbalanced-tuple-unpacking
            df_fa, _ = fd.get_cash_flow_annual(symbol=ticker)

        df_fa = clean_fundamentals_df(df_fa, num=ns_parser.n_num)
        print(df_fa)
        print("")

    except Exception as e:
        print(e)
        print("")
        return
Exemplo n.º 4
0
def cashflow_init_annual(request):

    if request.method == 'GET':

        symbol = request.GET.get('symbol')

        data = FundamentalData(key='I7WB8M63PERU90OY', output_format='pandas')
        cashflows, vasymbol = data.get_cash_flow_annual(symbol=symbol)

        for fical in cashflows['fiscalDateEnding']:
            cashflow = cashflows[cashflows['fiscalDateEnding'] == fical]

            for col in cashflow.columns:
                if col not in ['fiscalDateEnding', 'reportedCurrency']:
                    if cashflow[col].values[0] == 'None':
                        cashflow[col] = 0.0
                    else:
                        pass
                else:
                    pass

            cash = CashFlow(
                symbol=symbol,
                report_type='annualReport',
                fiscal_date_ending=datetime.strptime(
                    cashflow['fiscalDateEnding'].values[0], '%Y-%m-%d'),
                reported_currency=cashflow['reportedCurrency'].values[0],
                investments=cashflow['investments'].values[0],
                change_in_liabilities=cashflow['changeInLiabilities'].
                values[0],
                cashflow_from_investment=cashflow['cashflowFromInvestment'].
                values[0],
                cashflow_from_financing=cashflow['cashflowFromFinancing'].
                values[0],
                other_cashflow_from_financing=cashflow[
                    'otherCashflowFromFinancing'].values[0],
                change_in_operating_activities=cashflow[
                    'changeInOperatingActivities'].values[0],
                net_income=cashflow['netIncome'].values[0],
                change_in_cash=cashflow['changeInCash'].values[0],
                operating_cashflow=cashflow['operatingCashflow'].values[0],
                other_operating_cashflow=cashflow['otherOperatingCashflow'].
                values[0],
                depreciation=cashflow['depreciation'].values[0],
                dividend_payout=cashflow['dividendPayout'].values[0],
                stock_sale_and_purchase=cashflow['stockSaleAndPurchase'].
                values[0],
                change_in_inventory=cashflow['changeInInventory'].values[0],
                change_in_account_receivables=cashflow[
                    'changeInAccountReceivables'].values[0],
                change_in_net_income=cashflow['changeInNetIncome'].values[0],
                capital_expenditures=cashflow['capitalExpenditures'].values[0],
                change_in_receivables=cashflow['changeInReceivables'].
                values[0],
                change_in_exchange_rate=cashflow['changeInExchangeRate'].
                values[0],
                change_in_cash_and_cash_equivalents=cashflow[
                    'changeInCashAndCashEquivalents'].values[0])

            cash.save()

        return JsonResponse({'message': 'Annualy Data Save successlly'},
                            status=status.HTTP_200_OK)
Exemplo n.º 5
0
def get_fraud_ratios(ticker: str) -> Tuple[Dict[str, float], float]:
    """Get fraud ratios based on fundamentals

    Parameters
    ----------
    ticker : str
        Stock ticker

    Returns
    -------
    Dict[float]:
        Dictionary of fraud metrics
    float:
        Z score for fraud metrics
    """
    fd = FundamentalData(key=cfg.API_KEY_ALPHAVANTAGE, output_format="pandas")
    # pylint: disable=unbalanced-tuple-unpacking
    # pylint: disable=no-member
    df_cf, _ = fd.get_cash_flow_annual(symbol=ticker)
    df_bs, _ = fd.get_balance_sheet_annual(symbol=ticker)
    df_is, _ = fd.get_income_statement_annual(symbol=ticker)
    df_cf = df_cf.set_index("fiscalDateEnding").iloc[:2]
    df_bs = df_bs.set_index("fiscalDateEnding").iloc[:2]
    df_is = df_is.set_index("fiscalDateEnding").iloc[:2]

    ar = df_bs["currentNetReceivables"].apply(lambda x: 0 if x else int(x)).values
    sales = df_is["totalRevenue"].apply(lambda x: 0 if x else int(x)).values
    cogs = (
        df_is["costofGoodsAndServicesSold"].apply(lambda x: 0 if x else int(x)).values
    )
    ni = df_is["netIncome"].apply(lambda x: 0 if x else int(x)).values
    ca = df_bs["totalCurrentAssets"].apply(lambda x: 0 if x else int(x)).values
    cl = df_bs["totalCurrentLiabilities"].apply(lambda x: 0 if x else int(x)).values
    ppe = df_bs["propertyPlantEquipment"].apply(lambda x: 0 if x else int(x)).values
    cash = (
        df_bs["cashAndCashEquivalentsAtCarryingValue"]
        .apply(lambda x: 0 if x else int(x))
        .values
    )
    cash_and_sec = (
        df_bs["cashAndShortTermInvestments"].apply(lambda x: 0 if x else int(x)).values
    )
    sec = [y - x for (x, y) in zip(cash, cash_and_sec)]
    ta = df_bs["totalAssets"].apply(lambda x: 0 if x else int(x)).values
    dep = (
        df_bs["accumulatedDepreciationAmortizationPPE"]
        .apply(lambda x: 0 if x else int(x))
        .values
    )
    sga = (
        df_is["sellingGeneralAndAdministrative"]
        .apply(lambda x: 0 if x else int(x))
        .values
    )
    tl = df_bs["totalLiabilities"].apply(lambda x: 0 if x else int(x)).values
    icfo = (
        df_is["netIncomeFromContinuingOperations"]
        .apply(lambda x: 0 if x else int(x))
        .values
    )
    cfo = df_cf["operatingCashflow"].apply(lambda x: 0 if x else int(x)).values
    ratios: Dict = {}
    ratios["DSRI"] = (ar[0] / sales[0]) / (ar[1] / sales[1])
    ratios["GMI"] = ((sales[1] - cogs[1]) / sales[1]) / (
        (sales[0] - cogs[0]) / sales[0]
    )
    ratios["AQI"] = (1 - ((ca[0] + ppe[0] + sec[0]) / ta[0])) / (
        1 - ((ca[1] + ppe[1] + sec[1]) / ta[1])
    )
    ratios["SGI"] = sales[0] / sales[1]
    ratios["DEPI"] = (dep[1] / (ppe[1] + dep[1])) / (dep[0] / (ppe[0] + dep[0]))
    ratios["SGAI"] = (sga[0] / sales[0]) / (sga[1] / sales[1])
    ratios["LVGI"] = (tl[0] / ta[0]) / (tl[1] / ta[1])
    ratios["TATA"] = (icfo[0] - cfo[0]) / ta[0]
    ratios["MSCORE"] = (
        -4.84
        + (0.92 * ratios["DSRI"])
        + (0.58 * ratios["GMI"])
        + (0.404 * ratios["AQI"])
        + (0.892 * ratios["SGI"])
        + (0.115 * ratios["DEPI"] - (0.172 * ratios["SGAI"]))
        + (4.679 * ratios["TATA"])
        - (0.327 * ratios["LVGI"])
    )

    zscore = (
        -4.336
        - (4.513 * (ni[0] / ta[0]))
        + (5.679 * (tl[0] / ta[0]))
        + (0.004 * (ca[0] / cl[0]))
    )

    return ratios, zscore
Exemplo n.º 6
0
def get_fraud_ratios(
    ticker: str,
) -> Tuple[Optional[Dict[str, float]], Optional[float], Optional[float]]:
    """Get fraud ratios based on fundamentals

    Parameters
    ----------
    ticker : str
        Stock ticker

    Returns
    -------
    Dict[float]:
        Dictionary of fraud metrics
    float:
        Z score for fraud metrics
    """

    try:
        fd = FundamentalData(key=cfg.API_KEY_ALPHAVANTAGE,
                             output_format="pandas")
        # pylint: disable=unbalanced-tuple-unpacking
        df_cf, _ = fd.get_cash_flow_annual(symbol=ticker)
        df_bs, _ = fd.get_balance_sheet_annual(symbol=ticker)
        df_is, _ = fd.get_income_statement_annual(symbol=ticker)

    except Exception as e:
        console.print(e)
        return None, None, None

    # pylint: disable=no-member
    df_cf = df_cf.set_index("fiscalDateEnding").iloc[:2]
    df_bs = df_bs.set_index("fiscalDateEnding").iloc[:2]
    df_is = df_is.set_index("fiscalDateEnding").iloc[:2]

    ar = df_values(df_bs, "currentNetReceivables")
    sales = df_values(df_is, "totalRevenue")
    cogs = df_values(df_is, "costofGoodsAndServicesSold")
    ni = df_values(df_is, "netIncome")
    ca = df_values(df_bs, "totalCurrentAssets")
    cl = df_values(df_bs, "totalCurrentLiabilities")
    ppe = df_values(df_bs, "propertyPlantEquipment")
    cash = df_values(df_bs, "cashAndCashEquivalentsAtCarryingValue")
    cash_and_sec = df_values(df_bs, "cashAndShortTermInvestments")
    sec = [y - x for (x, y) in zip(cash, cash_and_sec)]
    ta = df_values(df_bs, "totalAssets")
    dep = df_values(df_bs, "accumulatedDepreciationAmortizationPPE")
    sga = df_values(df_is, "sellingGeneralAndAdministrative")
    tl = df_values(df_bs, "totalLiabilities")
    icfo = df_values(df_is, "netIncomeFromContinuingOperations")
    cfo = df_values(df_cf, "operatingCashflow")

    ratios: Dict = {}
    ratios["DSRI"] = (ar[0] / sales[0]) / (ar[1] / sales[1])
    ratios["GMI"] = ((sales[1] - cogs[1]) / sales[1]) / (
        (sales[0] - cogs[0]) / sales[0])
    ratios["AQI"] = (1 - ((ca[0] + ppe[0] + sec[0]) / ta[0])) / (1 - (
        (ca[1] + ppe[1] + sec[1]) / ta[1]))
    ratios["SGI"] = sales[0] / sales[1]
    ratios["DEPI"] = (dep[1] / (ppe[1] + dep[1])) / (dep[0] /
                                                     (ppe[0] + dep[0]))
    ratios["SGAI"] = (sga[0] / sales[0]) / (sga[1] / sales[1])
    ratios["LVGI"] = (tl[0] / ta[0]) / (tl[1] / ta[1])
    ratios["TATA"] = (icfo[0] - cfo[0]) / ta[0]
    ratios["MSCORE"] = (-4.84 + (0.92 * ratios["DSRI"]) +
                        (0.58 * ratios["GMI"]) + (0.404 * ratios["AQI"]) +
                        (0.892 * ratios["SGI"]) + (0.115 * ratios["DEPI"] -
                                                   (0.172 * ratios["SGAI"])) +
                        (4.679 * ratios["TATA"]) - (0.327 * ratios["LVGI"]))

    zscore = (-4.336 - (4.513 * (ni[0] / ta[0])) + (5.679 * (tl[0] / ta[0])) +
              (0.004 * (ca[0] / cl[0])))
    v1 = np.log(ta[0] / 1000)
    v2 = ni[0] / ta[0]
    v3 = cash[0] / cl[0]

    x = ((v1 + 0.85) * v2) - 0.85
    y = 1 + v3

    mckee = x**2 / (x**2 + y**2)

    return ratios, zscore, mckee
Exemplo n.º 7
0
def fraud(other_args: List[str], ticker: str):
    """Fraud indicators for given ticker
    Parameters
    ----------
    other_args : List[str]
        argparse other args
    ticker : str
        Fundamental analysis ticker symbol
    """
    parser = argparse.ArgumentParser(
        add_help=False,
        formatter_class=argparse.RawTextHelpFormatter,
        prog="fraud",
        description=
        ("Mscore:\n------------------------------------------------\n"
         "The Beneish model is a statistical model that uses financial ratios calculated with"
         " accounting data of a specific company in order to check if it is likely (high"
         " probability) that the reported earnings of the company have been manipulated."
         " A score of -5 to -2.22 indicated a low chance of fraud, a score of -2.22 to -1.78"
         " indicates a moderate change of fraud, and a score above -1.78 indicated a high"
         " chance of fraud.[Source: Wikipedia]\n\nDSRI:\nDays Sales in Receivables Index"
         " gauges whether receivables and revenue are out of balance, a large number is"
         " expected to be associated with a higher likelihood that revenues and earnings are"
         " overstated.\n\nGMI:\nGross Margin Index shows if gross margins are deteriorating."
         " Research suggests that firms with worsening gross margin are more likely to engage"
         " in earnings management, therefore there should be a positive correlation between"
         " GMI and probability of earnings management.\n\nAQI:\nAsset Quality Index measures"
         " the proportion of assets where potential benefit is less certain. A positive"
         " relation between AQI and earnings manipulation is expected.\n\nSGI:\nSales Growth"
         " Index shows the amount of growth companies are having. Higher growth companies are"
         " more likely to commit fraud so there should be a positive relation between SGI and"
         " earnings management.\n\nDEPI:\nDepreciation Index is the ratio for the rate of"
         " depreciation. A DEPI greater than 1 shows that the depreciation rate has slowed and"
         " is positively correlated with earnings management.\n\nSGAI:\nSales General and"
         " Administrative Expenses Index measures the change in SG&A over sales. There should"
         " be a positive relationship between SGAI and earnings management.\n\nLVGI:\nLeverage"
         " Index represents change in leverage. A LVGI greater than one indicates a lower"
         " change of fraud.\n\nTATA: \nTotal Accruals to Total Assets is a proxy for the"
         " extent that cash underlies earnigns. A higher number is associated with a higher"
         " likelihood of manipulation.\n\n\n"
         "Zscore:\n------------------------------------------------\n"
         "The Zmijewski Score is a bankruptcy model used to predict a firm's bankruptcy in two"
         " years. The ratio uses in the Zmijewski score were determined by probit analysis ("
         "think of probit as probability unit). In this case, scores less than .5 represent a"
         " higher probability of default. One of the criticisms that Zmijewski made was that"
         " other bankruptcy scoring models oversampled distressed firms and favored situations"
         " with more complete data.[Source: YCharts]"),
    )

    try:
        ns_parser = parse_known_args_and_warn(parser, other_args)

        if not ns_parser:
            return

        fd = FundamentalData(key=cfg.API_KEY_ALPHAVANTAGE,
                             output_format="pandas")
        # pylint: disable=unbalanced-tuple-unpacking
        # pylint: disable=no-member
        df_cf, _ = fd.get_cash_flow_annual(symbol=ticker)
        df_bs, _ = fd.get_balance_sheet_annual(symbol=ticker)
        df_is, _ = fd.get_income_statement_annual(symbol=ticker)
        df_cf = df_cf.set_index("fiscalDateEnding").iloc[:2]
        df_bs = df_bs.set_index("fiscalDateEnding").iloc[:2]
        df_is = df_is.set_index("fiscalDateEnding").iloc[:2]

        ar = df_bs["currentNetReceivables"].apply(lambda x: int(x)).values
        sales = df_is["totalRevenue"].apply(lambda x: int(x)).values
        cogs = df_is["costofGoodsAndServicesSold"].apply(
            lambda x: int(x)).values
        ni = df_is["netIncome"].apply(lambda x: int(x)).values
        ca = df_bs["totalCurrentAssets"].apply(lambda x: int(x)).values
        cl = df_bs["totalCurrentLiabilities"].apply(lambda x: int(x)).values
        ppe = df_bs["propertyPlantEquipment"].apply(lambda x: int(x)).values
        cash = (df_bs["cashAndCashEquivalentsAtCarryingValue"].apply(
            lambda x: int(x)).values)
        cash_and_sec = (df_bs["cashAndShortTermInvestments"].apply(
            lambda x: int(x)).values)
        sec = [y - x for (x, y) in zip(cash, cash_and_sec)]
        ta = df_bs["totalAssets"].apply(lambda x: int(x)).values
        dep = (df_bs["accumulatedDepreciationAmortizationPPE"].apply(
            lambda x: int(x)).values)
        sga = df_is["sellingGeneralAndAdministrative"].apply(
            lambda x: int(x)).values
        tl = df_bs["totalLiabilities"].apply(lambda x: int(x)).values
        icfo = df_is["netIncomeFromContinuingOperations"].apply(
            lambda x: int(x)).values
        cfo = df_cf["operatingCashflow"].apply(lambda x: int(x)).values
        ratios: Dict = {}
        ratios["DSRI"] = (ar[0] / sales[0]) / (ar[1] / sales[1])
        ratios["GMI"] = ((sales[1] - cogs[1]) / sales[1]) / (
            (sales[0] - cogs[0]) / sales[0])
        ratios["AQI"] = (1 - ((ca[0] + ppe[0] + sec[0]) / ta[0])) / (1 - (
            (ca[1] + ppe[1] + sec[1]) / ta[1]))
        ratios["SGI"] = sales[0] / sales[1]
        ratios["DEPI"] = (dep[1] / (ppe[1] + dep[1])) / (dep[0] /
                                                         (ppe[0] + dep[0]))
        ratios["SGAI"] = (sga[0] / sales[0]) / (sga[1] / sales[1])
        ratios["LVGI"] = (tl[0] / ta[0]) / (tl[1] / ta[1])
        ratios["TATA"] = (icfo[0] - cfo[0]) / ta[0]
        ratios["MSCORE"] = (-4.84 + (0.92 * ratios["DSRI"]) +
                            (0.58 * ratios["GMI"]) + (0.404 * ratios["AQI"]) +
                            (0.892 * ratios["SGI"]) +
                            (0.115 * ratios["DEPI"] -
                             (0.172 * ratios["SGAI"])) +
                            (4.679 * ratios["TATA"]) -
                            (0.327 * ratios["LVGI"]))

        zscore = (-4.336 - (4.513 * (ni[0] / ta[0])) +
                  (5.679 * (tl[0] / ta[0])) + (0.004 * (ca[0] / cl[0])))

        if ratios["MSCORE"] > -1.78:
            chanceM = "high"
        elif ratios["MSCORE"] > -2.22:
            chanceM = "moderate"
        else:
            chanceM = "low"

        if zscore < 0.5:
            chanceZ = "high"
        else:
            chanceZ = "low"

        print("Mscore Sub Stats:")
        for rkey, value in ratios.items():
            if rkey != "MSCORE":
                print("  ", f"{rkey} : {value:.2f}")

        print(
            "\n" + "MSCORE: ",
            f"{ratios['MSCORE']:.2f} ({chanceM} chance of fraud)",
        )

        print("ZSCORE: ", f"{zscore:.2f} ({chanceZ} chance of bankruptcy)",
              "\n")

    except Exception as e:
        print(e, "\n")
from alpha_vantage.fundamentaldata import FundamentalData
key = 'M4JP31006H3PKZ8T'
symbol = input('Ticker : ')
period = input('Period- annual, quarterly : ')
statement = input('Statement- balance sheet, income statement, cash flow : ')
fd = FundamentalData(key,output_format = 'pandas')
if period == 'annual':
    if statement == 'balance sheet':
        state = fd.get_balance_sheet_annual(symbol)[0].T[2:]
        state.columns = list(fd.get_balance_sheet_annual(symbol)[0].T.iloc[0])
    elif statement == 'income statement':
        state = fd.get_income_statement_annual(symbol)[0].T[2:]
        state.columns = list(fd.get_income_statement_annual(symbol)[0].T.iloc[0])
    elif statement == 'cash flow':
        state = fd.get_cash_flow_annual(symbol)[0].T[2:]
        state.columns = list(fd.get_cash_flow_annual(symbol)[0].T.iloc[0])
    else:
        print("wrong input given by the user ")

elif period == 'quarterly':
    if statement == 'balance sheet':
        state = fd.get_balance_sheet_quarterly(symbol)[0].T[2:]
        state.columns = list(fd.get_balance_sheet_quarterly(symbol)[0].T.iloc[0])
    elif statement == 'income statement':
        state = fd.get_income_statement_quarterly(symbol)[0].T[2:]
        state.columns = list(fd.get_income_statement_quarterly(symbol)[0].T.iloc[0])
    elif statement == 'cash flow':
        state = fd.get_cash_flow_quarterly(symbol)[0].T[2:]
        state.columns = list(fd.get_cash_flow_quarterly(symbol)[0].T.iloc[0])
    else:
        print('Wrong Entry')