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")
def get_data(console, ticker, ror): #This function returns the following details when given a stock ticker/symbol: #Earnings per Share, Equity Growth, P/E Ratio console.print('Fetching data...', style="blue") fd = FundamentalData(key=api_key) data = { "function": "OVERVIEW", "symbol": ticker, "outputsize": "compact", "datatype": "json", "apikey": api_key, } #Get Balance Sheet data of past five years bs_data, meta = fd.get_balance_sheet_annual(ticker) latest_equity = bs_data['totalShareholderEquity'][0] oldest_equity = bs_data['totalShareholderEquity'][4] #Calculating equity growth over five years eq_gr = calculate_equity_growth(latest_equity, oldest_equity, 5) #Get TTM EPS & PE Ratio response = requests.get(API_URL, data) co_data = response.json() eps = co_data['EPS'] per = co_data['PERatio'] #Get Company Details company_name = co_data['Name'] company_country = co_data['Country'] company_industry = co_data['Industry'] company_sector = co_data['Sector'] company_exchange = co_data['Exchange'] trading_price = get_price(ticker) calculated_data = calculate_fair_value(console, ticker, eps, eq_gr, per, ror, 5) company_data = { 'company_name': company_name, 'company_country': company_country, 'company_industry': company_industry, 'company_sector': company_sector, 'company_exchange': company_exchange, 'eps': eps, 'eq_gr': eq_gr, 'per': per, 'trading_price': trading_price, 'calculated_data': calculated_data } console.print('Data Fetched!', style="green bold") return company_data
def get_dupont(ticker: str) -> pd.DataFrame: """Get dupont ratios Parameters ---------- ticker : str Stock ticker Returns ------- dupont : pd.DataFrame The dupont ratio breakdown """ try: fd = FundamentalData(key=cfg.API_KEY_ALPHAVANTAGE, output_format="pandas") # pylint: disable=unbalanced-tuple-unpacking 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 pd.DataFrame() # pylint: disable=no-member df_bs = df_bs.set_index("fiscalDateEnding") df_is = df_is.set_index("fiscalDateEnding") dupont_years = pd.DataFrame() for i in range(len(df_bs)): ni = df_values(df_is, "netIncome", i, 1) pretax = df_values(df_is, "incomeBeforeTax", i, 1) ebit = df_values(df_is, "ebit", i, 1) sales = df_values(df_is, "totalRevenue", i, 1) assets = df_values(df_bs, "totalAssets", i, 1) equity = df_values(df_bs, "totalShareholderEquity", i, 1) ratios: Dict = {} try: ratios["Tax Burden"] = clean_fraction(ni[0], pretax[0]) ratios["Interest Burden"] = clean_fraction(pretax[0], ebit[0]) ratios["EBIT Margin"] = clean_fraction(ebit[0], sales[0]) ratios["Asset Turnover"] = clean_fraction(sales[0], assets[0]) ratios["Finance Leverage"] = clean_fraction(assets[0], equity[0]) ratios["ROI"] = clean_fraction(ni[0], equity[0]) except IndexError: pass if dupont_years.empty: dupont_years.index = ratios.keys() dupont_years[df_bs.index[i]] = ratios.values() dupont_years = dupont_years[sorted(dupont_years)] return dupont_years
def balance_sheet(l_args, s_ticker): parser = argparse.ArgumentParser( prog='balance', 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: 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_balance_sheet_quarterly( symbol=s_ticker) else: df_fa, d_fd_metadata = fd.get_balance_sheet_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 balancesheet_init_annual(request): if request.method == 'GET': symbol = request.GET.get('symbol') data = FundamentalData(key='I7WB8M63PERU90OY', output_format='pandas') balancesheets, vasymbol = data.get_balance_sheet_annual(symbol=symbol) for fical in balancesheets['fiscalDateEnding']: balancesheet = balancesheets[balancesheets['fiscalDateEnding'] == fical] for col in balancesheet.columns: if col not in ['fiscalDateEnding', 'reportedCurrency']: if balancesheet[col].values[0] == 'None': balancesheet[col] = 0.0 else: pass else: pass bs = BalanceSheet( symbol=symbol, report_type='annualReport', fiscal_date_ending=datetime.strptime( balancesheet['fiscalDateEnding'].values[0], '%Y-%m-%d'), reported_currency=balancesheet['reportedCurrency'].values[0], total_assets=balancesheet['totalAssets'].values[0], intangible_assets=balancesheet['intangibleAssets'].values[0], earning_assets=balancesheet['earningAssets'].values[0], other_current_assets=balancesheet['otherCurrentAssets']. values[0], total_liabilities=balancesheet['totalLiabilities'].values[0], total_shareholder_equity=balancesheet['totalShareholderEquity'] .values[0], deferred_long_term_liabilities=balancesheet[ 'deferredLongTermLiabilities'].values[0], other_current_liabilities=balancesheet[ 'otherCurrentLiabilities'].values[0], common_stock=balancesheet['commonStock'].values[0], retained_earnings=balancesheet['retainedEarnings'].values[0], other_liabilities=balancesheet['otherLiabilities'].values[0], goodwill=balancesheet['goodwill'].values[0], other_assets=balancesheet['otherAssets'].values[0], cash=balancesheet['cash'].values[0], total_current_liabilities=balancesheet[ 'totalCurrentLiabilities'].values[0], short_term_debt=balancesheet['shortTermDebt'].values[0], current_long_term_debt=balancesheet['currentLongTermDebt']. values[0], other_shareholder_equity=balancesheet['otherShareholderEquity'] .values[0], property_plant_equipment=balancesheet['propertyPlantEquipment'] .values[0], total_current_assets=balancesheet['totalCurrentAssets']. values[0], long_term_investment=balancesheet['longTermInvestments']. values[0], net_tangible_assets=balancesheet['netTangibleAssets']. values[0], short_term_investment=balancesheet['shortTermInvestments']. values[0], net_receivables=balancesheet['netReceivables'].values[0], long_term_debt=balancesheet['longTermDebt'].values[0], inventory=balancesheet['inventory'].values[0], accounts_payable=balancesheet['accountsPayable'].values[0], total_permanent_equity=balancesheet['totalPermanentEquity']. values[0], additional_paid_in_capital=balancesheet[ 'additionalPaidInCapital'].values[0], common_stock_total_equity=balancesheet[ 'commonStockTotalEquity'].values[0], preferred_stock_total_equity=balancesheet[ 'preferredStockTotalEquity'].values[0], retained_earnings_total_equity=balancesheet[ 'retainedEarningsTotalEquity'].values[0], treasury_stock=balancesheet['treasuryStock'].values[0], accumulated_amortization=balancesheet[ 'accumulatedAmortization'].values[0], other_non_current_assets=balancesheet['otherNonCurrrentAssets'] .values[0], deferred_long_term_asset_charges=balancesheet[ 'deferredLongTermAssetCharges'].values[0], total_non_current_assets=balancesheet['totalNonCurrentAssets']. values[0], capital_lease_obligations=balancesheet[ 'capitalLeaseObligations'].values[0], total_long_term_debt=balancesheet['totalLongTermDebt']. values[0], other_non_current_liabilities=balancesheet[ 'otherNonCurrentLiabilities'].values[0], total_non_current_liabilities=balancesheet[ 'totalNonCurrentLiabilities'].values[0], negative_goodwill=balancesheet['negativeGoodwill'].values[0], warrants=balancesheet['warrants'].values[0], preferred_stock_redeemable=balancesheet[ 'preferredStockRedeemable'].values[0], capital_surplus=balancesheet['capitalSurplus'].values[0], liabilities_and_shareholder_equity=balancesheet[ 'liabilitiesAndShareholderEquity'].values[0], cash_and_short_term_investments=balancesheet[ 'cashAndShortTermInvestments'].values[0], accumulated_depreciation=balancesheet[ 'accumulatedDepreciation'].values[0], common_stock_shares_outstanding=balancesheet[ 'commonStockSharesOutstanding'].values[0], ) bs.save() return JsonResponse( {'message': 'Annualy BalanceSheet Data Save successlly'}, status=status.HTTP_200_OK)
def balance_sheet(other_args: List[str], ticker: str): """Alpha Vantage balance sheet Parameters ---------- other_args : List[str] argparse other args ticker : str Fundamental analysis ticker symbol """ parser = argparse.ArgumentParser( add_help=False, prog="balance", 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: 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(other_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", 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_balance_sheet_quarterly(symbol=ticker) else: # pylint: disable=unbalanced-tuple-unpacking df_fa, _ = fd.get_balance_sheet_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
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
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
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')