def get_df_1(ticker): yahoo_financials = YahooFinancials(ticker) stats_1 = yahoo_financials.get_key_statistics_data() df_1 = pd.DataFrame(stats_1).loc[['enterpriseValue'], :].transpose() df_1['marketCap'] = [yahoo_financials.get_market_cap()] return df_1
def calculate_ps_metrics(stock): yahoo_stock = YahooFinancials(stock.symbol) market_cup = yahoo_stock.get_market_cap() if stock.target_avg_sales: multiplier = FilteredStocks.get_multiplier( stock.target_avg_sales[-1]) target_avg_sales = float(stock.target_avg_sales[:-1]) * multiplier try: stock.price_to_sell_ratio = round( market_cup / target_avg_sales, 2) stock.ps_to_growth_ratio = round( stock.price_to_sell_ratio / float(stock.target_sales_growth[:-1]), 2) ev = (yahoo_stock.get_key_statistics_data()[stock.symbol] ["enterpriseValue"]) profit_margins = (yahoo_stock.get_key_statistics_data()[ stock.symbol]["profitMargins"]) stock.ev_to_sell_ratio = round(ev / target_avg_sales, 2) stock.gross_margins = round( yahoo_stock.get_gross_profit() / yahoo_stock.get_total_revenue() * 100, 2) ev_to_profit_ratio = round( stock.ev_to_sell_ratio / profit_margins, 2) print("gross_margins : " + str(stock.gross_margins)) print("ev sells : " + str(stock.ev_to_sell_ratio)) print("ev / earnings : " + str(ev_to_profit_ratio)) print("ps_to_growth : " + str(stock.ps_to_growth_ratio)) print("sales targets:" + str(stock.target_sales_growth[:-1])) print("growth adujsted ev / sells: " + str( round( stock.ev_to_sell_ratio / float(stock.target_sales_growth[:-1]), 2))) except Exception as e: print(str(e))
def calc_b2m(tickers): total = {} for index, ticker in enumerate(tickers): if index % 1 == 0: print('Fetching B2M Data for %d out of %d' % (index, len(tickers))) yahoo_financials = YahooFinancials(ticker) total[ticker] = yahoo_financials.get_book_value( ) / yahoo_financials.get_market_cap() return total
def portfolio(request, portfolio_pk): portfolio = Portfolio.objects.get(pk=portfolio_pk) check_ownership(request, portfolio) stock_not_found = False quote_name = request.POST.get('quote', None) if quote_name: quote_name = quote_name.upper() yf = YahooFinancials(quote_name) exchange = yf.get_stock_exchange() try: stock = Stock.objects.get(name=quote_name) except Stock.DoesNotExist: stock = Stock.objects.create( name=quote_name, stock_exchange=yf.get_stock_exchange(), market_cap=convert_number(yf.get_market_cap()), last_price=convert_number(yf.get_current_price()) ) PortfolioStock.objects.get_or_create(stock=stock, portfolio=portfolio) stocks = PortfolioStock.objects.filter(portfolio=portfolio).order_by("-stock__value_score") operations = Operation.objects.filter(portfolio_stock__portfolio=portfolio)[0:10] total_value, total_spent, profit = portfolio.balance_sheet() if total_spent != 0: profit_purcent = round(profit / total_spent * 100, 2) else: profit_purcent = 0 total_cash_value = total_value + portfolio.cash c = { 'quote_name': quote_name, 'stock_not_found': stock_not_found, 'portfolio':portfolio, 'stocks': stocks, 'operations':operations, 'total_value':total_value, 'total_spent':total_spent, 'profit':profit, 'profit_purcent':profit_purcent, 'total_cash_value':total_cash_value, } c.update(csrf(request)) return render_to_response('portfolio.html', c)
async def stock(ctx, ticker, info): yahoo_financials = YahooFinancials(ticker) if (info == "current"): await ctx.send(ticker.upper() + " current share price: $" + str(yahoo_financials.get_current_price())) if (info == "open"): await ctx.send(ticker.upper() + " share price at opening: $" + str(yahoo_financials.get_open_price())) if (info == "prevclose"): await ctx.send(ticker.upper() + " share priced at previous close: $" + str(yahoo_financials.get_prev_close_price())) if (info == "cap"): await ctx.send(ticker.upper() + " market cap: $" + str("{:,}".format(yahoo_financials.get_market_cap()))) if (info == "dailylow"): await ctx.send(ticker.upper() + " daily low: $" + str(yahoo_financials.get_daily_low())) if (info == "dailyhigh"): await ctx.send(ticker.upper() + " daily high: $" + str(yahoo_financials.get_daily_high())) if (info == "yearlow"): await ctx.send(ticker.upper() + " yearly low: $" + str(yahoo_financials.get_yearly_low())) if (info == "yearhigh"): await ctx.send(ticker.upper() + " yearly high: $" + str(yahoo_financials.get_yearly_high())) if (info == "rev"): await ctx.send(ticker.upper() + " total revenue: $" + str("{:,}".format(yahoo_financials.get_total_revenue())) ) if (info == "net"): await ctx.send(ticker.upper() + " net income: $" + str("{:,}".format(yahoo_financials.get_net_income()))) if (info == "op"): await ctx.send( ticker.upper() + " operating income: $" + str("{:,}".format(yahoo_financials.get_operating_income()))) if (info == "profit"): await ctx.send(ticker.upper() + " gross profit: $" + str("{:,}".format(yahoo_financials.get_gross_profit())))
def create_retrieve_thread(tickers, metric, file_name, data_dict, batch_no): start_loop = time.time() print( f"Batch/thread {batch_no + 1}: Tickers to be retrieved are: {tickers}") yahoo_financials = YahooFinancials(tickers) if metric == "balance": print(f"Retrieving annual balance sheets from Yahoo Finance...") financial_statement = yahoo_financials.get_financial_stmts( 'annual', 'balance')['balanceSheetHistory'] elif metric == "income": print( f"Retrieving annual income statement history from Yahoo Finance..." ) financial_statement = yahoo_financials.get_financial_stmts( 'annual', 'income')['incomeStatementHistory'] elif metric == "cap": print(f"Retrieving market cap information from Yahoo Finance...") financial_statement = yahoo_financials.get_market_cap() else: print("Metric entered is not recognized.") financial_statement = {} dict_lock.acquire() data_dict.update(financial_statement) end_loop = time.time() print(f"Saving batch {batch_no + 1} to JSON file...") json.dump(data_dict, open(file_name + '.json', 'w')) dict_lock.release() print( f"Time elapsed for batch {batch_no + 1}: {end_loop - start_loop}, metric: {metric}" ) print()
def Statement(): page_bg_img = ''' <style> body { background-image: url("https://images.pexels.com/photos/2748757/pexels-photo-2748757.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) ticker = st.sidebar.selectbox('Stocks by Company', (df['Symbol'])) tickerData = YahooFinancials(ticker) 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(ticker.upper()) st.write("""# Analysis of """, company_name) company = yf.Ticker(ticker) # st.write(company.info) company_general = st.sidebar.checkbox("Financial Ratio") if company_general: st.markdown( "<h1 style='text-align: center; color: #002966;'>Financial Ratios</h1>", unsafe_allow_html=True) st.write('***Payout Ratio:*** ', company.info["payoutRatio"]) st.write('***Trailing Annual Dividend Yield:*** ', company.info["trailingAnnualDividendYield"]) st.write('***Dividend Rate:*** ', company.info["dividendRate"]) st.write('***Profit Margins: ***', company.info["profitMargins"]) st.write('***Peg Ratio: ***', company.info["pegRatio"]) yahoo_financials = YahooFinancials(ticker) marketcap = yahoo_financials.get_market_cap() price_to_sales = yahoo_financials.get_current_price() dividend_yield = yahoo_financials.get_dividend_yield() income_balance = si.get_income_statement(ticker) transpose_income = income_balance.transpose() balance_income = si.get_balance_sheet(ticker) transpose_balance = balance_income.transpose() st.write("""**Dividends**""", company.dividends) income = si.get_income_statement(ticker) transpose = income.transpose() interest_coverage1 = transpose['operatingIncome'] interest_coverage2 = transpose['interestExpense'] st.write( '***Interest Coverage:*** Operating Income / interest Expenses', interest_coverage1 / interest_coverage2) gross_profit_margin1 = transpose['totalRevenue'] gross_profit_margin2 = transpose['costOfRevenue'] st.write( '***Gross Profit Margin:*** Total Revenue / Gross Profit Margin', (gross_profit_margin1 - gross_profit_margin2) / gross_profit_margin1) balance = si.get_balance_sheet(ticker) transpose = balance.transpose() current_ratio1 = transpose['totalCurrentAssets'] current_ratio2 = transpose['totalCurrentLiabilities'] debt_to_assets1 = transpose['otherCurrentAssets'] debt_to_assets2 = transpose['totalAssets'] st.write('***Debit Assets:*** Total Debit / Total Assets', (debt_to_assets1 / debt_to_assets2)) debt_to_equity1 = transpose['otherCurrentAssets'] debt_to_equity2 = transpose['totalStockholderEquity'] st.write( '***Debit to Equity:*** Total Debit / Total Stock Holders Equity', (debt_to_equity1 / debt_to_equity2)) ROE1 = transpose_income['netIncome'] ROE2 = transpose_balance['totalStockholderEquity'] st.write( '***Return On Equity ROE:*** Net Income / (Total Stock Holder Equity + Total Stock Holder Equity)/2', (ROE1 / ((ROE2 + ROE2) / 2))) ROA1 = transpose_income['netIncome'] ROA2 = transpose_balance['totalAssets'] st.write('***Return On Assets:*** Net Income / Total Assets', (ROA1 / ROA2)) company_simulation = st.sidebar.checkbox("Monte Carlo Simulation") if company_simulation: st.markdown( "<h1 style='text-align: center; color: #002966;'>Monte Carlo Simulation Price</h1>", unsafe_allow_html=True) st.write( """Monte Carlo Simulation project future price for the stocks. """) yahoo_financials = YahooFinancials(ticker) price = yahoo_financials.get_current_price() st.write('***Current Price:***', price) marketcap = yahoo_financials.get_market_cap() st.write('***Market Capital***', marketcap) income_balance = si.get_income_statement(ticker) transpose_income = income_balance.transpose() revenue = transpose_income['totalRevenue'] st.write('***Price to sales:*** (Market Capital / Revenue', marketcap / revenue) price_to_earnings = transpose_income['netIncome'] st.write('***Price to Earnings:*** (Market Capital/ Net Income', marketcap / price_to_earnings) balance_income = si.get_balance_sheet(ticker) transpose_balance = balance_income.transpose() price_to_book = transpose_balance['totalStockholderEquity'] st.write('***Price to book:*** (marketcap/Total Stock Holders Equity', marketcap / price_to_book) start = st.date_input("Please enter date begin Analysis: ") price = yf.download(ticker, start=start, end=None)['Close'] returns = price.pct_change() last_price = price[-1] num_simulations = 1000 num_days = 252 num_simulations_df = pd.DataFrame() for x in range(num_simulations): count = 0 daily_vol = returns.std() price_series = [] price = last_price * (1 + np.random.normal(0, daily_vol)) price_series.append(price) for y in range(num_days): if count == 251: break price = price_series[count] * (1 + np.random.normal(0, daily_vol)) price_series.append(price) count += 1 num_simulations_df[x] = price_series fig = plt.figure() plt.title('Monte Carlo Simulation') plt.plot(num_simulations_df) plt.axhline(y=last_price, color='r', linestyle='-') plt.xlabel('Day') plt.ylabel('Price') st.set_option('deprecation.showPyplotGlobalUse', False) st.pyplot() st.write('Price Series Predict: ', num_simulations_df) # company_general = st.sidebar.checkbox("Quick_Ratio") # if company_general: # st.subheader("""**Quick Ratio**""") # balance=si.get_balance_sheet(ticker) # transpose=balance.transpose() # quick_ratio1 = transpose['otherCurrentAssets'] # quick_ratio2 = transpose['inventory'] # quick_ratio3 = transpose['otherCurrentLiab'] # quick_ratio = ((quick_ratio1-quick_ratio2)/quick_ratio3) # if not quick_ratio2: # st.write("No data available") # else: # st.write('(***Quick Ratio:*** CurrentAssets - Inventory)/Current Liabilities)', (quick_ratio1-quick_ratio2)/quick_ratio3) company_hist = st.sidebar.checkbox("Cash Flow") if company_hist: st.markdown( "<h1 style='text-align: center; color: #002966;'>Cash Flow</h1>", unsafe_allow_html=True) display_cash = si.get_cash_flow(ticker) if display_cash.empty == True: st.write("No data available") else: st.write(display_cash) company_hist = st.sidebar.checkbox("Income Statement") if company_hist: st.markdown( "<h1 style='text-align: center; color: #002966;'>Income Statement</h1>", unsafe_allow_html=True) display_income_stat = si.get_income_statement(ticker) if display_income_stat.empty == True: st.write("No data available") else: st.write(display_income_stat) company_hist = st.sidebar.checkbox("Balance Sheet") if company_hist: st.markdown( "<h1 style='text-align: center; color: #002966;'>Balance Sheet</h1>", unsafe_allow_html=True) display_balance = si.get_balance_sheet(ticker) if display_balance.empty == True: st.write("No data available") else: st.write(display_balance) company_hist = st.sidebar.checkbox("Quote Table") if company_hist: st.markdown( "<h1 style='text-align: center; color: #002966;'>Quote Table</h1>", unsafe_allow_html=True) display_table = si.get_quote_table(ticker, dict_result=False) if display_table.empty == True: st.write("No data available") else: st.write(display_table) quote_table = si.get_quote_table(ticker) t = quote_table["Forward Dividend & Yield"] st.write('Forward Dividend & Yield:', t) display_capital = si.get_quote_table(ticker)["Market Cap"] st.write('Market Capital', display_capital) company_hist = st.sidebar.checkbox("Call Option") if company_hist: st.markdown( "<h1 style='text-align: center; color: #002966;'>Call Option</h1>", unsafe_allow_html=True) c = ops.get_calls(ticker) transpose = c.transpose() st.write(transpose)
print("Loading ticker list...") with open('ticker_list.json') as json_list: ticker_list = json.load(json_list) # ticker_list = ticker_list[0:20] # For debugging purposes, when we want a smaller ticker_list to work with # Refresh market cap info without retrieving all the other info about the stocks if not args.refresh and args.refresh_market_caps: with open('market_cap_info.json') as json_list: market_cap = json_list cap_keys = market_cap.keys() print(f"Keys in market_cap dictionary: {cap_keys}") yahoo_financials = YahooFinancials(cap_keys) print("Retrieving market cap information from Yahoo Finance...") market_cap = yahoo_financials.get_market_cap() json.dump(market_cap, open('market_cap_info.json', 'w')) # Retrieve the ticker information (balance sheets, income statements, and market caps), scrape the data in # batches, and save in batches. if args.refresh and not args.continue_refresh: print("Refreshing all stock data...") balance_sheet = {} income_statement = {} market_cap = {} retrieve_data(batch_size, ticker_list, "balance", fn_balance, balance_sheet) retrieve_data(batch_size, ticker_list, "income", fn_income, income_statement) retrieve_data(batch_size, ticker_list, "cap", fn_cap, market_cap) clean_tickers()
from yahoofinancials import YahooFinancials ticker = 'KO' YF = YahooFinancials(ticker) balance_sheet_data_qt = YF.get_financial_stmts('annual', 'balance') income_statement_data_qt = YF.get_financial_stmts('annual', 'income') cash_statement_data_qt = YF.get_financial_stmts('annual', 'cash') all_statement_data_qt = YF.get_financial_stmts('annual', ['income', 'cash', 'balance']) apple_earnings_data = YF.get_stock_earnings_data() outstanding_share = YF.get_num_shares_outstanding() market_cap = YF.get_market_cap() #apple_net_income = YF.get_net_income() #historical_stock_prices = YF.get_historical_price_data('2008-08-15', '2018-09-15', 'daily') print("Balance", balance_sheet_data_qt) print("income statement", income_statement_data_qt) print("cash statement", cash_statement_data_qt) print("earnings", apple_earnings_data) print("outstanding shares", outstanding_share) print("market cap", market_cap) #print ("net income", apple_net_income) #print( "Div", historical_stock_prices[ticker]['eventsData']['dividends']) #print (YF.get_total_revenue()) #print (YF.get_50day_moving_avg()) print(income_statement_data_qt) print(all_statement_data_qt)
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 companiesData['Market Cap'] = market_caps