def update_current_ratio(entity): ticker = Ticker(entity) df = ticker.balance_sheet() print("df: ", df) df = df.reset_index(drop=True) cols = df.columns totalCurrentAssets = df["totalCurrentAssets"][0] totalCurrentLiabilities = df["totalCurrentLiabilities"][0] ratio = float(totalCurrentAssets) / float(totalCurrentLiabilities) if ratio > 2: financial_status = "Conservatively financed" elif ratio > 1: financial_status = "Be careful" else: financial_status = "indebted" data = dict( asset_and_liability=[financial_status, "totalCurrentAssets", "totalCurrentLiabilities"], parent=["", financial_status, financial_status], value=[ratio, totalCurrentAssets, totalCurrentLiabilities] ) fig = px.sunburst( data, names='asset_and_liability', parents='parent', values='value', ) return fig
def update_current_ratio(active_cell): df = pd.read_csv(DATA_PATH + 'tickers_september_2017_red.csv') row = df.iloc[[active_cell.get("row")]] ticker = row['Ticker'].values[0] ticker = Ticker(ticker) df = ticker.balance_sheet() df = df.reset_index(drop=True) cols = df.columns totalCurrentAssets = df["totalCurrentAssets"][0] totalCurrentLiabilities = df["totalCurrentLiabilities"][0] ratio = float(totalCurrentAssets) / float(totalCurrentLiabilities) if ratio > 2: financial_status = "Conservatively financed" elif ratio > 1: financial_status = "Be careful" else: financial_status = "indebted" data = dict(asset_and_liability=[ financial_status, "totalCurrentAssets", "totalCurrentLiabilities" ], parent=["", financial_status, financial_status], value=[ratio, totalCurrentAssets, totalCurrentLiabilities]) fig = px.sunburst(data, names='asset_and_liability', parents='parent', values='value') return fig
def fetch(self, dataset: AnyStr, ticker: Ticker, **kwargs): if dataset == "income_statement": output = ticker.income_statement(frequency=kwargs.get("period"), trailing=False) elif dataset == "cash_flow": output = ticker.cash_flow(frequency=kwargs.get("period"), trailing=False) elif dataset == "balance_sheet": output = ticker.balance_sheet(frequency=kwargs.get("period"), trailing=False) else: return DataFrame() if type(output) == DataFrame: return output else: self.logger.warning(output) return DataFrame()
# Add CSV File Implementation df_stocks = pd.read_csv(r"/Users/matthew/Documents/UNI/Coding/Stock.csv") df_stocks.columns = ["Stocks"] stocklist = df_stocks["Stocks"].values.tolist() tickers = Ticker(stocklist) # Key Stats Data keystats = tickers.key_stats esg_scores = tickers.summary_detail # Storing the income statement data into a dataframe df_balance = tickers.balance_sheet().transpose() df_income = tickers.income_statement().transpose() df_cashflow = tickers.cash_flow().transpose() df_keystats = pd.DataFrame.from_dict(keystats) df_summary = pd.DataFrame(tickers.summary_detail) # Defining all the empty directories all_stat_income = {} all_stat_balance = {} all_stat_cashflow = {} all_stat_keystat = {} all_stat_summary = {} # All the data directories
def get(self): s = Ticker(self.stock.symbol, timeout=15) # all numbers convert to million df = s.balance_sheet(frequency="q") if "unavailable" in df or "error" in df: logger.error("{}: {}".format(self.stock.symbol, df)) return # DB doesn't like NaN df = df.where(pd.notnull(df), 0) # mapping between model field (left) and data json key (right) mapping = { "ap": "AccountsPayable", "cash_and_cash_equivalent": "CashAndCashEquivalents", "cash_cash_equivalents_and_short_term_investments": "CashCashEquivalentsAndShortTermInvestments", "common_stock": "CommonStock", "common_stock_equity": "CommonStockEquity", "invested_capital": "InvestedCapital", "long_term_debt_and_capital_lease_obligation": "LongTermDebtAndCapitalLeaseObligation", "machinery_furniture_equipment": "MachineryFurnitureEquipment", "net_ppe": "NetPPE", "net_tangible_assets": "NetTangibleAssets", "payables": "Payables", "payables_and_accrued_expenses": "PayablesAndAccruedExpenses", "retained_earnings": "RetainedEarnings", "stockholders_equity": "StockholdersEquity", "tangible_book_value": "TangibleBookValue", "total_assets": "TotalAssets", "total_capitalization": "TotalCapitalization", "total_debt": "TotalDebt", "total_non_current_assets": "TotalNonCurrentAssets", "working_capital": "WorkingCapital", "gross_ppe": "GrossPPE", "current_assets": "CurrentAssets", "current_liabilities": "CurrentLiabilities", "receivables": "Receivables", "other_short_term_investments": "OtherShortTermInvestments", "long_term_debt": "LongTermDebt", "other_current_liabilities": "OtherCurrentLiabilities", "land_and_improvements": "LandAndImprovements", "ar": "AccountsReceivable", "other_current_assets": "OtherCurrentAssets", "investments_and_advances": "InvestmentsAndAdvances", "current_debt": "CurrentDebt", "inventory": "Inventory", "total_tax_payable": "TotalTaxPayable", "available_for_sale_securities": "AvailableForSaleSecurities", "other_receivables": "OtherReceivables", "other_current_borrowings": "OtherCurrentBorrowings", "investmentin_financial_assets": "InvestmentinFinancialAssets", "cash_equivalents": "CashEquivalents", "cash_financial": "CashFinancial", "commercial_paper": "CommercialPaper", "current_deferred_liabilities": "CurrentDeferredLiabilities", "current_deferred_revenue": "CurrentDeferredRevenue", "leases": "Leases", "net_debt": "NetDebt", "accumulated_depreciation": "AccumulatedDepreciation", "allowance_for_doubtful_accounts_receivable": "AllowanceForDoubtfulAccountsReceivable", "properties": "Properties", "goodwill": "Goodwill", "goodwill_and_other_intangible_assets": "GoodwillAndOtherIntangibleAssets", "other_intangible_assets": "OtherIntangibleAssets", "other_non_current_assets": "OtherNonCurrentAssets", "current_debt_and_capital_lease_obligation": "CurrentDebtAndCapitalLeaseObligation", "other_current_liabilities": "OtherCurrentLiabilities", "total_non_current_liabilities_net_minority_interest": "TotalNonCurrentLiabilitiesNetMinorityInterest", "non_current_deferred_liabilities": "NonCurrentDeferredLiabilities", "tradeand_other_payables_non_current": "TradeandOtherPayablesNonCurrent", "other_non_current_liabilities": "OtherNonCurrentLiabilities", "non_current_deferred_taxes_liabilities": "NonCurrentDeferredTaxesLiabilities", "non_current_deferred_revenue": "NonCurrentDeferredRevenue", "share_issued": "ShareIssued", } # enumerate data frame for row in df.itertuples(index=False): i, created = BalanceSheet.objects.get_or_create( stock=self.stock, on=row.asOfDate.date()) for key, val in mapping.items(): try: # value can be None tmp = float(getattr(row, val)) except AttributeError: tmp = 0 # if tmp is a large number, it's unlikely a rate, # eg. tax rate, thus convert it to B. if abs(tmp) > M: tmp = tmp / B # set value setattr(i, key, tmp) i.save()
def calcIntVal(self): outst_shrs_list = [] Eps_1to5y_list = [] discount_rate_list = [] last_close_list = [] intrisic_per_share_list = [] for tick in self.ticks: #### Retrieve Stock #### stock_yq = Ticker(tick) stock_fv = fv.get_stock(tick) #### Cash Flow #### cash_fl = stock_yq.cash_flow(frequency="a") op_cash = cash_fl.tail(1).loc[:, "OperatingCashFlow"] #### Balance Sheet #### bal_sheet = stock_yq.balance_sheet(frequency="q") if "TotalDebt" in bal_sheet: total_debt = bal_sheet.tail(1).loc[:, "TotalDebt"] else: total_debt = 0 cash_short_term_investment = bal_sheet.tail( 1).loc[:, "CashCashEquivalentsAndShortTermInvestments"] #### Growth Rate #### try: Eps_1to5y = float(stock_fv["EPS next 5Y"].strip(' \t\n\r%')) except ValueError: Eps_1to5y = 0 if Eps_1to5y >= 15: Eps_6to10y = 15 else: Eps_6to10y = Eps_1to5y #### Last Close #### last_close = stock_yq.price[tick]["regularMarketPrice"] #### Outstanding Shares ### outst_shrs = self.text_to_num(stock_fv["Shs Outstand"]) #### Discount Rate #### try: beta = float(stock_fv["Beta"]) except ValueError: beta = 0 risk_free_rate = 0.64 mrkt_risk_prem = 5 discount_rate = round(risk_free_rate + beta * mrkt_risk_prem, 1) #### Present Value of 10 year Cash Flows #### PV_10y_CF_li = [] for x in range(10): if x == 0: Op_cash_flow_proj = op_cash * (1 + (Eps_1to5y / 100)) elif x > 5: Op_cash_flow_proj = op_cash * (1 + (Eps_6to10y / 100)) else: Op_cash_flow_proj = Op_cash_flow_proj * (1 + (Eps_1to5y / 100)) if x == 0: discount_factor = (1 / (1 + discount_rate / 100)) else: discount_factor = (discount_factor / (1 + discount_rate / 100)) Op_cash_flow_proj_discounted = Op_cash_flow_proj * discount_factor PV_10y_CF_li.append(Op_cash_flow_proj_discounted) PV_10y_CF = sum(PV_10y_CF_li) #### Intrinsic Value before cash/debt #### if outst_shrs != 0: intrisic_bfr_cash_dbt = round(PV_10y_CF / outst_shrs, 2) else: intrisic_bfr_cash_dbt = 0 #### Less Debt per Share #### if outst_shrs != 0: less_dbt_per_shr = round(total_debt / outst_shrs, 2) else: less_dbt_per_shr = 0 #### Plus (+) Cash Per Share #### if outst_shrs != 0: plus_cash_per_shr = round( cash_short_term_investment / outst_shrs, 2) else: plus_cash_per_shr = 0 #### Final Intrinsic Value Per Share #### intrisic_per_share = intrisic_bfr_cash_dbt - less_dbt_per_shr + plus_cash_per_shr #### Discount/Premium #### #discount_premium = (last_close - intrisic_per_share)/intrisic_per_share outst_shrs_list.append(self.num_to_text(outst_shrs)) Eps_1to5y_list.append(Eps_1to5y) discount_rate_list.append(discount_rate) last_close_list.append(last_close) intrisic_per_share_list.append( round(intrisic_per_share.get(tick), 2)) data = { 'symbol': self.ticks, 'outst_shrs': outst_shrs_list, 'Eps_1to5y': Eps_1to5y_list, 'discount_rate': discount_rate_list, 'last_close': last_close_list, 'intrisic_per_share': intrisic_per_share_list } df = pd.DataFrame.from_dict(data) return df