async def stocks(self, ctx, stock): bot.command_used(ctx, "stocks") data = YahooFinancials(stock) if str(data.get_current_price()) != "None" and str( data.get_current_price()) != "": print(data.get_current_price()) await ctx.send( f"**{stock.upper()} - USD**\nCurrent Value: `{str(data.get_current_price())}`\nDaily Low/High: `" + f"{str(data.get_daily_low())} `/` {str(data.get_daily_high())}`\nYearly Low/High: `{str(data.get_yearly_low())} `/` {str(data.get_yearly_high())}`" ) else: await ctx.send( "Invalid Listing, listings must be abbreviated e.g. AMZN or TSLA", delete_after=7)
def balance_sheet(request): stocks = Stock.objects.filter(user=request.user) total = 0 latest = 0 loss_profit = 0 percent = 0 for stock in stocks: total += float(stock.stock_final_amount) ticker = stock.stock_name t = YahooFinancials(ticker) latest += float( round(t.get_current_price(), 2) * float(stock.stock_quant)) loss_profit = round(abs(float(total) - latest), 2) try: percent = ((latest - total) / latest) * 100 except Exception as e: pass return render( request, 'balance.html', { 'stocks': stocks, 'total': total, 'latest': round(latest, 2), 'loss_profit': loss_profit, 'percent': round(percent, 2) })
def get_latest(symbol): stock = YahooFinancials(symbol) return stock.get_current_price() # print(get_div_yield('SPY')) # print(get_latest('AAPL'))
def calculate(): url = 'http://www.google.com/' timeout = 2 try: _ = requests.get(url, timeout=timeout) symbol = (request.form['ticketSymbol']) try: data = YahooFinancials(symbol) date = datetime.datetime.now(tzlocal()) timezone = str(time.asctime(time.localtime(time.time()))) strftime = date.strftime("%Z") financials = data.get_stock_quote_type_data() name = str(financials.get(symbol).get('longName')) sym = financials.get(symbol).get('symbol') current = str(data.get_current_price()) currentchange = str(round(data.get_current_change(), 2)) percentchange = str( round(data.get_current_percent_change() * 100, 2)) + '%' return render_template('output.html', symbol=symbol, data=data, timezone=timezone, strftime=strftime, financials=financials, name=name, sym=sym, current=current, currentchange=currentchange, percentchange=percentchange) except: return 'INVALID SYMBOL' except: return 'NO INTERNET CONNECTION'
def response(self, sentence): with open(self.intents_location) as json_data: intents = json.load(json_data) json_data.close() results = self.classify(sentence) # if classification exists then find the matching intent tag and return a response from the respective tag if results: # loop as long as there are matches to process while results: for i in intents['intents']: # find a tag matching the first result if i['tag'] == results[0]["intent"]: # return a random response from the intent # If question is for specific data such as Time, Weather, Wikipedia, etc, return specified info if i['tag'] == 'information': topic = re.search('tell me about (.*)', sentence.lower()) if topic: topic = topic.group(1) try: wiki = wikipedia.summary(topic) except (wikipedia.exceptions.PageError, wikipedia.exceptions.DisambiguationError) as e: wiki = str(e) return wiki return "For me to understand your wikipedia question, use the format 'tell me about *'" if i['tag'] == 'time': ents = self.spacy_retrieve_nouns(sentence) if len(ents) > 0: time = self.get_time_by_city(str(ents[0])) return f"The current time in {str(ents[0])} is {time}" if i['tag'] == 'weather': ents = self.spacy_retrieve_nouns(sentence) print(ents) if len(ents) > 0: loop = asyncio.get_event_loop() data_weather = loop.run_until_complete(self.get_weather(str(ents[0]))) return data_weather if i['tag'] == 'stocks': ticker = reticker.TickerExtractor().extract(sentence.upper()) print(ticker) return_text = "" for tick in ticker: yahoo_price = YahooFinancials(tick) if yahoo_price.get_current_price() is None: continue return_text += f"Current price of {tick} is {yahoo_price.get_currency()} " \ f"{yahoo_price.get_current_price()}\n" if len(return_text) > 0: return return_text return random.choice(i['response']) results.pop(0)
def update_volume_watchlist_stock_dict(stock): global stocks_dict #global temp global daily_avg_change stock_yahoo_obj = YahooFinancials(stock.symbol) stock_volume_increase_ratio = compare_stock_relative_volume_to_avg(stock_yahoo_obj) stock_price_change = stock_yahoo_obj.get_current_percent_change() stock_price_change = str(round((stock_price_change * 100 ),2))+'%' current_stock_price = round(stock_yahoo_obj.get_current_price(),2) stocks_dict[stock.symbol] = [stock.eps_growth,stock.net_income_growth,stock.sales_growth,stock_volume_increase_ratio,stock_price_change,current_stock_price]
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 stock_detail(stock_name): stock_dict = {} yahoo_financial = YahooFinancials(stock_name) current_price = yahoo_financial.get_current_price() fifty_two_week_high_value = yahoo_financial.get_yearly_high() fifty_two_week_low_value = yahoo_financial.get_yearly_low() stock_dict['stock_name'] = stock_name stock_dict['high_value'] = fifty_two_week_high_value stock_dict['low_value'] = fifty_two_week_low_value stock_dict['current_price'] = current_price return stock_dict
def get_data(request, slug): item = Stock.objects.filter(slug=slug) for i in item: ticker = i.stock_name purchased_price = float(i.stock_cb) quantity = float(i.stock_quant) yahoo_financials = YahooFinancials(ticker) prev_close_balance = yahoo_financials.get_current_price() # total = prev_close_balance*quantity diff = round(quantity * (prev_close_balance - purchased_price), 2) default_items = [purchased_price, prev_close_balance, diff] data = {"default": default_items, "difference": diff} return JsonResponse(data)
def scrap_stock_current_price(): # récupération du prix courant de l'action (ici "AAPL") # avec le timestamp timestamp = str(int(time.time())) yahoo_financials = YahooFinancials(stock) current_price = str(yahoo_financials.get_current_price()) # afin de pouvoir importer les données dans un sorted set Redis, # chaque ligne du fichier CSV a le format suivant: # [timestamp],[prix_action]:[timesamp] line = timestamp + "," + current_price + ":" + timestamp print(line) outputFile.write(line) outputFile.write("\n") outputFile.flush()
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)
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 update_shares(request, portfolio_pk): portfolio = Portfolio.objects.get(pk=portfolio_pk) check_ownership(request, portfolio) pstocks = PortfolioStock.objects.filter(portfolio=portfolio) for pstock in pstocks: stock = pstock.stock yf = YahooFinancials(quote_name) stock.last_price = convert_number(yf.get_current_price()) stock.price_sales_ratio = convert_number(yf.get_price_to_sales()) stock.dividend_yield = convert_number(yf.get_dividend_yield()) stock.save() return http.HttpResponseRedirect('..')
def defaultapi(ticker): #print(tick.get_summary_data()) #print(mark) #print(tick.get_stock_quote_type_data()) #print(mark) #print(tick.get_stock_price_data()) #print(mark) #print(mark) #print(tick.get_dividend_rate()) try: tick = YF(ticker) print("DIGN:", tick.get_current_price()) except: print("DIGN: -") pass
def update_stock(i): now = datetime.datetime.now() time_list.append(now) j = 0 for stock in stocks: ticker = stock print("processing stock "+stock) yahoo_financials = YahooFinancials(ticker) stock_dict[stock].append(yahoo_financials.get_current_price()) ax2[j].clear() ax2[j].plot(time_list, stock_dict[stock], label=stock) ax2[j].set_xlabel('Date Time') ax2[j].set_ylabel('Closing price ($)') j += 1
def defaultapi(ticker): tick = YF(ticker) print(tick.get_stock_summary_data()) print(mark) print(tick.get_stock_quote_type_data()) print(mark) print(tick.get_stock_price_data()) print(mark) print(tick.get_current_price()) print(mark) print(tick.get_dividend_rate()) try: r = tick._cache.keys() except AttributeError: pass else: print(mark) print(r)
def get_data(cls, self): """Get data from yahoo finance.""" treasuries = YahooFinancials(self.tickers) tdata = treasuries.get_current_price() # Add current timestamp tdata['time'] = datetime.datetime.now() # Append data to existing data frame df = self.df.append(tdata, ignore_index=True) """ # Remove time from columns for data conversion try: self.cols.remove('time') except ValueError: pass # Convert cols to float 16s df[self.cols] = df[self.cols].astype(np.float16) """ df.reset_index(inplace=True, drop=True) return df
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 get_stock_price(self, stock_name, t=None): stock = YahooFinancials(self.stickers[stock_name]) if t is None: price = stock.get_current_price() else: data = stock.get_historical_price_data(start_date=str(t)[:10], end_date=str( datetime.date.today()), time_interval='daily') data = pd.DataFrame(data[self.stickers[stock_name]]['prices']) data.rename(columns={ 'formatted_date': 'ds', 'close': 'y' }, inplace=True) if not (data.empty) and str(t)[:10] in data.ds.unique(): price = data[data.ds == str(t)[:10]]['y'].values[0] else: price = np.nan return price
class TestModule(TestCase): def setUp(self): self.test_yf_stock_single = YahooFinancials('C') self.test_yf_stock_multi = YahooFinancials(stocks) self.test_yf_treasuries_single = YahooFinancials('^IRX') self.test_yf_treasuries_multi = YahooFinancials(us_treasuries) self.test_yf_currencies = YahooFinancials(currencies) # Fundamentals Test def test_yf_fundamentals(self): # Single stock test single_balance_sheet_data_qt = self.test_yf_stock_single.get_financial_stmts( 'quarterly', 'balance') single_income_statement_data_qt = self.test_yf_stock_single.get_financial_stmts( 'quarterly', 'income') single_all_statement_data_qt = self.test_yf_stock_single.get_financial_stmts( 'quarterly', ['income', 'cash', 'balance']) # Multi stock test multi_balance_sheet_data_qt = self.test_yf_stock_multi.get_financial_stmts( 'quarterly', 'balance') multi_income_statement_data_qt = self.test_yf_stock_multi.get_financial_stmts( 'quarterly', 'income') multi_all_statement_data_qt = self.test_yf_stock_multi.get_financial_stmts( 'quarterly', ['income', 'cash', 'balance']) # Single stock check result = check_fundamental(single_balance_sheet_data_qt, 'bal') self.assertEqual(result, True) result = check_fundamental(single_income_statement_data_qt, 'inc') self.assertEqual(result, True) result = check_fundamental(single_all_statement_data_qt, 'all') self.assertEqual(result, True) # Multi stock check result = check_fundamental(multi_balance_sheet_data_qt, 'bal') self.assertEqual(result, True) result = check_fundamental(multi_income_statement_data_qt, 'inc') self.assertEqual(result, True) result = check_fundamental(multi_all_statement_data_qt, 'all') self.assertEqual(result, True) # Historical Price Test def test_yf_historical_price(self): single_stock_prices = self.test_yf_stock_single.get_historical_price_data( '2015-01-15', '2017-10-15', 'weekly') expect_dict = { 'high': 49.099998474121094, 'volume': 125737200, 'formatted_date': '2015-01-12', 'low': 46.599998474121094, 'adjclose': 45.35684585571289, 'date': 1421038800, 'close': 47.61000061035156, 'open': 48.959999084472656 } self.assertDictEqual(single_stock_prices['C']['prices'][0], expect_dict) # Historical Stock Daily Dividend Test def test_yf_dividend_price(self): single_stock_dividend = self.test_yf_stock_single.get_daily_dividend_data( '1986-09-15', '1987-09-15') expect_dict = { "C": [{ "date": 533313000, "formatted_date": "1986-11-25", "amount": 0.02999 }, { "date": 541348200, "formatted_date": "1987-02-26", "amount": 0.02999 }, { "date": 544714200, "formatted_date": "1987-04-06", "amount": 0.332 }, { "date": 549120600, "formatted_date": "1987-05-27", "amount": 0.02999 }, { "date": 552576600, "formatted_date": "1987-07-06", "amount": 0.332 }, { "date": 557501400, "formatted_date": "1987-09-01", "amount": 0.02999 }] } self.assertDictEqual(single_stock_dividend, expect_dict) # Extra Module Methods Test def test_yf_module_methods(self): # Stocks if isinstance(self.test_yf_stock_single.get_current_price(), float): self.assertEqual(True, True) else: self.assertEqual(False, True) if isinstance(self.test_yf_stock_single.get_net_income(), int): self.assertEqual(True, True) else: self.assertEqual(False, True) # Treasuries if isinstance(self.test_yf_treasuries_single.get_current_price(), float): self.assertEqual(True, True) else: self.assertEqual(False, True)
from yahoofinancials import YahooFinancials import pandas as pd import time ## dd/mm/yyyy format print(time.strftime("%d/%m/%Y")) ## 12 hour format ## print(time.strftime("%I:%M:%S")) holdings = open( "holdings.txt" ) #create a file called "holdings" and add your stock list to it for line in holdings: Name_of_stock = line.split(',')[0] Ticker_symbol = line.split(',')[1].split('*')[0] #print (Name_of_stock,Ticker_symbol) stockInfo = YahooFinancials( Ticker_symbol) #import the stock details from yahoo finance stockpricechange = format( 100 * float(stockInfo.get_current_change()) / (float(stockInfo.get_current_price()) - float(stockInfo.get_current_change())), '.2f') #For ease of viewing this allows you to see if the stock has risen or fallen if float(stockpricechange) > 0.00: print Name_of_stock, Ticker_symbol, "^^^", "UP", stockpricechange, "^^^", stockInfo.get_currency( ), stockInfo.get_current_price() elif float(stockpricechange) <= 0.00: print Name_of_stock, Ticker_symbol, "***", "DOWN", stockpricechange, "***", stockInfo.get_currency( ), stockInfo.get_current_price() # Written by Tom Meany please add suff you think is useful!
from yahoofinancials import YahooFinancials from servertools import SlackComm stonk = '6098.T' yf = YahooFinancials(stonk) price = yf.get_current_price() change = yf.get_current_change() pct_change = yf.get_current_percent_change() scom = SlackComm('viktor') jpyusd = 1 / 104.48 units = 100 strike_price = 4542 msg = f'{units:,.0f} shares of `{stonk}` are now worth *`{(price - strike_price) * jpyusd * units:+,.2f}`* USD' \ f' more than when you got it' blocks = [ scom.bkb.make_context_section( f':trending_up_and_down: time for stonk updates !'), scom.bkb.make_block_section(msg), scom.bkb.make_context_section([ f'JPY/USD: {jpyusd:.4f}, strike price: {strike_price}, current price: {price}' ]) ] scom.st.send_message('C01M49M5EEM', message='stonk update', blocks=blocks)
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)
# Just want to watch some major worldwide indexes mutual_funds = [ '^GSPC', '^DJI', '^IXIC', '^FTSE', '^N100', '^FCHI', '^GDAXI', '^N225', '^TWII', '^HSI' ] mutual_funds = YahooFinancials(mutual_funds) # Define dates for the historical price data arguments today = datetime.date.today() endDate = (today - datetime.timedelta(weeks=1)).strftime('%Y-%m-%d') startDate = (today - datetime.timedelta(weeks=52)).strftime('%Y-%m-%d') # Actually call the YF functions hist = mutual_funds.get_historical_price_data(startDate, endDate, "monthly") curr = mutual_funds.get_current_price() # Initialize empty list of alerts alerts = [] # Loop through provided tickers to get Current price and High/Low range. for ticker in curr: currentValue = curr[ticker] lows = [] highs = [] for price in hist[ticker]['prices']: if price['low'] is not None: lows.append(price['low']) if price['high'] is not None:
def analyze_stock(pstock): days = 1000 now = datetime.datetime.now() year_before = now - datetime.timedelta(days=days) stock = pstock.stock yf = YahooFinancials(stock.name) stock_analysis = StockAnalysis(yf) # update important fields stock.last_price = convert_number(yf.get_current_price()) stock.price_sales_ratio = convert_number(yf.get_price_to_sales()) stock.dividend_yield = convert_number(yf.get_annual_avg_div_yield()) # historical_prices = yf.get_historical_price_data(stock.name, # year_before.strftime('%Y%m%d'), now.strftime('%Y%m%d'), 'daily') #[['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Clos'] # history = [] # historical_prices = historical_prices[1:] # has_history = True # for p in historical_prices: # # error index out of range here # if(len(p) == 1): # has_history = False # break # close_v = float(p[4]) # date = datetime.datetime.strptime(p[0],'%Y-%m-%d') # history.append({"date":date, "close_value":close_v}) # price_trends = [] # volatilities = [ # {'days':100}, # {'days':300}, # {'days':600}, # ] # if has_history: # # today first # history = sorted(history, key=lambda p: p['date']) # assert history[1]['date'] > history[0]['date'] # for v in volatilities: # if len(history) < v['days']: # v['days'] = len(history) # v['volatility'] = round(calculate_historical_volatility(history[-v['days']:]), 2) # v['start_date'] = history[-v['days']:][0]['date'] # stock_analysis.volatility = volatilities[1]['volatility'] # stock.volatility = stock_analysis.volatility # start = 0 # interval = int(len(history) / 5.0) # while len(history) > (start + interval) and interval > 0: # trend = calculate_historical_price_trend(history[start:start+interval]) # price_trends.append(trend) # start = start + interval # #if len(history) < (start + interval): # # interval = len(history) - start - 1 # trend = calculate_historical_price_trend(history) # price_trends.append(trend) # stock_analysis.trend = trend stock.value_score = stock_analysis.value_score_analysis() stock.save() return { #'price_trends':price_trends, 'stock':stock, #'volatilities':volatilities, 'stock_analysis':stock_analysis, 'days':days, #'history': history }
def get_financial_values_by_ticker(ticker): print('Finding ticker in Yahoo Finance...') s = YahooFinancials(ticker) financial_values = {'beta': round(s.get_beta(), 2), 'current_price': round(s.get_current_price(), 2), 'prev_close_price': round(s.get_prev_close_price(), 2)} return financial_values
class TestModule(TestCase): def setUp(self): self.test_yf_stock_single = YahooFinancials('C') self.test_yf_stock_multi = YahooFinancials(stocks) self.test_yf_treasuries_single = YahooFinancials('^IRX') self.test_yf_treasuries_multi = YahooFinancials(us_treasuries) self.test_yf_currencies = YahooFinancials(currencies) # Fundamentals Test def test_yf_fundamentals(self): # Single stock test single_balance_sheet_data_qt = self.test_yf_stock_single.get_financial_stmts( 'quarterly', 'balance') single_income_statement_data_qt = self.test_yf_stock_single.get_financial_stmts( 'quarterly', 'income') single_all_statement_data_qt = self.test_yf_stock_single.get_financial_stmts( 'quarterly', ['income', 'cash', 'balance']) # Multi stock test multi_balance_sheet_data_qt = self.test_yf_stock_multi.get_financial_stmts( 'quarterly', 'balance') multi_income_statement_data_qt = self.test_yf_stock_multi.get_financial_stmts( 'quarterly', 'income') multi_all_statement_data_qt = self.test_yf_stock_multi.get_financial_stmts( 'quarterly', ['income', 'cash', 'balance']) # Single stock check result = check_fundamental(single_balance_sheet_data_qt, 'bal') self.assertEqual(result, True) result = check_fundamental(single_income_statement_data_qt, 'inc') self.assertEqual(result, True) result = check_fundamental(single_all_statement_data_qt, 'all') self.assertEqual(result, True) # Multi stock check result = check_fundamental(multi_balance_sheet_data_qt, 'bal') self.assertEqual(result, True) result = check_fundamental(multi_income_statement_data_qt, 'inc') self.assertEqual(result, True) result = check_fundamental(multi_all_statement_data_qt, 'all') self.assertEqual(result, True) # Historical Price Test def test_yf_historical_price(self): single_stock_prices = self.test_yf_stock_single.get_historical_price_data( '2015-01-15', '2017-10-15', 'weekly') expect_dict = { 'high': 49.099998474121094, 'volume': 125737200, 'formatted_date': '2015-01-12', 'low': 46.599998474121094, 'adjclose': 45.669029235839844, 'date': 1421038800, 'close': 47.61000061035156, 'open': 48.959999084472656 } self.assertDictEqual(single_stock_prices['C']['prices'][0], expect_dict) # Extra Module Methods Test def test_yf_module_methods(self): # Stocks if isinstance(self.test_yf_stock_single.get_current_price(), float): self.assertEqual(True, True) else: self.assertEqual(False, True) if isinstance(self.test_yf_stock_single.get_net_income(), int): self.assertEqual(True, True) else: self.assertEqual(False, True) # Treasuries if isinstance(self.test_yf_treasuries_single.get_current_price(), float): self.assertEqual(True, True) else: self.assertEqual(False, True)
from yahoofinancials import YahooFinancials def div_yield_percentage(dividend, spot_price): div_yield = str(round(dividend/spot_price*100, 2)) + "%" return div_yield shares = YahooFinancials(["1299.HK", "2318.HK"]) dividend_data = shares.get_daily_dividend_data("2018-01-01", "2018-12-31") price_data = shares.get_current_price() for ins, dividends in dividend_data.items(): total_div = 0 spot_price = price_data[ins] for dividend in dividends: total_div = total_div + dividend["amount"] div_yield = div_yield_percentage(total_div, spot_price) print ("Dividend yield for %s is %s" % (ins, div_yield)) # div = 0.848 + 0.095 # spot = 84.25 # div_yield = div_yield_percentage(div, spot) # print ("Dividend yield of 1299.HK = %s " % div_yield ) # div = 1.284144 # spot = 93.8 # div_yield = div_yield_percentage(div, spot) # print ("Dividend yield of 2318.HK = %s " % div_yield )