def get_fin_regressors(ticker_code): # TEST : get financial data for one ticker data = si.get_financials( ticker=ticker_code)['yearly_income_statement'].transpose() data['co_name'] = tickers_df.loc[ticker_code]['name'] data = data.sort_values(by='endDate') #data.loc['ds'] = data.loc['endDate'] # remove duplicates data.drop_duplicates(subset=['totalRevenue'], inplace=True) data = data.reset_index() data.index = data.endDate # calculate aggregates data['grossProfit_margin'] = data.apply( lambda x: margin(x['grossProfit'], x['totalRevenue']), axis=1) data['operatingIncome_margin'] = data.apply( lambda x: margin(x['operatingIncome'], x['totalRevenue']), axis=1) data['netIncome_margin'] = data.apply( lambda x: margin(x['netIncome'], x['totalRevenue']), axis=1) # calculate % growth revenue_growth = ['NaN'] for i in range(1, len(data)): revenue_growth.append( per_growth(data['totalRevenue'][i], data['totalRevenue'][i - 1])) data['revenue_growth'] = revenue_growth grossProfit_growth = ['NaN'] for i in range(1, len(data)): grossProfit_growth.append( per_growth(data['grossProfit'][i], data['grossProfit'][i - 1])) data['grossProfit_growth'] = grossProfit_growth operatingIncome_growth = ['NaN'] for i in range(1, len(data)): operatingIncome_growth.append( per_growth(data['operatingIncome'][i], data['operatingIncome'][i - 1])) data['operatingIncome_growth'] = operatingIncome_growth netIncome_growth = ['NaN'] for i in range(1, len(data)): netIncome_growth.append( per_growth(data['netIncome'][i], data['netIncome'][i - 1])) data['netIncome_growth'] = netIncome_growth return data
input( 'What is the Weighted Average Maturity of Debt Found in 10k Report (if unsure write 5):' )) print(int(input('Stock Based Compensation:'))) Ticker = input("Insert Ticker:") quote = yf.get_quote_table(Ticker) # indexing market cap MarketCap = quote["Market Cap"] # print market cap beta = quote["Beta (5Y Monthly)"] print('Market Cap:', "{:,}".format(conv_mrktcap(MarketCap)), '$') print('Beta:', beta) stats = yf.get_stats_valuation(Ticker) Data = yf.get_data(Ticker) Balance_Sheet = yf.get_balance_sheet(Ticker) financials = yf.get_financials(Ticker) analyst = yf.get_analysts_info(Ticker) # import company's valuations as stats income = yf.get_income_statement(Ticker) Cash = yf.get_cash_flow(Ticker) # import comapny's income statement as income ebit = income.loc["ebit"] # indexing ebit in icnome statement ebit2020 = int(ebit["2020"]) # indexing latest ebit in income statement print('Latest Calender Ebit:', "{:,}".format(ebit2020), "$") interestExpense = income.loc['interestExpense'] # indexing interest expense in imcome statement interestExpense2020 = int(-interestExpense["2020"])
def get_yahoo_fin(prod, outdir): """ Query exhaustive information of a stock on Yahoo finance and output to a worksheet Args: prod Product object, containing basic info about the stock such as symbol, name, currency etc. start_date start date string such as '1/1/2018' or '2018-1-1T00:00:00' end_date end date string such as '30/12/2018' ... outdir output dir to save the plot Return: no return """ ticker = prod._symbol out_path = os.path.join(outdir, f'{prod._name}.xlsx') print(f'Retrieving data for {prod._name} ...') writer = pd.ExcelWriter(out_path,engine='xlsxwriter') # Creating Excel Writer Object from Pandas # summary, quote table, stats print('\tQuerying summary/quote table/stats ...') row_count = 0 summ = {'name': prod._name, 'id': prod._id, 'symbol': prod._symbol, 'close price': prod._closeprice, 'close date': prod._closedate, 'current price': si.get_live_price(ticker), 'vwdId': prod._vwdId} df_summ = dict2dataframe(summ, 'info') df_summ.rename_axis('Summary', axis='index', inplace=True) df_summ.to_excel(writer, sheet_name='Summary', startrow=row_count, startcol=0) row_count = row_count + len(df_summ) + 2 df_quote = dict2dataframe(si.get_quote_table(ticker)) df_quote.rename_axis('Quote table', axis='index', inplace=True) df_quote.to_excel(writer, sheet_name='Summary', startrow=row_count, startcol=0) row_count = row_count + len(df_quote) + 2 df_stats = si.get_stats(ticker) df_stats.rename_axis('Stats', axis='index', inplace=True) df_stats.to_excel(writer, sheet_name='Summary', startrow=row_count, startcol=0) row_count = row_count + len(df_stats) + 2 # analyst print('\tQuerying analyst ...') ana = si.get_analysts_info(ticker) # this return a dict of pandas dataframes row_count = 0 for key, df in ana.items(): df.name = key df.to_excel(writer, sheet_name='Analyst Info', startrow=row_count, startcol=0) row_count = row_count + len(df) + 2 # balance sheet print('\tQuerying balance ...') df_bal = si.get_balance_sheet(ticker) df_bal.to_excel(writer,sheet_name='Balance', startrow=0 , startcol=0) # cash flow print('\tQuerying cash flow ...') df_cash = si.get_cash_flow(ticker) df_cash.to_excel(writer,sheet_name='Cash flow', startrow=0 , startcol=0) # data print('\tQuerying historic data ...') df_data = si.get_data(ticker) df_data.sort_index(ascending=False, inplace=True) df_data.to_excel(writer,sheet_name='Data', startrow=0 , startcol=0) # financial print('\tQuerying financial ...') fin = si.get_financials(ticker) # this return a dict of dataframes row_count = 0 for key, df in fin.items(): df.rename_axis(key, axis='index', inplace=True) df.to_excel(writer, sheet_name='Financial', startrow=row_count, startcol=0) row_count = row_count + len(df) + 2 # save writer.save() print(f'Data saved to {out_path}')
def get_fundamental_data(self): """ all fundamental data """ try: self.fundamental = si.get_quote_data(self.ticker) except: pass try: self.quote = si.get_quote_table(self.ticker) except: pass try: self.stats = si.get_stats(self.ticker) except: pass try: self.earnings = si.get_earnings(self.ticker) except: pass try: self.financials = si.get_financials(self.ticker) except: pass # Individual fundamental factors try: self.earnings_up_count = sum( (self.earnings['quarterly_revenue_earnings'].earnings.diff() > 0).iloc[1:]) except: self.errorCount += 1 try: self.earnings_up_latest = int( (self.earnings['quarterly_revenue_earnings'].earnings.diff() > 0).iloc[-1]) except: self.errorCount += 1 try: self.trailingPE = self.quote['PE Ratio (TTM)'] except: self.errorCount += 1 try: self.EPS = self.quote['EPS (TTM)'] except: self.errorCount += 1 try: self.marketCap = self.fundamental['marketCap'] except: self.errorCount += 1 try: self.TotalDebtEquity = self.stats[ self.stats.Attribute == 'Total Debt/Equity (mrq)'].iloc[0, 1] except: self.errorCount += 1 try: self.shortRatio = float(self.stats[ self.stats.Attribute.str.contains('Short Ratio')].iloc[0, 1]) except: self.errorCount += 1 try: self.institutionPct = float( self.stats[self.stats.Attribute.str.contains( 'Held by Institutions')].iloc[0, 1][:-1]) except: self.errorCount += 1
def __init__(self, name): quote_table = si.get_quote_table(name, dict_result=False) open = quote_table.at[12, 'value'] price = quote_table.at[15, 'value'] prePrice = quote_table.at[14, 'value'] pe = quote_table.at[13, 'value'] avgVol = quote_table.at[3, 'value'] vol = quote_table.at[6, 'value'] ticker = yf.Ticker(name) info = ticker.info mktCap = info['marketCap'] mktCapNum = mktCap mktCap = mktCap / 1000000000 mktCap = "{:.1f}".format(mktCap) self.mktCap = mktCap + 'B' symbol = info['symbol'] self.ave50 = info['fiftyDayAverage'] self.name = info['shortName'] country = get_dict_item(info, 'country') employeeRaw = get_dict_item(info, 'fullTimeEmployees') if employeeRaw is not None: employee = format(employeeRaw, ',d') else: employee = '-' instHoldPctRaw = get_dict_item(info, 'heldPercentInstitutions') if instHoldPctRaw is not None: instHoldPct = "{:.1%}".format(instHoldPctRaw) else: instHoldPct = '-' fin = si.get_financials(name) # fin_bs_q=fin["quarterly_balance_sheet"] fin_bs_q = fin["yearly_balance_sheet"] fin_bs_q_dates = fin_bs_q.columns.values date = fin_bs_q_dates[0] dateStr = str(date) self.finDate = dateStr[0:10] fin_year_y = fin["yearly_balance_sheet"] fin_year_dates_y = fin_year_y.columns.values date_y = fin_year_dates_y[0] dateStr_y = str(date_y) self.finDate_y = dateStr_y[0:10] sharesOutstandingRaw = get_dict_item(info, 'sharesOutstanding') sharesOutstanding = number2M_pure(sharesOutstandingRaw) ## General # Total Asset totalAssetsRaw, totalAssets = get_dataframe_item( fin_bs_q, 'totalAssets', country, date, 0) # Total Liabilities totalLiabRaw, totalLiab = get_dataframe_item(fin_bs_q, 'totalLiab', country, date, 0) totalLiab_pct = addPct(totalLiabRaw, totalLiab, totalAssetsRaw) # Total Equity totalEquityRaw = totalAssetsRaw - totalLiabRaw totalEquity = number2M(totalEquityRaw, country, date) totalEquityRaw_pct = addPct(totalEquityRaw, totalEquity, totalAssetsRaw) ## ASSET # Total Current Assets totalCurrentAssetsRaw, totalCurrentAssets = get_dataframe_item( fin_bs_q, 'totalCurrentAssets', country, date, 0) if totalCurrentAssetsRaw is not None: pct = "{:.1%}".format(totalCurrentAssetsRaw / totalAssetsRaw) totalCurrentAssets = totalCurrentAssets + ' (' + pct + ')' # Cash cashRaw, cash = get_dataframe_item(fin_bs_q, 'cash', country, date, 0) cash_pct = addPct(cashRaw, cash, totalCurrentAssetsRaw) # Short Term Investment shortTermInvestmentsRaw, shortTermInvestments = get_dataframe_item( fin_bs_q, 'shortTermInvestments', country, date, 0) shortTermInvestments_pct = addPct(shortTermInvestmentsRaw, shortTermInvestments, totalCurrentAssetsRaw) # Receivables netReceivablesRaw, netReceivables = get_dataframe_item( fin_bs_q, 'netReceivables', country, date, 0) netReceivables_pct = addPct(netReceivablesRaw, netReceivables, totalCurrentAssetsRaw) # Inventory inventoryRaw, inventory = get_dataframe_item(fin_bs_q, 'inventory', country, date, 0) inventory_pct = addPct(inventoryRaw, inventory, totalCurrentAssetsRaw) # Other Current Asset otherCurrentAssetsRaw, otherCurrentAssets = get_dataframe_item( fin_bs_q, 'otherCurrentAssets', country, date, 0) otherCurrentAssets_pct = addPct(otherCurrentAssetsRaw, otherCurrentAssets, totalCurrentAssetsRaw) # Total Long Term Asset totalLongTermAssetRaw = totalAssetsRaw - totalCurrentAssetsRaw totalLongTermAsset = number2M(totalLongTermAssetRaw, country, date) totalLongTermAsset_pct = addPct(totalLongTermAssetRaw, totalLongTermAsset, totalAssetsRaw) # Property, Plant, and Equipment propertyPlantEquipmentRaw, propertyPlantEquipment = get_dataframe_item( fin_bs_q, 'propertyPlantEquipment', country, date, 0) propertyPlantEquipment_pct = addPct(propertyPlantEquipmentRaw, propertyPlantEquipment, totalLongTermAssetRaw) # Long-term Investment longTermInvestmentsRaw, longTermInvestments = get_dataframe_item( fin_bs_q, 'longTermInvestments', country, date, 0) longTermInvestments_pct = addPct(longTermInvestmentsRaw, longTermInvestments, totalLongTermAssetRaw) # Net Intangible Asset netIntangibleAssetsRaw, netIntangibleAssets = get_dataframe_item( fin_bs_q, 'intangibleAssets', country, date, 0) netIntangibleAssets_pct = addPct(netIntangibleAssetsRaw, netIntangibleAssets, totalLongTermAssetRaw) # Goodwill goodWillRaw, goodWill = get_dataframe_item(fin_bs_q, 'goodWill', country, date, 0) goodWill_pct = addPct(goodWillRaw, goodWill, totalLongTermAssetRaw) # Intangible Asset intangibleAssetsRaw = netIntangibleAssetsRaw + goodWillRaw intangibleAssets = number2M(intangibleAssetsRaw, country, date) intangibleAssets_pct = addPct(intangibleAssetsRaw, intangibleAssets, totalLongTermAssetRaw) # Other Long-term Asset otherAssetsRaw, otherAssets = get_dataframe_item( fin_bs_q, 'otherAssets', country, date, 0) otherAssets_pct = addPct(otherAssetsRaw, otherAssets, totalLongTermAssetRaw) # Tangible tangibleAssetsRaw = totalAssetsRaw - intangibleAssetsRaw tangibleAssets = number2M(tangibleAssetsRaw, country, date) tangibleAssets_pct = addPct(tangibleAssetsRaw, tangibleAssets, totalAssetsRaw) ## LIABILITY # Total Current Liabilities totalCurrentLiabilitiesRaw, totalCurrentLiabilities = get_dataframe_item( fin_bs_q, 'totalCurrentLiabilities', country, date, 0) totalCurrentLiabilities_pct = addPct(totalCurrentLiabilitiesRaw, totalCurrentLiabilities, totalLiabRaw) # Account Payable accountsPayableRaw, accountsPayable = get_dataframe_item( fin_bs_q, 'accountsPayable', country, date, 0) accountsPayable_pct = addPct(accountsPayableRaw, accountsPayable, totalCurrentLiabilitiesRaw) # Other Current Liabilities otherCurrentLiabRaw, otherCurrentLiab = get_dataframe_item( fin_bs_q, 'otherCurrentLiab', country, date, 0) otherCurrentLiab_pct = addPct(otherCurrentLiabRaw, otherCurrentLiab, totalCurrentLiabilitiesRaw) # Total Long-term Liablities totalLongTermLiabRaw = totalLiabRaw - totalCurrentLiabilitiesRaw totalLongTermLiab = number2M(totalLongTermLiabRaw, country, date) totalLongTermLiab_pct = addPct(totalLongTermLiabRaw, totalLongTermLiab, totalLiabRaw) # Long-term Debt longTermDebtRaw, longTermDebt = get_dataframe_item( fin_bs_q, 'longTermDebt', country, date, 0) longTermDebt_pct = addPct(longTermDebtRaw, longTermDebt, totalLongTermLiabRaw) shortLongTermDebtRaw, shortLongTermDebt = get_dataframe_item( fin_bs_q, 'shortLongTermDebt', country, date, 0) ## EQUITY # Minority Interest minorityInterestRaw, minorityInterest = get_dataframe_item( fin_bs_q, 'minorityInterest', country, date, 0) minorityInterest_pct = addPct(minorityInterestRaw, minorityInterest, totalEquityRaw) # Total Shareholder's Equity totalShareholderEquityRaw = totalEquityRaw - minorityInterestRaw totalShareholderEquity = number2M(totalShareholderEquityRaw, country, date) totalShareholderEquity_pct = addPct(totalShareholderEquityRaw, totalShareholderEquity, totalEquityRaw) # Common Stock commonStockRaw, commonStock = get_dataframe_item( fin_bs_q, 'commonStock', country, date, 0) # Retained Earnings retainedEarningsRaw, retainedEarnings = get_dataframe_item( fin_bs_q, 'retainedEarnings', country, date, 0) # Gains Losses Not Affecting Retained Earnings (Treasury Stock) treasuryStockRaw, treasuryStock = get_dataframe_item( fin_bs_q, 'treasuryStock', country, date, 0) # Common Stock Equity commonStockEquityRaw, commonStockEquity = get_dataframe_item( fin_bs_q, 'totalStockholderEquity', country, date, 0) commonStockEquity_pct = addPct(commonStockEquityRaw, commonStockEquity, totalShareholderEquityRaw) # Preferred Stock Equity preferredStockEquityRaw = totalShareholderEquityRaw - commonStockEquityRaw preferredStockEquity = number2M(preferredStockEquityRaw, country, date) preferredStockEquity_pct = addPct(preferredStockEquityRaw, preferredStockEquity, totalShareholderEquityRaw) # Book Value bookValueRaw = tangibleAssetsRaw - totalLiabRaw bookValue = number2M(bookValueRaw, country, date) # Common Book Value commonBookValueRaw = commonStockEquityRaw - intangibleAssetsRaw commonBookValue = number2M(commonBookValueRaw, country, date) capitalSurplusRaw, capitalSurplus = get_dataframe_item( fin_bs_q, 'capitalSurplus', country, date, 0) floatSharesRaw = info["floatShares"] floatShares = number2M(floatSharesRaw, country, date) floatSharesPct = "{:.1%}".format(floatSharesRaw / sharesOutstandingRaw) # FUNDAMENTALS workingCapitalRaw = totalCurrentAssetsRaw - totalCurrentLiabilitiesRaw if (workingCapitalRaw is not None) & (not math.isnan(workingCapitalRaw)): workingCapital = number2M(workingCapitalRaw, country, date) # Basic Ratios currentRatioRaw = totalCurrentAssetsRaw / totalCurrentLiabilitiesRaw currentRatio = "{:.2f}".format(currentRatioRaw) quickRatioRaw = (totalCurrentAssetsRaw - inventoryRaw) / totalCurrentLiabilitiesRaw quickRatio = "{:.2f}".format(quickRatioRaw) deRaw = totalLiabRaw / totalShareholderEquityRaw de = "{:.2f}".format(deRaw) # BVPS bvpsRaw = commonStockEquityRaw / sharesOutstandingRaw bvps = "{:.2f}".format(bvpsRaw) tanBvpsRaw = (commonStockEquityRaw - intangibleAssetsRaw) / sharesOutstandingRaw tanBvps = "{:.2f}".format(tanBvpsRaw) ## Income in_quart = fin["quarterly_income_statement"] netIncomeRaw, netIncome = get_dataframe_item(in_quart, 'netIncome', country, date, 0) # roeRaw=4*netIncomeRaw/((totalStockholderEquityRaw+totalStockholderEquityRawPre1)/2) # roe="{:.1%}".format(roeRaw) totalRevenueRaw, totalRevenue = get_dataframe_item( in_quart, 'totalRevenue', country, date, 0) # dfsize=in_quart.shape # colNum=dfsize[1] # if colNum>1: # sum = totalRevenueRaw # for i in range(1,colNum): # tempRaw,temp=get_dataframe_item(in_quart,'totalRevenue',country,date,i) # sum = sum + tempRaw # totalRevenueRawTTM = sum / colNum # totalRevenueTTM=number2M(totalRevenueRawTTM,country,date) grossProfitRaw, grossProfit = get_dataframe_item( in_quart, 'grossProfit', country, date, 0) rd_q0Raw, rd_q0 = get_dataframe_item(in_quart, 'researchDevelopment', country, date, 0) in_year = fin["yearly_income_statement"] rd_y = in_year.loc['researchDevelopment'] rd_y0 = rd_y.iloc[0] if rd_y0 is not None: rd_y0 = convert_currency(rd_y0, country, date) rd_y0 = int(rd_y0 / 1000000) rd_y0 = format(rd_y0, ',d') rd_y0 = str(rd_y0) + 'M' BalanceSheetBasic = { 'Symbol': symbol, 'MktCapNum': [mktCapNum], # Used for data reorder 'Tot Asset': totalAssets, 'Tot Liab': totalLiab_pct, 'Tot Equity': totalEquityRaw_pct } df_BalanceSheetBasic = pd.DataFrame(BalanceSheetBasic, index=[0]) d = { 'Symbol': symbol, 'MktCapNum': mktCapNum, # Used for data reorder 'Price': [("{:.2f}".format(price))], 'EMPL No.': employee, 'Qtly Date': self.finDate, 'Annu Date': self.finDate_y, 'Shares Outsdg': sharesOutstanding } df_Old = pd.DataFrame(d, index=[0]) incomeDetail = { 'Symbol': symbol, 'MktCapNum': mktCapNum, # Used for data reorder 'Net Income': netIncome } df_incomeDetail = pd.DataFrame(incomeDetail, index=[0]) assetDetail = { 'Symbol': symbol, 'MktCapNum': mktCapNum, # Used for data reorder 'Tot Asset': totalAssets, 'Total Current / Tot': totalCurrentAssets, 'Cash / Cr': cash_pct, 'ShrtT Invest / Cr': shortTermInvestments_pct, 'Receivables / Cr': netReceivables_pct, 'Inventory / Cr': inventory_pct, 'Other Curr Asset / Cr': otherCurrentAssets_pct, 'Total Long-term / Tot': totalLongTermAsset_pct, 'Property,ect / Lng': propertyPlantEquipment_pct, 'LongT Invest / Lng': longTermInvestments_pct, 'Intangible / Lng': intangibleAssets_pct, 'Net Intangible / Lng': netIntangibleAssets_pct, 'Goodwill / Lng': goodWill_pct, 'Other LongT Asset / Lng': otherAssets_pct, 'Tangible / Tot': tangibleAssets_pct, } df_assetDetail = pd.DataFrame(assetDetail, index=[0]) liabilityDetail = { 'Symbol': symbol, 'MktCapNum': mktCapNum, # Used for data reorder 'Tot Liab': totalLiab, 'Total Current / Tot': totalCurrentLiabilities_pct, 'Acc Payable / Cr': accountsPayable_pct, 'Other Curr / Cr': otherCurrentLiab_pct, 'Total Long / Tot': totalLongTermLiab_pct, 'Long Debt / Lng': longTermDebt_pct, 'shortLongTermDebt': shortLongTermDebt } df_liabilityDetail = pd.DataFrame(liabilityDetail, index=[0]) equityDetail = { 'Symbol': symbol, 'MktCapNum': mktCapNum, # Used for data reorder 'Tot Eqty': totalEquity, 'Mnrty Int / Tot': minorityInterest_pct, 'Tot Sh Eqty / Tot': totalShareholderEquity_pct, 'Commn Eqty / ShH': commonStockEquity_pct, 'Prffd Eqty / ShH': preferredStockEquity_pct, 'Book Val': bookValue, 'Comn Book Val': commonBookValue, 'Cap Surplus': capitalSurplus } df_equityDetail = pd.DataFrame(equityDetail, index=[0]) fundamentals = { 'Symbol': symbol, 'MktCapNum': mktCapNum, # Used for data reorder 'Wrk Cap': workingCapital, } df_fundamentals = pd.DataFrame(fundamentals, index=[0]) baiscRatios = { 'Symbol': symbol, 'MktCapNum': mktCapNum, # Used for data reorder 'Current Rt': currentRatio, 'Quick Rt': quickRatio, 'Debt-Equity': de, 'BVPS': bvps, 'TanBVPS': tanBvps } df_baiscRatios = pd.DataFrame(baiscRatios, index=[0]) self.output = { 'General Information': df_Old, 'Balance Sheet Basic': df_BalanceSheetBasic, 'Income': df_incomeDetail, 'Assets Details': df_assetDetail, 'Liability Details': df_liabilityDetail, 'Equity Details': df_equityDetail, 'Fundamentals': df_fundamentals, 'Basic Ratios': df_baiscRatios }
def getQuarterlyFinancials(ticker): return si.get_financials(ticker, yearly=False, quarterly=True)
from yahoo_fin import stock_info as si import pandas as pd import xlsxwriter stock = 'NVDA' directory = "/users/satish/Desktop/" + stock + "_fundamentals.xlsx" writer = pd.ExcelWriter(directory, engine='xlsxwriter') balance_sheet = si.get_balance_sheet(stock, True) income_statement = si.get_income_statement(stock, True) cash_flow = si.get_cash_flow(stock, True) financials = si.get_financials(stock, yearly=True) balance_sheet.to_excel(writer, sheet_name='Balance Sheet') income_statement.to_excel(writer, sheet_name='Income Statement') cash_flow.to_excel(writer, sheet_name='Cash Flow') #financials.to_excel(writer, sheet_name = 'Financials') writer.save()