def add_quick_summary(self): quick_summary_md = "" quick_summary_md += f"# Quick summary about {self.name}\n\n" quick_summary_md += "This is the quick summary:\n\n" try: status, messages, _ = self.is_good_business() quick_summary_md += f"{self.name} is a good business? \nAnswer: {status}\n\n" if status == False: quick_summary_md += f"Reason:, {messages}\n\n" except: pass for item in [ "sector", "longBusinessSummary", "country", "city", "trailingPE", "priceToSalesTrailing12Months", "fiftyTwoWeekHigh", "fiftyTwoWeekLow", "pegRatio", "shortPercentOfFloat", "next_earnings_date" ]: try: tmp_str = f"- {item}: {self.attribute[item]}\n\n" quick_summary_md += tmp_str except: pass info = si.get_stats_valuation(self.name) quick_summary_md += info.to_markdown() + "\n\n" info = si.get_analysts_info(self.name) quick_summary_md += info["Growth Estimates"].to_markdown() + "\n\n" #quick_summary_md += info["Revenue Estimate"].to_markdown() + "\n\n" # finally, add it into markdown_notes self.markdown_notes += quick_summary_md return quick_summary_md
def fair_value(ticker, years=1, wish_return=0.4): netincome = Decimal(si.get_income_statement(ticker)[si.get_income_statement(ticker).columns[0]].netIncome) shares_outstanding = number_encoder(str(si.get_stats(ticker)["Value"][9])) current_eps = netincome / shares_outstanding all_growth_rates = [Decimal(x[:-1]) for x in si.get_analysts_info(ticker)["Revenue Estimate"][ si.get_analysts_info(ticker)["Revenue Estimate"].columns[ :-2]].iloc[5][1:].dropna()] growth_rate = sum(all_growth_rates) / len(all_growth_rates) / 100 projected_eps = current_eps * (1 + growth_rate) ** years projected_pe_ratio = Decimal(si.get_live_price(ticker)) / projected_eps forwarded_pe_ratio = Decimal(si.get_stats_valuation(ticker)[si.get_stats_valuation(ticker).columns[1]][2]) * ( 1 + growth_rate) ** (years - 1) return (forwarded_pe_ratio * projected_eps) / Decimal(1 + wish_return)
def plot_valuation(self): stock_name = self.name valuation = si.get_stats_valuation(stock_name) valuation = valuation.set_index('Unnamed: 0') valuation = valuation.applymap(algotrading.stock._convert_to_numeric) valuation = valuation.T valuation = valuation.sort_index() tmp = plt.rcParams["figure.figsize"] plt.rcParams["figure.figsize"] = (20, 20) valuation[[ 'Trailing P/E', 'Forward P/E 1', 'PEG Ratio (5 yr expected) 1', 'Price/Sales (ttm)', 'Price/Book (mrq)' ]].plot(subplots=True, grid=True) plt.rcParams["figure.figsize"] = tmp return valuation
def __init__(self, a_ticker: str = 'CNI'): self.__ticker = a_ticker self.__quote = si.get_quote_table(a_ticker) self.__val = si.get_stats_valuation(a_ticker) self.__val = self.__val.iloc[:, :2] self.__val.columns = ['Attribute', 'Recent'] self.__pe_ratio = float(self.__val[self.__val.Attribute.str.contains( 'Trailing P/E')].iloc[0, 1]) self.__fpe_ratio = float(self.__val[self.__val.Attribute.str.contains( 'Forward P/E')].iloc[0, 1]) self.__peg_ratio = float( self.__val[self.__val.Attribute.str.contains('PEG')].iloc[0, 1]) self.__price_to_book = float(self.__val[ self.__val.Attribute.str.contains('Price/Book')].iloc[0, 1]) self.__price_to_earn = float(self.__val[ self.__val.Attribute.str.contains('Trailing P/E')].iloc[0, 1]) self.__price_to_sales = float(self.__val[ self.__val.Attribute.str.contains('Price/Sales')].iloc[0, 1])
def get_valuation_stats(self): selected = { 'Market Cap (intraday) 5': 'Market Cap', 'Price/Sales (ttm)': 'Price/Sales (ttm)', 'Trailing P/E': 'P/E (trailing)', 'PEG Ratio (5 yr expected) 1': 'PEG (5 yr expected)', 'Price/Book (mrq)': 'Price/Book', } df = si.get_stats_valuation(self.tinker) df = df.set_index(df.columns[0]) new_df = pd.DataFrame(index=selected.keys()).fillna('na') for idx in new_df.index: try: value = df.loc[idx, df.columns[0]] except Exception as e: value = 'N/A' new_df.loc[idx, self.tinker] = value # print(df.index) return new_df
table.index = ticker_index table1 = table[ratio_stat] time.sleep(60 * 20) table = pd.DataFrame() tickers = ticker_index.copy() new_index = [] retry_ticker = [] count = 0 for p in tickers: # print(p) try: extra_ratio = si.get_stats_valuation(p) extra_ratio = extra_ratio.iloc[:, 0:2] extra_ratio.index = extra_ratio['Unnamed: 0'] extra_ratio = extra_ratio.drop(labels='Unnamed: 0', axis=1) new_table = extra_ratio.T table = table.append(new_table) #Table having Data about the company new_index.append(p) time.sleep(10) except: count = count + 1 print('Bad Ticker {}: {}'.format(count, p)) retry_ticker.append(p) time.sleep(60 * 5) if len(retry_ticker) > 0: time.sleep(60 * 20)
def Stock(): page_bg_img = ''' <style> body { background-image: url("https://images.pexels.com/photos/1353938/pexels-photo-1353938.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=1000"); background-size: cover; } </style> ''' st.markdown(page_bg_img, unsafe_allow_html=True) symbols = 'https://raw.githubusercontent.com/Moly-malibu/Stocks/main/bxo_lmmS1.csv' df = pd.read_csv(symbols) st.markdown( "<h1 style='text-align: center; color: #002966;'>Financial Information</h1>", unsafe_allow_html=True) st.write(""" Financial information from the companies and Stocks by years! """) start = st.sidebar.date_input("Date to Analysis") st.sidebar.subheader("Index") tickerSymbol2 = st.sidebar.selectbox('Stocks by Company', (df['Symbol'])) tickerData = yf.Ticker(tickerSymbol2) tickerDf = tickerData.history(period='id', start=start, end=None) def get_symbol(symbol): url = "http://d.yimg.com/autoc.finance.yahoo.com/autoc?query={}®ion=1&lang=en".format( symbol) result = requests.get(url).json() for x in result['ResultSet']['Result']: if x['symbol'] == symbol: return x['name'] company_name = get_symbol(tickerSymbol2.upper()) st.write("""# Analysis of """, company_name) company = yf.Ticker(tickerSymbol2) # st.write(company.info) company_general = st.sidebar.checkbox("Company Information") if company_general: st.markdown( "<h1 style='text-align: center; color: #002966;'>General Information</h1>", unsafe_allow_html=True) st.write('***Sector:*** ', company.info["sector"]) st.write('***Industry:*** ', company.info["industry"]) st.write('***Phone:*** ', company.info["phone"]) st.write('***Address: ***', company.info["address1"]) st.write('***City: ***', company.info["city"]) st.write('***Country: ***', company.info["country"]) st.write('***Web: ***', company.info["website"]) st.write('***Business Summary:*** ', '\n', company.info["longBusinessSummary"]) st.write('***Job Generator***', company.info["fullTimeEmployees"]) company_hist = st.sidebar.checkbox("Company Shares Asigned") if company_hist: st.markdown( "<h1 style='text-align: center; color: #002966;'>Company Shares Asigned </h1>", unsafe_allow_html=True) display_histo = company.major_holders display_mh = company.history(period='max') if display_histo.empty == True: st.write("No data available") else: st.write(display_histo) company_recomend = st.sidebar.checkbox("Stocks Recommendations") if company_recomend: st.markdown( "<h1 style='text-align: center; color: #002966;'>Stocks Recommendatios</h1>", unsafe_allow_html=True) display_recomend = company.recommendations if display_recomend.empty == True: st.write("No data available") else: st.write(display_recomend) company_job = st.sidebar.checkbox("Action and Split") if company_job: st.markdown( "<h1 style='text-align: center; color: #002966;'>History Actions and Split</h1>", unsafe_allow_html=True) data = {} list = [(tickerSymbol2)] for ticker in list: ticker_object = yf.Ticker(ticker) temp = pd.DataFrame.from_dict(ticker_object.info, orient='index') temp.reset_index(inplace=True) temp.columns = ['Attribute', 'Recent'] data[ticker] = temp merge = pd.concat(data) merge = merge.reset_index() del merge['level_1'] merge.columns = ['Ticker', 'Attribute', 'Recent'] split = company.history(period='max', interval='1wk') st.sidebar.checkbox("Stock level") st.write('Company History', split) company_stadistic = st.sidebar.checkbox("Statistics") if company_stadistic: st.markdown( "<h1 style='text-align: center; color: #002966;'>Statistics</h1>", unsafe_allow_html=True) data = yf.download((tickerSymbol2), start=start, end=None, group_by='tickers') table = st.table(data.describe()) company_hist = st.sidebar.checkbox("Status of Evaluation") if company_hist: st.markdown( "<h1 style='text-align: center; color: #002966;'>Status of Evaluation</h1>", unsafe_allow_html=True) display_evaluation = si.get_stats_valuation(tickerSymbol2) if display_evaluation.empty == True: st.write("No data available") else: st.write(display_evaluation)
import asyncio import pandas import yahoo_fin.stock_info as si async def get_fundamental_indicators_for_company(config, company): company.fundmantal_indicators = {} # Statistics Valuation keys = { 'Market Cap (intraday) 5': 'MarketCap', 'Price/Sales (ttm)': 'PS', 'Trailing P/E': 'PE', 'PEG Ratio (5 yr expected) 1': 'PEG', 'Price/Book (mrq)': 'PB' } data = si.get_stats_valuation(company.symbol) get_data_item(company.fundmantal_indicators, data, keys) # Income statement and Balance sheet data = get_statatistics(company.symbol) get_data_item(company.fundmantal_indicators, data, { 'Profit Margin': 'ProfitMargin', 'Operating Margin (ttm)': 'OperMargin', 'Current Ratio (mrq)': 'CurrentRatio', 'Payout Ratio 4': 'DivPayoutRatio' }) get_last_data_item(company.fundmantal_indicators, data, { 'Return on assets': 'ROA',
def get_stats(self, ticker): stats = yahoo.get_stats_valuation(ticker) return (stats)
def my_valuation(ticker): # Quote table try: key_attributes_quote = [ 'PE Ratio (TTM)', 'Beta (5Y Monthly)', '1y Target Est', 'EPS (TTM)', 'Previous Close', 'Market Cap' ] quote = si.get_quote_table(ticker) attr_results = [] for attribute in key_attributes_quote: attr_results.append(quote[attribute]) attr_results_df = pd.DataFrame([attr_results], columns=key_attributes_quote) attr_results_df['Ticker'] = ticker # Stats table stats_table = si.get_stats(ticker) stats_table = stats_table.iloc[[22, 24, 46, 47, 48], :].transpose() stats_table.columns = stats_table.iloc[0, :] stats_table = stats_table.iloc[1, :] stats_table = pd.DataFrame(stats_table) stats_table = stats_table.transpose().reset_index(drop=True) # Stats valuation val = si.get_stats_valuation(ticker).transpose() val.columns = val.iloc[0, :] val = val.iloc[1, :] val = pd.DataFrame(val) val = val.transpose().reset_index(drop=True) # Analysts recommendation lhs_url = 'https://query2.finance.yahoo.com/v10/finance/quoteSummary/' rhs_url = '?formatted=true&crumb=swg7qs5y9UP&lang=en-US®ion=US&' 'modules=upgradeDowngradeHistory,recommendationTrend,' 'financialData,earningsHistory,earningsTrend,industryTrend&' 'corsDomain=finance.yahoo.com' url = lhs_url + ticker + rhs_url headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' } r = requests.get(url, headers=headers) if not r.ok: recommendation = 6 try: result = r.json()['quoteSummary']['result'][0] recommendation = result['financialData']['recommendationMean'][ 'fmt'] except: recommendation = 6 stats_table['Recommendation'] = recommendation # Adding business summary comp_ticker = yf.Ticker(ticker) stats_table['Company Summary'] = comp_ticker.info[ 'longBusinessSummary'] # join horizontal_stack = pd.concat([stats_table, val, attr_results_df], axis=1) # Changing columns order cols = horizontal_stack.columns.tolist() cols = cols[-1:] + cols[:-1] horizontal_stack = horizontal_stack[cols] return horizontal_stack except: return pd.DataFrame()
import yahoo_fin.stock_info as si import pandas as pd quote = si.get_quote_table("aapl") df = pd.DataFrame([quote]) print (df.T) # get list of Dow tickers dow_list = si.tickers_dow() # Get data in the current column for each stock's valuation table dow_stats = {} for ticker in dow_list: temp = si.get_stats_valuation(ticker) temp = temp.iloc[:,:2] temp.columns = ["Attribute", "Value"] dow_stats[ticker] = temp # combine all the stats valuation tables into a single data frame combined_stats = pd.concat(dow_stats) combined_stats = combined_stats.reset_index() del combined_stats["level_1"] # update column names combined_stats.columns = ["Ticker", "Attribute", "Value"] print(combined_stats) dow_extra_stats = {} for ticker in dow_list: dow_extra_stats[ticker] = si.get_stats(ticker)
def getStatsValuation(ticker): return si.get_stats_valuation(ticker)
import yahoo_fin.stock_info as si import pandas as pd import pprint quote = si.get_quote_table("aapl") quote["PE Ratio (TTM)"] val = si.get_stats_valuation("aapl") val = val.iloc[:,:2] val.columns = ["Attribute", "Recent"] val = float(val[val.Attribute.str.contains("Trailing P/E")].iloc[0,1]) pprint.pprint(quote)
if Company_name(symbol) == None: print('Company not found') print('') col += 1 continue print('Company: ' + Company_name(symbol)) print('Collecting Data: ', end = '') start_time = time.time() Balance_Sheet = si.get_balance_sheet(symbol) Income_Statement = si.get_income_statement(symbol) Cash_Flow = si.get_cash_flow(symbol) Quote = si.get_quote_table(symbol) Valuation_Stats = si.get_stats_valuation(symbol) print(round(time.time() - start_time,2), 'seconds') ##column 2 print('Insert Data: ', end = '') start_time = time.time() total_assets = int(Balance_Sheet.loc[list(Balance_Sheet.iloc[:,0]).index('Total Assets')][1]) total_debt = int(Balance_Sheet.loc[list(Balance_Sheet.iloc[:,0]).index('Total Debt')][1]) try: ebitda_anual = int(Income_Statement.loc[list(Income_Statement.iloc[:,0]).index('Normalized EBITDA')][2]) except: ebitda_anual = 'Fail' if ebitda_anual == 'Fail': Debt_Ebitda = 'Fail' else: Debt_Ebitda = total_debt / ebitda_anual try: operating_income = int(Income_Statement.loc[list(Income_Statement.iloc[:,0]).index('Operating Income')][1])
'What Percentage of Total Revenue Comes From that Country? (1=100%, and if its a developed country write 1):' )) WAM = int( 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), "$")
def update_stats_valuation(self, symbol): stats_valuation = si.get_stats_valuation(symbol).to_dict(orient="dict") self.update(symbol, stats_valuation, 'Stocks', 'Stats_Valuation')
from selenium import webdriver from selenium.webdriver.common.keys import Keys import yahoo_fin.stock_info as si df = pd.read_csv(r'C:/Users/91855/Desktop/oil and gas/oil.csv') df # In[ ]: count = -1 for company in df['compsymbol']: count = count + 1 Market_Cap = [] Enterprise_Value = [] EBITDA_LIST_VALUES = [] data_stats_valuation = si.get_stats_valuation(company) market_cap = data_stats_valuation.iloc[0] market_cap_final = market_cap[1] Market_Cap.append(market_cap_final) print('-----', company) print('marktcp', Market_Cap) enterprice_value = data_stats_valuation.iloc[1] enterprice_value_final = enterprice_value[1] Enterprise_Value.append(enterprice_value_final) print('enterpval', Enterprise_Value) mydata_stats = si.get_stats(company) row_touse = mydata_stats.loc[mydata_stats['Attribute'] == 'EBITDA'] ebitda_row = row_touse.iloc[0] final_ebitda = ebitda_row[1] EBITDA_LIST_VALUES.append(final_ebitda) print('eb', EBITDA_LIST_VALUES)
df = pd.read_csv(f'stock_data/{ticker}.csv', index_col=0) # Load dataframe from csv file moving_averages = [ 150, 200 ] #these numbers can be added more, 100 days, 150 days .... for ma in moving_averages: df['SMA_' + str(ma)] = round( df['Adj Close'].rolling(window=ma).mean(), 2 ) #Aggregate the values over a timeframe and apply mean function and round to 2 decimal places. latest_price = df['Adj Close'][-1] pe_ratio = float(si.get_quote_table(ticker) ['PE Ratio (TTM)']) # Trailing 12 Months (TTM) # To add your own criteria use print(si.get_quote_table(ticker)) which will lead to a dictionary for all the available parameters. peg_ratio = float(si.get_stats_valuation(ticker)[1][4]) # To add your own criteria use print(si.get_stats_valuation(ticker)) which will lead to all the available parameters. moving_average_150 = df['SMA_150'][-1] moving_average_200 = df['SMA_200'][-1] low_52week = round( min(df['Low'][-(52 * 5):]), 2) # 5 days in a week for 52 weeks, so get the lowest out of all. high_52week = round(max(df['High'][-(52 * 5):]), 2) score = round(best_performers[best_performers['Ticker'] == ticker] ['Score'].tolist()[0]) # get instance where the ticker symbol is ticker get the score value and then turn it to a list and pick the first value condition_1 = latest_price > moving_average_150 > moving_average_200 condition_2 = latest_price >= ( 1.1 * low_52week