class YahooFinancialEngine(AbstractEngine): """description of class""" StockName: str PeRatio: float FromDate: date FromDateStr: str ToDate: date ToDateStr: str Financial: YahooFinancials HistoricalPriceDic: dict FinancialTypeDic: dict def __init__(self, yahoo_ticker: YahooTicker): self.__dateFormat: str = '%Y-%m-%d' self.__ticker = yahoo_ticker self.__setFrom(yahoo_ticker.DateTimeFrom) self.__setTo(yahoo_ticker.DateTimeTo) self.Financial = YahooFinancials(self.__ticker.TickerName) self.HistoricalPriceDic = self.Financial.get_historical_price_data(self.FromDateStr, self.ToDateStr, 'daily')[self.__ticker.TickerName] self.__setStockName() self.__setPeRatio() self.FinancialTypeDic = self.Financial.YAHOO_FINANCIAL_TYPES def __setStockName(self): self.StockName = ( 'NA' if self.Financial.get_stock_exchange() is None else self.Financial.get_stock_exchange() ) def __setPeRatio(self): self.PeRatio = ( 0.0 if self.Financial.get_pe_ratio() is None else self.Financial.get_pe_ratio() ) def __setFrom(self, from_date: date): self.FromDate = from_date self.FromDateStr = from_date.strftime(self.__dateFormat) def __setTo(self, to_date: date): self.ToDate = to_date self.ToDateStr = to_date.strftime(self.__dateFormat) def GetDailyHistoricalDataPrices(self, from_date: date, to_date: date): self.__setFrom(from_date) self.__setTo(to_date) return self.HistoricalPriceDic['prices']
def fundamentals(tickers, begin="2020-05-26", end="2020-06-26",): format_header = '{:>6} {:>6} {:>6} {:>6} {:>6} {:>6} {:>6} {:>6} {:>6} {:>6} {:>10} {:>10}' format_numbers = '{:>6} {:>6} {:>6} {:>6} {:>6} {:>6} {:>6} {:>6} {:>6} {:>6} {:>10.2e} {:>10.2E}' print(format_header.format('ticker', 'P/E', 'EARNSH', 'BK/PR', 'DY', 'DR', 'VAR', 'PEG', 'PS', 'PCI', 'VOLPR', 'CM',)) for ticker in tickers: yf = YF(ticker) try: pe = get_number_for_None(get_number_for_None(yf.get_pe_ratio())) prices = yf.get_historical_price_data(begin, end, "daily")[ticker]['prices'] stat_pr = calc_statistics(prices) var_pr = get_number_for_None(100 * stat_pr[1] / stat_pr[0]) volume = get_number_for_None(stat_pr[4]) es = get_number_for_None(yf.get_earnings_per_share()) sh = get_number_for_None(yf.get_num_shares_outstanding(price_type='current')) ''' "pegRatio" "priceToBook" "heldPercentInstitutions" ''' statistics = yf.get_key_statistics_data()[ticker] summary = yf.get_summary_data()[ticker] peg = get_number_for_None(statistics["pegRatio"]) PCI = get_number_for_None(statistics["heldPercentInstitutions"]) bv = yf.get_key_statistics_data()[ticker]['bookValue'] pr = yf.get_current_price() if pr is not None and bv is not None: pr_bv = get_number_for_None(pr/bv) else: pr_bv = '-99.99' f_s = yf.get_financial_stmts('annual', 'income')['incomeStatementHistory'][ticker][0] f_s_key = list(f_s.keys())[0] totalRevenue = f_s[f_s_key]['totalRevenue'] outstanding = statistics["sharesOutstanding"] rev_per_share = totalRevenue / outstanding if pr is not None and es is not None: p_s = get_number_for_None(rev_per_share/float(es)) else: p_s = '99' dy = get_number_for_None(yf.get_dividend_yield()) dr = get_number_for_None(yf.get_dividend_rate()) volume10days = summary['averageVolume10days'] marketCap = summary['marketCap'] # float(volume)*pr # float(sh)*pr) print(format_numbers.format(ticker, pe, es, pr_bv, dy, dr, var_pr, peg, p_s, PCI, volume10days, marketCap)) except Exception as e: print(ticker, e)
def getMarketData(): tickers = 'AAPL' financials = YahooFinancials(tickers) # company_stock_price = financials.get_stock_price_data() #gets stock price information historical_stock_prices_data = financials.get_historical_price_data( '2015-11-21', '2020-11-21', 'daily') #gets historical daily stock price of company # get_Div_data(historical_stock_prices_data[tickers]) get_stock_price_data(historical_stock_prices_data[tickers]) # company_balance_sheet_data_qt = financials.get_financial_stmts('quarterly', 'balance') #get balance sheet # company_income_statement_data_qt = financials.get_financial_stmts('quarterly', 'income') #get income statement company_key_statistics_data = financials.get_key_statistics_data( ) #includes profit margins, forward eps, yearly change etc. # get_forward_pe(company_key_statistics_data[tickers]) # get_trailing_eps(company_key_statistics_data[tickers]) # get_foward_eps(company_key_statistics_data[tickers]) # get_ytdReturn(company_key_statistics_data[tickers]) company_earnings_data = financials.get_stock_earnings_data( ) #historical eps only for 1 year span # get_earnings_data(company_earnings_data[tickers]) company_dividend_yield = financials.get_dividend_yield( ) #current dividends yield company_dividend = financials.get_dividend_rate() #current dividends rate company_avg_div_yield_1year = financials.get_annual_avg_div_yield( ) #average 1 year div yield company_avg_div_yield_5year = financials.get_five_yr_avg_div_yield( ) #average 5 year div yield company_eps = financials.get_earnings_per_share() #current eps company_pe = financials.get_pe_ratio() #current pe ratio company_beta = financials.get_beta() #current beta company_current_stock_price = financials.get_current_price( ) #current stock price company_revenue = financials.get_total_revenue() #current company revenue company_operating_income = financials.get_operating_income( ) #current company operating income company_net_income = financials.get_net_income() #current net income company_yearly_high = financials.get_yearly_high() #get yearly high company_yearly_low = financials.get_yearly_low() #get yearly low company_moving_50 = financials.get_50day_moving_avg( ) #50 day moving average of stock company_moving_200 = financials.get_200day_moving_avg( ) #200 day moving average of stock
def calc_earnings_yield(tickers): """ calc earnings to yield ratio :param tickers: :return: """ print('Fetching Earnings to Yield Data from Yahoo for 100 Tickers...') total_data = {} for index, ticker in enumerate(tickers): if index % 1 == 0: print('Fetching Earnings to Yield Data for %d out of %d' % (index, len(tickers))) try: yahoo_financials = YahooFinancials(ticker) total_data[ticker] = 1 / yahoo_financials.get_pe_ratio() except KeyError: print('Could not calc. PE for %s' % ticker) total_data[ticker] = None continue return total_data
def get_stock_data(stock_data): symbol = stock_data['symbol'] start = time.time() print('start: {}'.format(symbol)) Stock = YahooFinancials(symbol) stock_data['pe_ratio'] = Stock.get_pe_ratio() if stock_data['pe_ratio'] != None and stock_data['pe_ratio'] < 15: key_stock_data = Stock.get_key_statistics_data() stock_data['pb_ratio'] = key_stock_data[symbol]['priceToBook'] if stock_data['pb_ratio'] != None and stock_data['pb_ratio'] < 1.5: balance_sheet_data = Stock.get_financial_stmts('annual', 'balance') income_sheet_data = Stock.get_financial_stmts('annual', 'income') bal1 = balance_sheet_data['balanceSheetHistory'][symbol][0] bal2 = balance_sheet_data['balanceSheetHistory'][symbol][1] bal3 = balance_sheet_data['balanceSheetHistory'][symbol][2] bal4 = balance_sheet_data['balanceSheetHistory'][symbol][3] bal1_key1 = next(iter(bal1)) bal2_key1 = next(iter(bal2)) bal3_key1 = next(iter(bal3)) bal4_key1 = next(iter(bal4)) inc1 = income_sheet_data['incomeStatementHistory'][symbol][0] inc2 = income_sheet_data['incomeStatementHistory'][symbol][1] inc3 = income_sheet_data['incomeStatementHistory'][symbol][2] inc4 = income_sheet_data['incomeStatementHistory'][symbol][3] inc1_key1 = next(iter(inc1)) inc2_key1 = next(iter(inc2)) inc3_key1 = next(iter(inc3)) inc4_key1 = next(iter(inc4)) stock_data['liabilities'] = bal1[bal1_key1][ 'totalCurrentLiabilities'] stock_data['assets'] = bal1[bal1_key1]['totalCurrentAssets'] stock_data['equity1'] = bal1[bal1_key1]['totalStockholderEquity'] stock_data['equity2'] = bal2[bal2_key1]['totalStockholderEquity'] stock_data['equity3'] = bal3[bal3_key1]['totalStockholderEquity'] stock_data['equity4'] = bal4[bal4_key1]['totalStockholderEquity'] stock_data['net_income1'] = inc1[inc1_key1]['netIncome'] stock_data['net_income2'] = inc2[inc2_key1]['netIncome'] stock_data['net_income3'] = inc3[inc3_key1]['netIncome'] stock_data['net_income4'] = inc4[inc4_key1]['netIncome'] db = sqlite3.connect('stocks.db') c = db.cursor() c.execute( '''INSERT INTO stocks ( symbol, company_name, pb_ratio, pe_ratio, assets, liabilities, net_income1, net_income2, net_income3, net_income4, equity1, equity2, equity3, equity4 ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)''', (stock_data['symbol'], stock_data['company_name'], stock_data['pb_ratio'], stock_data['pe_ratio'], stock_data['assets'], stock_data['liabilities'], stock_data['net_income1'], stock_data['net_income2'], stock_data['net_income3'], stock_data['net_income4'], stock_data['equity1'], stock_data['equity2'], stock_data['equity3'], stock_data['equity4'])) db.commit() del stock_data end = time.time() print('got: {} - {}'.format(symbol, round(end - start))) return None
def balance_sheet_provider(comp_name, comp_code): yahoo_finance_object = YahooFinancials(comp_code) balance_sheet_raw = yahoo_finance_object.get_financial_stmts( 'annual', 'balance') income_statement_raw = yahoo_finance_object.get_financial_stmts( 'annual', 'income') e_p_s = None pe_rat = None try: e_p_s = yahoo_finance_object.get_earnings_per_share() pe_rat = yahoo_finance_object.get_pe_ratio() except KeyError: pass balance_sheet = balance_sheet_raw["balanceSheetHistory"][comp_code] income_statement = income_statement_raw["incomeStatementHistory"][ comp_code] company_data_provider_object = StockDataExtractor(comp_code, comp_name, balance_sheet, income_statement, e_p_s, pe_rat) ''' balance_sheet_raw = {"balanceSheetHistory": {"KO": [{"2017-12-31": {"intangibleAssets": 7235000000, "capitalSurplus": 15864000000, "totalLiab": 68919000000, "totalStockholderEquity": 17072000000, "minorityInterest": 1905000000, "otherCurrentLiab": 2169000000, "totalAssets": 87896000000, "commonStock": 1760000000, "otherCurrentAssets": 7993000000, "retainedEarnings": 60430000000, "otherLiab": 10504000000, "goodWill": 9401000000, "treasuryStock": -60982000000, "otherAssets": 3231000000, "cash": 6006000000, "totalCurrentLiabilities": 27194000000, "deferredLongTermAssetCharges": 331000000, "shortLongTermDebt": 47754000000, "otherStockholderEquity": -10305000000, "propertyPlantEquipment": 8203000000, "totalCurrentAssets": 36545000000, "longTermInvestments": 23281000000, "netTangibleAssets": 436000000, "shortTermInvestments": 14669000000, "netReceivables": 3667000000, "longTermDebt": 31221000000, "inventory": 2655000000, "accountsPayable": 2288000000}}, {"2016-12-31": {"intangibleAssets": 10499000000, "capitalSurplus": 14993000000, "totalLiab": 64050000000, "totalStockholderEquity": 23062000000, "minorityInterest": 158000000, "otherCurrentLiab": 1936000000, "totalAssets": 87270000000, "commonStock": 1760000000, "otherCurrentAssets": 3592000000, "retainedEarnings": 65502000000, "otherLiab": 7786000000, "goodWill": 10629000000, "treasuryStock": -59193000000, "otherAssets": 2928000000, "cash": 8555000000, "totalCurrentLiabilities": 26532000000, "deferredLongTermAssetCharges": 326000000, "shortLongTermDebt": 45801000000, "otherStockholderEquity": -11205000000, "propertyPlantEquipment": 10635000000, "totalCurrentAssets": 34010000000, "longTermInvestments": 18569000000, "netTangibleAssets": 1934000000, "shortTermInvestments": 13646000000, "netReceivables": 3856000000, "longTermDebt": 29732000000, "inventory": 2675000000, "accountsPayable": 2682000000}}, {"2015-12-31": {"intangibleAssets": 12843000000, "capitalSurplus": 14016000000, "totalLiab": 64232000000, "totalStockholderEquity": 25554000000, "minorityInterest": 210000000, "otherCurrentLiab": 2333000000, "totalAssets": 89996000000, "commonStock": 1760000000, "otherCurrentAssets": 4748000000, "retainedEarnings": 65018000000, "otherLiab": 8760000000, "goodWill": 11289000000, "treasuryStock": -55240000000, "otherAssets": 3030000000, "cash": 7309000000, "totalCurrentLiabilities": 26929000000, "deferredLongTermAssetCharges": 360000000, "shortLongTermDebt": 44401000000, "otherStockholderEquity": -10174000000, "propertyPlantEquipment": 12571000000, "totalCurrentAssets": 33395000000, "longTermInvestments": 16868000000, "netTangibleAssets": 1422000000, "shortTermInvestments": 12591000000, "netReceivables": 4466000000, "longTermDebt": 19100000000, "inventory": 3100000000, "accountsPayable": 2089000000}}]}} income_statement_raw = {"incomeStatementHistory": {"KO": [{"2017-12-31": {"researchDevelopment": None, "effectOfAccountingCharges": None, "incomeBeforeTax": 6742000000, "minorityInterest": 1905000000, "netIncome": 1248000000, "sellingGeneralAdministrative": 14653000000, "grossProfit": 22154000000, "ebit": 7583000000, "operatingIncome": 7501000000, "otherOperatingExpenses": None, "interestExpense": 841000000, "extraordinaryItems": None, "nonRecurring": None, "otherItems": None, "incomeTaxExpense": 5560000000, "totalRevenue": 35410000000, "totalOperatingExpenses": 0, "costOfRevenue": 13256000000, "totalOtherIncomeExpenseNet": -989000000, "discontinuedOperations": 101000000, "netIncomeFromContinuingOps": 1182000000, "netIncomeApplicableToCommonShares": 1248000000}}, {"2016-12-31": {"researchDevelopment": None, "effectOfAccountingCharges": None, "incomeBeforeTax": 8136000000, "minorityInterest": 158000000, "netIncome": 6527000000, "sellingGeneralAdministrative": 16772000000, "grossProfit": 25398000000, "ebit": 8869000000, "operatingIncome": 8626000000, "otherOperatingExpenses": None, "interestExpense": 733000000, "extraordinaryItems": None, "nonRecurring": None, "otherItems": None, "incomeTaxExpense": 1586000000, "totalRevenue": 41863000000, "totalOperatingExpenses": 0, "costOfRevenue": 16465000000, "totalOtherIncomeExpenseNet": -592000000, "discontinuedOperations": 101000000, "netIncomeFromContinuingOps": 6550000000, "netIncomeApplicableToCommonShares": 6527000000}}, {"2015-12-31": {"researchDevelopment": None, "effectOfAccountingCharges": None, "incomeBeforeTax": 9605000000, "minorityInterest": 210000000, "netIncome": 7351000000, "sellingGeneralAdministrative": 18084000000, "grossProfit": 26812000000, "ebit": 10461000000, "operatingIncome": 8728000000, "otherOperatingExpenses": None, "interestExpense": 856000000, "extraordinaryItems": None, "nonRecurring": None, "otherItems": None, "incomeTaxExpense": 2239000000, "totalRevenue": 44294000000, "totalOperatingExpenses": 0, "costOfRevenue": 17482000000, "totalOtherIncomeExpenseNet": 1244000000, "discontinuedOperations": 101000000, "netIncomeFromContinuingOps": 7366000000, "netIncomeApplicableToCommonShares": 7351000000}}]}} ''' comp_ratio_data_dict = json.dumps( company_data_provider_object.return_data_for_stock()) return comp_ratio_data_dict
class Company(object): def __init__(self, ticker): self.ticker = ticker.upper() self.financials = YahooFinancials(ticker) self.timeframe = 'annual' self.balance_sheet = None self.income_statement = None self.cash_flow_statement = None self.key_statistics = None self.historical_eps = None self.price_data = None self.new_corporate_tax_rate = 0.21 self.old_corporate_tax_rate = 0.35 self.risk_free_ror = 0.025 self.market_ror = 0.098 def __set_balance_sheet(self): if str(type(self.balance_sheet)) == "<class 'NoneType'>": try: self.balance_sheet = self.financials.get_financial_stmts( self.timeframe, 'balance')['balanceSheetHistory'][self.ticker] self.balance_sheet = self.__clean_statement_timestamp( self.balance_sheet) except: return None def __set_income_statement(self): if str(type(self.income_statement)) == "<class 'NoneType'>": try: self.income_statement = self.financials.get_financial_stmts( self.timeframe, 'income')['incomeStatementHistory'][self.ticker] self.income_statement = self.__clean_statement_timestamp( self.income_statement) except: return None def __set_cash_flow_statement(self): if str(type(self.cash_flow_statement)) == "<class 'NoneType'>": try: self.cash_flow_statement = self.financials.get_financial_stmts( self.timeframe, 'cash')['cashflowStatementHistory'][self.ticker] self.cash_flow_statement = self.__clean_statement_timestamp( self.cash_flow_statement) except: return None def __set_key_statistics(self): if str(type(self.key_statistics)) == "<class 'NoneType'>": try: self.key_statistics = self.financials.get_key_statistics_data() except: return None def __set_historical_eps(self): if str(type(self.historical_eps)) == "<class 'NoneType'>": url = 'https://www.nasdaq.com/earnings/report/{}'.format( self.ticker) page = requests.get(url) if page.status_code == 200: soup = BeautifulSoup(page.text, 'html.parser') eps_list = [] td = soup.find_all('td') counter = 0 for i in td[2::5]: try: test = float(i.get_text()) counter += 1 except: break for i in range(counter * 5): eps_list.append(list(soup.find_all('td'))[i].get_text()) self.historical_eps = pd.DataFrame({ 'textdate': eps_list[0::5], 'timestamp': eps_list[1::5], 'eps': eps_list[2::5], 'consensus_eps': eps_list[3::5], 'surprise': eps_list[4::5] }) self.historical_eps = self.historical_eps.iloc[::-1] self.historical_eps.reset_index(inplace=True, drop=True) else: return None def __set_price_data(self): if str(type(self.price_data)) == "<class 'NoneType'>": try: self.price_data = pd.DataFrame( self.financials.get_historical_price_data( '1800-01-01', str(datetime.now())[:10], 'daily')[self.ticker]['prices']) except: pass def __clean_statement_timestamp(self, statement): for i in statement: for j in i.keys(): i[j[:4]] = i.pop(j) return statement def __get_specific_year(self, statement, year): for i in statement: if str(list(i.keys())[0]) == str(year): return i['{}'.format(year)] def __json_to_dataframe(self, data): columns = [] for i in data: for j in i.keys(): columns.append(j) df = pd.DataFrame(data[0]) for i in range(len(columns)): df[columns[i]] = pd.DataFrame(data[i]) df = df[df.columns[::-1]] return df def set_risk_free_ror(self, risk_free_ror): self.risk_free_ror = risk_free_ror def set_market_ror(self, market_ror): self.market_ror = market_ror def check_risk_free_ror(self): return self.risk_free_ror def check_market_ror(self): return self.market_ror def check_old_corporate_tax_rate(self): return self.old_corporate_tax_rate def check_new_corporate_tax_rate(self): return self.new_corporate_tax_rate def get_balance_sheet(self): self.__set_balance_sheet() df = self.__json_to_dataframe(self.balance_sheet) return df def get_income_statement(self): self.__set_income_statement() df = self.__json_to_dataframe(self.income_statement) return df def get_cash_flow_statement(self): self.__set_cash_flow_statement() df = self.__json_to_dataframe(self.cash_flow_statement) return df def get_key_statistics(self): self.__set_key_statistics() ser = pd.Series(self.key_statistics[self.ticker]) return ser def get_historical_eps(self): self.__set_historical_eps() return self.historical_eps def get_price_data(self): self.__set_price_data() return self.price_data def check_ticker(self): return self.ticker def revenue(self, year): self.__set_income_statement() try: return self.__get_specific_year(self.income_statement, year)['totalRevenue'] except: return None def total_expenses(self, year): self.__set_income_statement() self.__set_cash_flow_statement() try: operating_expenses = self.__get_specific_year( self.income_statement, year)['totalOperatingExpenses'] interest = self.__get_specific_year(self.income_statement, year)['interestExpense'] tax = self.__get_specific_year(self.income_statement, year)['incomeTaxExpense'] depreciation = self.__get_specific_year(self.cash_flow_statement, year)['depreciation'] return abs(operating_expenses) + abs(interest) + abs(tax) + abs( depreciation) except: return None def operating_expenses(self, year): self.__set_income_statement() try: return self.__get_specific_year(self.income_statement, year)['totalOperatingExpenses'] except: return None def outstanding_shares(self): self.__set_key_statistics() try: return self.get_key_statistics()['sharesOutstanding'] except: return None def share_price(self): self.__set_price_data() try: return float(self.price_data[-1:]['close']) except: return None def market_value(self): try: return self.share_price() * self.outstanding_shares() except: return None def liquid_assets(self, year): self.__set_balance_sheet() try: return self.__get_specific_year( self.balance_sheet, year)['cash'] + self.__get_specific_year( self.balance_sheet, year)['shortTermInvestments'] except: return None def total_debt(self, year): self.__set_balance_sheet() try: return self.__get_specific_year( self.balance_sheet, year)['shortLongTermDebt'] + self.__get_specific_year( self.balance_sheet, year)['longTermDebt'] except: return None def tax(self, year): self.__set_income_statement() try: return abs( self.__get_specific_year(self.income_statement, year)['incomeTaxExpense']) except: return None def interest(self, year): self.__set_income_statement() try: return self.__get_specific_year(self.income_statement, year)['interestExpense'] except: return None def depreciation(self, year): self.__set_cash_flow_statement() try: return self.__get_specific_year(self.cash_flow_statement, year)['depreciation'] except: return None def cost_of_revenue(self, year): self.__set_income_statement() try: return self.__get_specific_year(self.income_statement, year)['costOfRevenue'] except: return None def total_receivables(self, year): self.__set_balance_sheet() try: return self.__get_specific_year(self.balance_sheet, year)['netReceivables'] except: return None def total_liabilities(self, year): self.__set_balance_sheet() try: return self.__get_specific_year(self.balance_sheet, year)['totalLiab'] except: return None def total_assets(self, year): self.__set_balance_sheet() try: return self.__get_specific_year(self.balance_sheet, year)['totalAssets'] except: return None def total_capital(self, year): self.__set_balance_sheet() try: return self.__get_specific_year( self.balance_sheet, year)['totalStockholderEquity'] + self.total_debt(year) except: return None def total_equity(self, year): try: return self.total_assets(year) - self.total_liabilities(year) except: return None def capital_expenditures(self, year): self.__set_cash_flow_statement() try: return self.__get_specific_year(self.cash_flow_statement, year)['capitalExpenditures'] except: return None def net_income(self, year): self.__set_income_statement() try: return self.__get_specific_year(self.income_statement, year)['netIncome'] except: return None def gross_profit(self, year): self.__set_income_statement() try: return self.__get_specific_year(self.income_statement, year)['grossProfit'] except: return None def earnings_per_share(self): try: return self.financials.get_earnings_per_share() except: return None def pe_ratio(self): try: return self.financials.get_pe_ratio() except: return None def enterprise_value(self): try: return self.get_key_statistics()['enterpriseValue'] except: return None def ebit(self, year): self.__set_income_statement() try: return self.__get_specific_year(self.income_statement, year)['ebit'] except: return None def ebitda(self, year): try: temp_net_income = abs(self.net_income(year)) temp_tax = abs(self.tax(year)) temp_interest = abs(self.interest(year)) temp_depreciation = abs(self.depreciation(year)) return temp_net_income + temp_tax + temp_interest + temp_depreciation except: return None def quick_ratio(self, year): try: temp_liquid_assets = abs(self.liquid_assets(year)) temp_receivables = abs(self.total_receivables(year)) temp_liabilities = abs(self.total_liabilities(year)) return (temp_liquid_assets + temp_receivables) / temp_liabilities except: return None def income_continuing_operations_margin(self, year): try: temp_ebit = self.ebit(year) temp_revenue = abs(self.revenue(year)) return temp_ebit / temp_revenue except: return None def net_margin(self, year): try: temp_net_income = self.net_income(year) temp_revenue = self.revenue(year) return temp_net_income / temp_revenue except: return None def return_on_assets(self, year): try: ending_year = year beginning_year = year - 1 temp_net_income = self.net_income(year) beginning_total_assets = abs(self.total_assets(beginning_year)) ending_total_assets = abs(self.total_assets(ending_year)) return temp_net_income / ( (beginning_total_assets + ending_total_assets) / 2) except: return None def return_on_capital(self, year): try: ending_year = year beginning_year = year - 1 if ending_year >= 2018: temp_ebit = self.ebit(year) temp_tax_rate = self.new_corporate_tax_rate beginning_total_capital = abs( self.total_capital(beginning_year)) ending_total_capital = abs(self.total_capital(ending_year)) return (temp_ebit * (1 - temp_tax_rate)) / ( (beginning_total_capital + ending_total_capital) / 2) elif ending_year < 2018: temp_ebit = self.ebit(year) temp_tax_rate = self.old_corporate_tax_rate beginning_total_capital = abs( self.total_capital(beginning_year)) ending_total_capital = abs(self.total_capital(ending_year)) return (temp_ebit * (1 - temp_tax_rate)) / ( (beginning_total_capital + ending_total_capital) / 2) except: return None def return_on_equity(self, year): try: temp_ebit = self.ebit(year) temp_total_equity = abs(self.total_equity(year)) return temp_ebit / temp_total_equity except: return None def cash_flow_operations(self, year): try: temp_revenue = abs(self.revenue(year)) temp_operating_expenses = abs(self.operating_expenses(year)) return temp_revenue - temp_operating_expenses except: return None def free_cash_flow(self, year): try: if year >= 2018: temp_cfo = self.cash_flow_operations(year) temp_interest = self.interest(year) temp_tax_rate = self.new_corporate_tax_rate temp_capex = self.capital_expenditures(year) return temp_cfo + (temp_interest * (1 - temp_tax_rate)) - temp_capex elif year < 2018: temp_cfo = self.cash_flow_operations(year) temp_interest = self.interest(year) temp_tax_rate = self.old_corporate_tax_rate temp_capex = self.capital_expenditures(year) return temp_cfo + (temp_interest * (1 - temp_tax_rate)) - temp_capex except: return None def beta(self): try: return self.financials.get_beta() except: return None def cost_of_equity(self): try: return self.risk_free_ror + ( self.beta() * (self.market_ror - self.risk_free_ror)) except: return None def gross_profit_margin(self, year): try: return (self.revenue(year) - self.cost_of_revenue(year)) / self.revenue(year) except: return None def operating_profit_margin(self, year): try: return self.ebit(year) / self.revenue(year) except: return None def net_profit_margin(self, year): try: return self.net_income(year) / self.revenue(year) except: return None def short_ratio(self): try: return self.get_key_statistics()['shortRatio'] except: return None
# Extract company tickers from the data frame and turn them into a list companyTickers = companiesData['Ticker'].tolist() # print(companyTickers) pe_ratios = [] market_caps = [] dividend_yields = [] sectors = [] industries = [] names = [] # For each company in the S&P 500 list, extract its PE ratio and market cap and add each of them to its respective list for ticker in companyTickers: yahoo_financials = YahooFinancials(ticker) print('Downloading data for ' + ticker + '...') pe_ratios.append(yahoo_financials.get_pe_ratio()) market_caps.append(yahoo_financials.get_market_cap()) try: dividend_yields.append( str(format(yahoo_financials.get_dividend_yield() * 100, ".2f")) + '%') except: dividend_yields.append(str(yahoo_financials.get_dividend_yield())) sectors.append(yahoo_data.getSector(ticker)) industries.append(yahoo_data.getIndustry(ticker)) names.append(yahoo_data.getName(ticker)) companiesData['Name'] = names companiesData['Sector'] = sectors companiesData['Industry'] = industries companiesData['P/E'] = pe_ratios