def import_yahoofinance2(): # import stock_info module from yahoo_fin from yahoo_fin import stock_info as si # get live price of Apple si.get_live_price("aapl") # or Amazon si.get_live_price("amzn") # or any other ticker si.get_live_price(ticker) # get quote table back as a data frame si.get_quote_table("aapl", dict_result = False) # or get it back as a dictionary (default) si.get_quote_table("aapl") si.get_top_crypto() # get most active stocks on the day si.get_day_most_active() # get biggest gainers si.get_day_gainers() # get worst performers si.get_day_losers()
def getTickerData(stocks): tickerData = {} for c in stocks: #td[c]=si.get_quote_table(c, dict_result=False) price = si.get_quote_table(c)["Quote Price"] pc = si.get_quote_table(c)["Previous Close"] pct_ch = "%.2f" % ((price / pc - 1) * 100) + '%' tickerData[c] = {'price': "{:.0f}".format(price), 'pct_ch': pct_ch} return tickerData
def indices_v2(): dow_quote = get_quote_table('^dji') sp_500_quote = get_quote_table('^gspc') nasdaq_quote = get_quote_table('^ixic') # russell_2000_quote = get_quote_table('^rut') # vix = get_quote_table('^vix') return jsonify({ 'dow': _transform_data(dow_quote), 'nasdaq': _transform_data(nasdaq_quote), 'sp500': _transform_data(sp_500_quote), # 'russell2000': _transform_data(russell_2000_quote), # 'vix': _transform_data(vix) }), 200
def get_precos(): acoes = Acao.objects.all() for acao in acoes: try: print(str(acao)) preco = get_quote_table(str(acao)) #print(preco) p = acao.preco_set.create(preco=preco["Quote Price"]) p.save() #print("limites") try: limite = Perfil.objects.get(pk=acao.id) except Perfil.DoesNotExist: limite = False #print(getattr(limite, "limInf")) if limite: lSup = float(getattr(limite, "limSup")) lInf = float(getattr(limite, "limInf")) print(str(lInf) + ' \ ' + str(lSup)) if float(preco["Quote Price"]) >= float(lSup): manda_email("sup", str(acao), lSup, preco["Quote Price"]) if float(preco["Quote Price"]) <= float(lInf): manda_email("inf", str(acao), lInf, preco["Quote Price"]) else: print("Limite de {} não adicionado".format(str(acao))) except Exception as e: print("Error") pass atualizar()
def get_yahoo_quotes(): """ [ {'52 Week Range': '157.13 - 186.99', 'Ask': '0.00 x 4000', 'Avg. Volume': 8064500.0, 'Beta (5Y Monthly)': 0.09, 'Bid': '0.00 x 1300', "Day's Range": '166.90 - 170.19', 'Expense Ratio (net)': '0.40%', 'Inception Date': '2004-11-18', 'NAV': 166.84, 'Net Assets': '59.26B', 'Open': 167.58, 'PE Ratio (TTM)': 28.63, 'Previous Close': 167.67, 'Quote Price': 170.19000244140625, 'Volume': 10036431.0, 'YTD Daily Total Return': '-6.43%', 'Yield': '0.00%'}, {'52 Week Range': '319.80 - 450.65', 'Ask': '0.00 x 1200', 'Avg. Volume': 61116292.0, 'Beta (5Y Monthly)': 1.0, 'Bid': '0.00 x 3100', "Day's Range": '447.07 - 450.65', 'Expense Ratio (net)': '0.09%', 'Inception Date': '1993-01-22', 'NAV': 439.23, 'Net Assets': '374.03B', 'Open': 447.12, 'PE Ratio (TTM)': 3.12, 'Previous Close': 446.26, 'Quote Price': 450.25, 'Volume': 77235113.0, 'YTD Daily Total Return': '19.94%', 'Yield': '1.30%'}, {'52 Week Range': '133.19 - 167.24', 'Ask': '0.00 x 1100', 'Avg. Volume': 15720817.0, 'Beta (5Y Monthly)': 3.36, 'Bid': '0.00 x 2200', "Day's Range": '148.34 - 149.48', 'Expense Ratio (net)': '0.15%', 'Inception Date': '2002-07-22', 'NAV': 149.23, 'Net Assets': '15.15B', 'Open': 148.57, 'PE Ratio (TTM)': nan, 'Previous Close': 148.45, 'Quote Price': 149.4600067138672, 'Volume': 15384740.0, 'YTD Daily Total Return': '-5.12%', 'Yield': '1.50%'} ] """ try: quotes = [] for quote in ['gld', 'spy', 'tlt', 'tqqq', 'upro', 'tmf']: quote_table = si.get_quote_table(quote) quotes.append({ "symbol": quote, "previousClose": quote_table.get('Previous Close'), "open": quote_table.get('Open'), "latestPrice": quote_table.get('Quote Price'), "week52Low": float(quote_table.get('52 Week Range').split(" - ")[0]), "week52High": float(quote_table.get('52 Week Range').split(" - ")[1]), "ytdChange": quote_table.get('YTD Daily Total Return'), }) with open('static/quote.json', 'w') as fp: json.dump(quotes, fp, sort_keys=True, indent=4) except: return
def check_stock(stock, row): print("check_stock->" + stock) print("will update row->" + str(row)) try: price = get_live_price(stock) except: stock_mx[row][0] = 0 stock_mx[row][1] = 0 return try: prev_price = get_quote_table(stock)['Previous Close'] except: stock_mx[row][0] = 0 stock_mx[row][1] = 0 if price > prev_price: print(stock + " up") stock_mx[row][0] = 0 stock_mx[row][1] = 1 return (True) else: print(stock + " down") stock_mx[row][0] = 1 stock_mx[row][1] = 0 return (False)
def queryPrices(symbs, cur, conn): # query the prices from api and push to database # symbs : list of ticker symbols # cur : cursor # conn : connection symb_cnt = len(symbs) new_sks = getPriceSK(cur, conn, symbCount) # pull list of fresh SKs for indx, tickerSymb in enumerate(symbs): ticker = tickerSymb.rstrip().replace('.', '') try: qt = si.get_quote_table(ticker) except: print("[error] Cannot pull quot table for %s." % ticker) if qt is not None: pushPrice( cur, # cursor conn, # connection int(newSKs[indx]), # new price SK ticker, # ticker symbol str(qt["Quote Price"]).replace(',', ''), # quote price str(qt["Ask"]).replace(',', '').split(' ', 1)[0], # ask price str(qt["Bid"]).replace(',', '').split(' ', 1)[0], # bid price qt["Volume"]) # cumulative day volume
def current_stock_price(stock, value): ''' Takes company's Yahoo Finance ticker and intrinsic value of company Returns Value per share ''' df = si.get_quote_table(stock) cmp = df['Quote Price'] market_cap = df['Market Cap'] if market_cap[-1] == 'T': market_cap = float(market_cap[:-1]) * 10**12 / 10**7 elif market_cap[-1] == 'B': market_cap = float(market_cap[:-1]) * 10**9 / 10**7 elif market_cap[-1] == 'M': market_cap = float(market_cap[:-1]) * 10**6 / 10**7 else: market_cap = float(market_cap) print('Market Capitalisation (in Crs):', market_cap) share_out = market_cap / cmp print('Shares Outstanding (in Crs):', round(share_out, 3)) print('-----------------------------------------------------') print('CMP : Rs ', round(cmp, 3)) value_per_share = value / share_out print('Value per share: Rs ', round(value_per_share, 3)) print('-----------------------------------------------------') if value_per_share <= cmp: print('The Stock is OVER PRICED') else: print('The Stock is UNDER PRICED') return value_per_share, market_cap, share_out, cmp
def get(): sym = {} batch_id = 0 batch_size = 1 small_dict = {} mid_dict = {} large_dict = {} while batch_id < len(companies): sym = companies[batch_id:batch_id + batch_size] if sym[0]['marketCap'] < 20000000: small_dict[sym[0]['symbol']] = sym[0]['marketCap'] elif sym[0]['marketCap'] < 100000000 and sym[0]['marketCap'] > 20000000: mid_dict[sym[0]['symbol']] = sym[0]['marketCap'] else: large_dict[sym[0]['symbol']] = sym[0]['marketCap'] batch_id = batch_id + batch_size small_dict = dict(itertools.islice(small_dict.items(), 5)) mid_dict = dict(itertools.islice(mid_dict.items(), 5)) large_dict = dict(itertools.islice(large_dict.items(), 5)) #m = (input)("Enter cap : ") m = request.args.get('cap') comp = {} if m == "smallcap": for key, value in small_dict.items(): comp[key] = filterfunc(key) comp = dict( sorted(comp.items(), key=operator.itemgetter(1), reverse=True)) elif m == "midcap": for key in mid_dict.items(): comp[key] = filterfunc(key) comp = dict( sorted(comp.items(), key=operator.itemgetter(1), reverse=True)) elif m == "largecap": for key in large_dict.items(): comp[key] = filterfunc(key) comp = dict( sorted(comp.items(), key=operator.itemgetter(1), reverse=True)) print("filtered") print(comp) Com = [] for key, value in comp.items(): quote = si.get_quote_table(key) c = Company(key, quote.get('1y Target Est'), quote.get('52 Week Range'), quote.get('Ask'), quote.get('Avg. Volume'), quote.get('Beta (5Y Monthly)'), quote.get('Bid'), quote.get("Day's Range"), quote.get('EPS (TTM)'), quote.get('Earnings Date'), quote.get('Ex-Dividend Date'), quote.get('Forward Dividend & Yield'), quote.get('Market Cap'), quote.get('Open'), quote.get('PE Ratio (TTM)'), quote.get('Previous Close'), quote.get('Price'), quote.get('Volume')) Com.append(c.toJSON()) print(c.toJSON()) return jsonify(Com)
def getCurrentMarketData(self, tickerList): """ get real-time market data, you can use this with my two reporters :param tickerList: list of tickers, like: ["AAPL","IBM","JPM"] :return: dataframe of accessed data """ ans = pd.DataFrame(columns=[ "Best Ask Price", "Best Ask Amount", "Best Bid Price", "Best Bid Amount", "Quote Price", "Open", "Previous Close", "Volume" ]) temp_dict = {} keys = [ "Ask", "Bid", "Open", "Previous Close", "Quote Price", "Volume" ] for ticker in tickerList: try: temp_dict[ticker] = si.get_quote_table(ticker) except: warnings.warn("{}'s market data not found!".format(ticker)) for ticker, data in temp_dict.items(): values = list(itemgetter(*keys)(data)) organized_values = list(map(float, values[0].split("x"))) + \ list(map(float, values[1].split("x"))) + \ [round(values[4], 4)] + \ values[2:4] + \ values[5:] ans.loc[ticker] = organized_values with pd.option_context('display.max_rows', None, 'display.max_columns', None): print(ans) return ans
def priceDiv(ticker): try: price = si.get_live_price(ticker) div = si.get_quote_table(ticker)['Forward Dividend & Yield'][:4] return price, div except: raise Exception('There was a problem updating %s...' % (ticker))
def update1(self): input_stocklv = self.lineEditlive.text() df = si.get_quote_table(input_stocklv, dict_result=False) a = df['value'][15] - df['value'][14] #print(round(a, 2)) b = (a / df['value'][15]) * 100 #print(round(b, 2), "%") c = "(" + str(round(b, 2)) + "%" + ")" if df['value'][14] > df['value'][15]: self.qplabel.setStyleSheet('color:red') self.ndlabel.setStyleSheet('color:red') self.nplabel.setStyleSheet('color:red') self.qplabel.setText(str(df['value'][15])) self.ndlabel.setText(str(round(a, 2))) self.nplabel.setText(c) elif df['value'][14] < df['value'][15]: self.qplabel.setStyleSheet('color:green') self.ndlabel.setStyleSheet('color:green') self.nplabel.setStyleSheet('color:green') self.qplabel.setText(str(df['value'][15])) self.ndlabel.setText(str(round(a, 2))) self.nplabel.setText(c) self.model = pandasModel(df) self.tableViewcd.setModel(self.model) self.tableViewcd.show()
def base(request, symbol): liveval = si.get_quote_table(symbol) template = loader.get_template('base.html') cnx = sqlite3.connect('db.sqlite3') df = pd.read_sql_query("SELECT * FROM mainapp_" + symbol.lower(), cnx) x_date = {} for i in range(len(df['price_date'])): key = str(i) x_date[key] = df['price_date'][i] json_data = json.dumps(x_date) with open('static/data.json', 'w') as outfile: json.dump(json_data, outfile) df.price_date = pd.to_datetime(df.price_date) df = df.sort_values('price_date') #DISPLAY GRAPH # graph(symbol,df) secondlast_price, last_price = find_price(symbol, df) dt = df['price_date'].values close_date = pd.Timestamp(dt[len(dt) - 1]).date() change = last_price - secondlast_price sign = 0 if (change > 0): sign = 1 per = (change / last_price) * 100 change = '%.2f' % (change) per = '%.2f' % (per) if change[0] != '-': change = "+" + change last_price = '%.2f' % (last_price) context = { 'symbol': symbol, 'sign': sign, 'temp': df, 'change': change, 'last_price': last_price, 'per': per, 'close_date': close_date, 'close': list(df['close_price'].values), 'open': list(df['open_price'].values), 'high': list(df['high_price'].values), 'low': list(df['low_price'].values), 'val1': liveval['1y Target Est'], 'val2': liveval['52 Week Range'], 'val3': liveval['Ask'], 'val4': liveval['Avg. Volume'], 'val5': liveval['Beta (3Y Monthly)'], 'val6': liveval['Bid'], 'val7': liveval['EPS (TTM)'], 'val8': liveval['Earnings Date'], 'val9': liveval['Ex-Dividend Date'], 'val10': liveval['Forward Dividend & Yield'], 'val11': liveval['Market Cap'], 'val12': liveval['Open'], 'val13': liveval['PE Ratio (TTM)'], 'val14': liveval['Previous Close'], 'val15': '%.2f' % (liveval['Quote Price']), 'val16': liveval['Volume'], } return HttpResponse(template.render(context, request))
def obtenerCotizacion(self, event): #hace la consulta a la API self.busquedaCot = last_price = si.get_quote_table( self.lb1.GetStringSelection())["Quote Price"] cartel = MessageBox("Ultima cotizacion de " + self.lb1.GetStringSelection() + " en el mercado: $" + str(round(self.busquedaCot, 2)))
def _get_price_yahoo(symbol, mysettings): """ Return current price for given stock, 0 if hit an error. Note that am using Yahoo Finance to retrieve prices. Also note that appears that if request a symbol that they don't recognize, they return an empty Global Quote object. """ time.sleep(mysettings.yahooCallDelay) yahooSymbol = get_yahoo_ticker(symbol) priceInfo = security.PriceInfo() # Try up to three times if fail. for i in range(0, 3): try: quote_table = get_quote_table(yahooSymbol) priceInfo.currentPrice = quote_table['Quote Price'] priceInfo.lastClosePrice = quote_table['Previous Close'] priceInfo.low52Week, priceInfo.high52Week = _split_price_range( quote_table['52 Week Range']) break except (ValueError, IndexError, ImportError, HTTPError) as E: # E = sys.exc_info()[0] print("Failed to retrieve price for ", yahooSymbol) print(E) E = sys.exc_info()[0] print(E) return priceInfo
async def check(ctx, ticker): print('Price check command received') live_price = str(round(si.get_live_price(ticker), 2)) today_range = si.get_quote_table(ticker).get("Day's Range") await ctx.send("Live price: " + live_price + "\nToday's range: " + today_range)
def get_dividend_yield(symbol): data = si.get_quote_table(symbol , dict_result = True) begin = data['Forward Dividend & Yield'].index('(') try: end = data['Forward Dividend & Yield'].index('%') except: return "N/A" return (float(data['Forward Dividend & Yield'][begin+1:end]))/100
def get_pe(share): try: ticker = si.get_quote_table(share)['PE Ratio (TTM)'] if ticker == '' or pd.isnull(ticker): ticker = 0 return ticker except: return 0
def get(ticker): try: logging.debug("Retrieving quote for '%s'", ticker) data = stock_info.get_quote_table(ticker) data["ticker"] = ticker.upper() return StockQuote(data) except: logging.error("Error retrieving quote for ticker '%s'", ticker)
def fetch_stock(name): try: data = si.get_quote_table(name) return data except ValueError: print("Invalid stock name. Check and try again.") logging.debug("Invalid stock name.") return None
def indices(): dow = get_quote_table('^dji') dow['Change'] = dow['Quote Price'] - dow['Previous Close'] dow['Percent Change'] = dow['Change'] / dow['Previous Close'] * 100 sp500 = get_quote_table('^gspc') sp500['Change'] = sp500['Quote Price'] - sp500['Previous Close'] sp500['Percent Change'] = sp500['Change'] / sp500['Previous Close'] * 100 nasdaq = get_quote_table('^ixic') nasdaq['Change'] = nasdaq['Quote Price'] - nasdaq['Previous Close'] nasdaq['Percent Change'] = nasdaq['Change'] / \ nasdaq['Previous Close'] * 100 major_indices = {'dow': dow, 'sp500': sp500, 'nasdaq': nasdaq} return jsonify(major_indices), 200
def quotes_genrator(n_clicks, ticker): # info table current_stock = yf.get_quote_table(ticker, dict_result=False) columns = [{"name": i, "id": i} for i in current_stock.columns] t_data = current_stock.to_dict("records") # price return columns, t_data
def companyinfo(): if request.method == 'POST': stock = '' try: stock = str(json.loads(request.data)["stock"]) except Exception as ex: print(ex) try: stock = str(request.form["stock"]) except Exception as ex: print(ex) obj = '' try: obj = Ticker(stock) except Exception as ex: print(ex) val = '' try: val = obj.info except Exception as ex: print(ex) data = dict() try: data["PEGratio"] = val["pegRatio"] data["futurePEGratio"] = val["pegRatio"] except Exception as ex: print(ex) try: data["futurePEratio"] = val["forwardPE"] data["PEratio"] = val["forwardPE"] except Exception as ex: print(ex) try: data["beta"] = val["beta"] except Exception as ex: print(ex) try: val = si.get_quote_table(stock) except Exception as ex: print(ex) try: data["PEratio"] = val["PE Ratio (TTM)"] except Exception as ex: print(ex) outputdata = jsonify(data) outputdata.headers.add("Access-Control-Allow-Origin", "*") outputdata.headers.add("Access-Control-Allow-Headers", "*") outputdata.headers.add("Access-Control-Allow-Methods", "*") return outputdata
def get_quote_table_field(field, stock_ticker): """ This will get data from a field in the quote table. :param field: field you want data from. :param stock_ticker: stock you want data on. :return: data from field. """ quote_table = si.get_quote_table(stock_ticker) return quote_table[field]
def index(request): version = Version.objects.all().first() ticker_hits = TickerHits.objects.filter( version=version.version).order_by("-hits").first() reddit = ticker_hits.tickers.symbol version = IHVersion.objects.all().first() ticker_weights = IHTickerWeights.objects.filter( version=version.version).order_by("-weight").first() ihub = ticker_weights.tickers.symbol twitter_tickers = Twitter.objects.all().order_by("-created_at").first() twitter = twitter_tickers.tickers.symbol reddit_data = si.get_quote_table(reddit, dict_result=True) twitter_data = si.get_quote_table(twitter, dict_result=True) ihub_data = si.get_quote_table(ihub, dict_result=True) now = datetime.datetime.now() then = start_date = datetime.datetime.now() - datetime.timedelta(30) month_data = si.get_data(reddit, then, now) open_data = [] for data in month_data.open: open_data.append(data) start_dt = date(2019, 1, 21) end_dt = date(2019, 2, 4) data_date = [] weekdays = [5, 6] for dt in daterange(then, now): if dt.weekday() not in weekdays: data_date.append(dt.strftime(str("%m-%d"))) context = { 'reddit': reddit, 'ihub': ihub, 'ihub_data': ihub_data, 'twitter': twitter, 'twitter_data': twitter_data, 'reddit_data': reddit_data, 'open_data': open_data, 'data_date': data_date, } return render(request, "stock_data/screener.html", context)
def write_stock_info(tickers): for ticker in tickers: data = si.get_quote_table(ticker) output = "\r" price = str(data["Quote Price"]) output += price output += "\n I love ice cream" output += "\0x1B[1A" sys.stdout.write(output) sys.stdout.flush()
def get_quote(ticker): stockinfo = {} stockinfo["symbol"] = ticker stockinfo["market_price"] = yf.get_live_price(ticker) stock_tmp = yf.get_quote_table(ticker) stockinfo["day_range"] = stock_tmp["Day's Range"] stockinfo["year_range"] = stock_tmp["52 Week Range"] return stockinfo
async def outstanding_close_name(self) -> Dict[str, float]: """ get the price and outstandings from yahoo API the unit of outstanding is 'M' """ out = si.get_quote_data(self.symbol)['sharesOutstanding'] out = out / 1000000 close = round(si.get_quote_table(self.symbol)['Quote Price'], 2) name = self.symbol return {'out': round(out), 'close': close, 'name': name}
def stockform(): form = StockForm(request.form) if form.validate_on_submit(): global output output = si.get_quote_table(form.stockname.data, dict_result=False) return output return render_template('output.html', title='Stock Details', form=form, output=output)
def _checkStock(stock_id): """ Checks price of stock from Yahoo! Finance """ try: try: stock = si.get_quote_table(stock_id, dict_result=True) except: try: stock = si.get_quote_table(stock_id, dict_result=True) except: try: stock = si.get_quote_table(stock_id, dict_result=True) except: stock = si.get_quote_table(stock_id, dict_result=True) quote_price = round(stock['Quote Price'], 2) close_price = stock['Previous Close'] percentage = round(((quote_price - close_price) / close_price) * 100, 2) day_range = stock["Day's Range"] volume = int(stock['Volume']) return (quote_price, percentage, volume, day_range) except: return (0,0,0,"")