def setup_class(self): self.cshare = Stock("aapl") self.cshare2 = Stock("aapl", output_format='pandas') self.cshare3 = Stock("svxy") self.cshare4 = Stock("aapl", json_parse_int=Decimal, json_parse_float=Decimal) self.cshare5 = Stock("gig^")
def test_wrong_iex_input_type(self): with pytest.raises(ValueError): Stock(34) with pytest.raises(ValueError): Stock("") with pytest.raises(ValueError): ls = [] Stock(ls)
def setup_class(self): self.cshare = Stock("AAPL") self.cshare2 = Stock("AAPL", output_format='pandas') self.cshare3 = Stock("SVXY") self.cshare4 = Stock("AAPL", json_parse_int=Decimal, json_parse_float=Decimal) self.cshare5 = Stock("GIG^")
def get_ticker(body): global ticker_set # frequent words that look like tickers but aren't blacklist_words = [ "YOLO", "TOS", "CEO", "CFO", "CTO", "DD", "BTFD", "WSB", "OK", "RH", "KYS", "FD", "TYS", "US", "USA", "IT", "ATH", "RIP", "BMW", "GDP", "OTM", "ATM", "ITM", "IMO", "LOL", "DOJ", "BE", "PR", "PC", "ICE", "TYS", "ISIS", "PRAY", "PT", "FBI", "SEC", "GOD", "NOT", "POS", "COD", "AYYMD", "FOMO", "TL;DR", "EDIT", "STILL", "LGMA", "WTF", "RAW", "PM", "LMAO", "LMFAO", "ROFL", "EZ", "RED", "BEZOS", "TICK", "IS", "DOW" "AM", "PM", "LPT", "GOAT", "FL", "CA", "IL", "PDFUA", "MACD", "HQ", "OP", "DJIA", "PS", "AH", "TL", "DR", "JAN", "FEB", "JUL", "AUG", "SEP", "SEPT", "OCT", "NOV", "DEC", "FDA", "IV", "ER", "IPO", "RISE" "IPA", "URL", "MILF", "BUT", "SSN", "FIFA", "USD", "CPU", "AT", "GG", "ELON", "I", "WE", "A", "AND", "THE", "THIS", "TO", "BUY", "MY", "MOST", "ARK", "IN", "S", "BABY", "APES" ] # FIRST CHECK IF THERE'S A $TICKER WITH DOLLAR SIGN if '$' in body: index = body.find('$') + 1 word = check_after_dollarsign(body, index) if word and word not in blacklist_words: try: # special case for $ROPE if word != "ROPE": # sends request to IEX API to determine whether the current word is a valid ticker # if it isn't, it'll return an error and therefore continue on to the next word if not word in ticker_set: price = Stock(word).get_company() ticker_set.add(word) else: return word except Exception as e: pass # IF NO TICKER WITH DOLLAR SIGN, CHECK FOR TICKER WITHOUT IT: splits every body into list of words word_list = re.sub("[^\w]", " ", body).split() for count, word in enumerate(word_list): # initial screening of words if word.isupper() and len(word) >= 1 and ( word.upper() not in blacklist_words) and len(word) <= 5 and word.isalpha(): try: # special case for $ROPE if word != "ROPE": if not word in ticker_set: price = Stock(word).get_company() ticker_set.add(word) else: return word except Exception as e: continue # if no ticker was found return "None"
def respond(state, message, params): entities = interpreter.parse(message)["entities"] intent = interpreter.parse(message)["intent"]["name"] # Initialize an empty params dictionary #params = {} # Fill the dictionary with entities for ent in entities: params[ent["entity"]] = str(ent["value"]) # find the match response (new_state, response) = policy_rules[(state, intent)] # extract the name of company if new_state == 1: for ent in params: if ent == "company": company = str(params[ent]) if new_state == 2: if intent == "get_price": for ent in params: if ent == "company": company = str(params[ent]) stock = Stock(company) price = str(stock.get_price()) response = "The current stock price of " + company + " is " + price if intent == "get_historical_price": my_friend.send("Loading diagram...") for ent in params: if ent == "company": company = str(params[ent]) if ent == "start_date": startdateStr = str(params[ent]) startda = startdateStr.split('.') start = datetime(int(startda[0]), int(startda[1]), int(startda[2])) if ent == "end_date": enddateStr = str(params[ent]) endda = enddateStr.split('.') end = datetime(int(endda[0]), int(endda[1]), int(endda[2])) df = get_historical_data(company, start, end, output_format='pandas') df.plot() plt.savefig("./figure.jpg") my_friend.send_image('figure.jpg') response = "The stock price diagram of " + company if intent == "get_open_price": for ent in params: if ent == "company": company = str(params[ent]) stock = Stock(company) price = str(stock.get_open()) response = "The open price of " + company + " is " + price return new_state, response, params
def price(self, ticker, database): try: # price = float(Stock(ticker).get_price()) price = Stock(ticker).get_price() # self.myDatabase.at["price", ticker] = price self.price_fetch_price(ticker, price, database) except: try: price = float(Stock(ticker).get_close()) # self.myDatabase.at["price", ticker] = price self.price_fetch_price(ticker, price, database) except: price = 0.0 self.price_fetch_price(ticker, price, database)
def eternal_price(self): import time import datetime import pytz now = datetime.datetime.now(tz=pytz.timezone('US/Eastern')) print('Current price') if now.hour > 9 and now.weekday() < 5: while True: print(Stock(self.name).get_price()) time.sleep(5) else: print(Stock(self.name).get_price()) print( 'NASDAQ working hours: 9:30 a.m to 4 p.m. in New York. From Monday to Friday. It\'s closed right know.' )
def _calculate_next_dividend(self, symbols): """ Returns estimated date for the next dividend Returns ------- If date is unknown, returns beginning of epoch """ next_div_dates = {} for symbol in symbols: logging.debug("IExcloudService - Fetching get_dividends") stock = Stock(symbol) logging.debug("IExcloudService - Finished fetching get_dividends") logging.error("IExcloud does not return dividend dates correctly") div_data = stock.get_dividends() if div_data: data = {symbol: div_data[0]['exDate']} else: epoch = datetime.datetime(1970, 1, 1).date() data = {symbol: epoch.strftime("%Y-%m-%d")} dividends = self._next_div(data, symbol) next_div_dates[symbol] = dividends return next_div_dates
def set_stock_id(self, stock_id): self.symbol_info = IEXQuery.get_symbol_detail(stock_id) if self.symbol_info is None: return False else: self._stock = Stock(stock_id, output_format="json", token=API_KEY) return True
def growth(ticker, created): if not ticker or ticker == "None": return "N/A" # get today's date and DD's date (ranges from <>1 week in case of weekends/holidays) try: # get today's price sandbox(True) price_today = Stock(ticker).get_quote().latestPrice[ticker] ticker_date_start = get_start_date(created) ticker_date_end = datetime.fromtimestamp(int(created)) # dates for post creation: loop until get valid date counter = 0 new_date = created while not ticker_date_start and counter < 20: counter += 1 new_date -= 86400 ticker_date_start = get_start_date(new_date) # get DD date's price if ticker_date_start: ticker_date_end = ticker_date_start + timedelta(days=0.8) price_ticker_date = get_historical_data(ticker, ticker_date_start, ticker_date_end, close_only=True).close[0] # compute percentage growth #print(ticker,created) #print(get_metadata()) percentage = ((price_today / price_ticker_date) - 1) * 100 return "{:.2f}".format(percentage) + "%" except Exception as e: print(e) return "N/A"
def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the sensor platform.""" from iexfinance.refdata import get_symbols from iexfinance.stocks import Stock os.environ['IEX_TOKEN'] = config.get(CONF_API_KEY) avail = get_symbols() symbols = config.get(CONF_SYMBOLS, []) dev = [] for symbol in symbols: symbol_found = next( (item for item in avail if item["symbol"] == symbol[CONF_SYMBOL]), None) if symbol_found is not None: stock = Stock(symbol[CONF_SYMBOL]) dev.append(IEXSensor(stock, symbol)) _LOGGER.debug("Device created for symbol %s", symbol[CONF_SYMBOL]) else: _LOGGER.warn("No sensor created for unsupported symbol %s", symbol[CONF_SYMBOL]) add_devices(dev, True) _LOGGER.debug("Setup completed")
def buy_stock(): form = BuyForm() if request.method == 'POST' and form.validate(): # return render_template('failure.html', msg = 'finally') symbol = form.symbol.data.upper() shares = form.shares.data # company = Company.query.filter_by(symbol = symbol) company = Company.query.filter(Company.symbol == symbol).first() if company: stock = Stock(company.symbol) current_price = stock.get_quote()['latestPrice'] price_each_cent = int(current_price * 100) cost_cent = price_each_cent * shares cost = cost_cent / 100 if cost_cent > current_user.cash_cent: return render_template('failure.html',\ msg = f'The cost of these shares, {cost:.2f}, is '\ + f'more than the cash you have in your account, '\ + f'{current_user.cash_cent /100}.') current_user.cash_cent -= cost_cent user_id = current_user.id transact = Transact(shares, price_each_cent, user_id, company.id) db.session.add(transact) db.session.commit() return redirect(url_for('home')) else: return render_template( 'failure.html', msg=f'{symbol} is not a recognized stock symbol.') return render_template('buy.html', form=form)
def get_stock_details(self, stock): print("Details") try: s = Stock(stock, token="REPLACE YOUR TOKEN") return s.get_quote() except (IEXQueryError, IEXSymbolError): return "Please Input A Valid Stock Symbol"
def create_stock(tickerstr): try: # print("D") stock = Py_Stock() tempstock = Stock(str(tickerstr), token=IEX_TOKEN) # print(tempstock) stock.ticker = str(tickerstr) stock.price = tempstock.get_quote()["latestPrice"] # stock.price = tempstock.get_price(token= IEX_TOKEN) # stock.price = finnhub_client.quote(tickerstr) # stock.price = float(si.get_live_price(tickerstr)) # stock.price = stock.price['c'] # print("D") # print(str(stock.ticker) + str(stock.price)) # del tempstock # stock.price = str(si.get_live_price(str(tickerstr))) # print(stock.price) # if stock.price.isnumeric: # stock.price = int(stock.price) # print(stock.ticker, stock.price) # else: # print("D") # stock.price = str("NA") # except: None return stock
def get(self): try: symbol = StockDetail.parser.parse_args()['symbol'] stock = Stock(symbol) company = stock.get_company() quote = stock.get_quote() stats = stock.get_key_stats() return { 'symbol': company['symbol'], 'name': company['companyName'], 'description': company['description'], 'ceo': company['CEO'], 'employees': company['employees'], 'industry': company['industry'], 'price': quote['latestPrice'], 'volume': quote['volume'], 'avgVolume': stats['avg10Volume'], 'week52High': stats['week52high'], 'week52Low': stats['week52low'], 'marketCap': stats['marketcap'], 'peRatio': stats['peRatio'], 'dividendYield': stats['dividendYield'] }, 200 except Exception as e: print('Error while retrieving company', e, file=sys.stderr) return {'message': 'Could not find company'}, 500
def fetch_price(producer, symbol): """ helper function to retrieve stock data and send it to kafka :param producer: instance of a kafka producer :param symbol: symbol of the stock :return: None """ logger.debug('Start to fetch stock price for %s', symbol) tsla = Stock('TSLA') try: price = tsla.get_price() #price = random.randint(30, 120) timestamp = datetime.datetime.fromtimestamp( time.time()).strftime('%Y-%m-%dT%H:%MZ') payload = ( '[{"StockSymbol":"AAPL","LastTradePrice":%d,"LastTradeDateTime":"%s"}]' % (price, timestamp)).encode('utf-8') logger.debug('Retrieved stock info %s', price) producer.send(topic=topic_name, value=bytes(price), timestamp_ms=time.time()) logger.debug('Sent stock price for %s to Kafka', symbol) except KafkaTimeoutError as timeout_error: logger.warn( 'Failed to send stock price for %s to kafka, caused by: %s', (symbol, timeout_error.message)) except Exception: logger.warn('Failed to fetch stock price for %s', symbol)
def find_price(name): print(name) stock_price = Stock(name) stock_price.get_price() appe=stock_price.get_price() print(appe) return appe
def interpret(message): data = interpreter.parse(message) intent = data['intent']['name'] entities = data["entities"] matched_intent = match_intent(message) if matched_intent =="greet": return "greet",None if intent == "company_search": for item in entities: company_name = item["value"] company_stock = Stock(company_name,token = api_token) stock_batch = company_stock.get_quote() return "specify_company", stock_batch['symbol'] elif intent =="explanation": return "introduction", None elif intent =="stock_search": return "inquire", None elif intent == "information_search": for item in entities: if str(item["value"]) == "price": return "price",stock_batch['latestPrice'] elif str(item["value"]) == "volume": return "volume", stock_batch['latestVolume'] elif str(item["value"]) == "market cap": return "market cap",stock_batch['marketCap'] elif intent == "goodbye": return "goodbye",None
def get_price(symbol): try: return float(api.polygon.last_quote(symbol).askprice) except: # try IEX data if polygon fails stk = Stock(symbol, output_format='pandas') return float(stk.get_price().loc[symbol])
def update_db(): BASE_DIR = os.path.dirname(os.path.abspath(__file__)) db_path = os.path.join(BASE_DIR, "stocks.db") conn = sqlite3.connect(db_path) c = conn.cursor() c2 = conn.cursor() c.execute('SELECT * FROM stocks') for row in c: ticker = row[0] if (row[1] == None or row[1] == 'Null'): #shortname update try: name = tick.get_short_name(ticker) except KeyError: pass else: c.execute("UPDATE stocks set name = ? where ticker = ?", (name, ticker)) print("update name") if (row[3] == None or row[3] == 'Null'): #exchange update stock_IEX = Stock(ticker, tocken=IEX_TOKEN) try: exchange = stock_IEX.get_company()['exchange'] except utils.exceptions.IEXQueryError: print("Could not complete exchange query") else: c2.execute("UPDATE stocks set exchange = ? where ticker = ?", (exchange, ticker)) print("Added {} for {}".format(exchange, ticker)) conn.commit() c.close() c2.close() conn.close()
def home(): if not current_user.is_authenticated: return redirect(url_for('register')) current_stocks = db.session.query( Company.symbol, Company.name, func.sum(Transact.shares).label('shares_sum')).join( Transact.business).filter( Transact.user_id == current_user.id).group_by( Transact.company_id).having( func.sum(Transact.shares) > 0).all() portfolio = dict() for value in current_stocks: # so stocks that you sold off in the past don't show up # if value.shares_sum <= 0: # continue stock = Stock(value.symbol) current_price = stock.get_quote()['latestPrice'] portfolio[value.symbol] = { 'name': value.name, 'shares_sum': value.shares_sum, 'price': current_price, 'total_price': current_price * value.shares_sum } return render_template('index.html', portfolio=portfolio)
def getLatestPrice(Symbol): stockInfo = Stock(Symbol, output_format='json').get_quote() latestPrice = stockInfo['latestPrice'] return latestPrice
def get_price(symbol, times): #real time price if len(times) == 0: target = Stock(symbol) tp = target.get_quote() r = {} tp_dic = {} tp_dic['open'] = tp['open'] tp_dic['high'] = tp['high'] tp_dic['low'] = tp['low'] tp_dic['close'] = tp['close'] tp_dic['volume'] = tp['latestVolume'] tp_dic['price'] = tp['latestPrice'] r['Today'] = tp_dic return r elif len(times) == 1: df = get_historical_data(symbol, times[0], times[0]) t = list(df.keys())[0] r = {} #make return value have same format df[t]["price"] = df[t]['close'] r[t] = df[t] #r is a dic with only one specific date return r else: df = get_historical_data(symbol, times[0], times[1]) for date in df: df[date]["price"] = df[date]["close"] return df
def update_stock_logo(input_data): myStock = Stock(input_data) logo = myStock.get_logo() image = Image.open(urllib.request.urlopen(logo['url'])) new_image = make_square(image) #print(new_image) path = f'./assets/{input_data}.png' #new_image.save(path, format="PNG") #api = Client('2f8f8da3544e9d704d0081a6ea2aa5fb', '55c4f243a2d9925204714ff7202c404c2653d779') # data = { # 'wait': True, # "resize": { # "width": 115, # "height": 115, # "strategy": "fill", # "background": "rgba(35, 43, 43, 1)" # } # } # result = api.url(logo['url'], data) # if result.get('success'): # print(result.get('kraked_url')) # else: # print(result.get('message')) # return html.Img(src=result.get('kraked_url'), style={'height': 'auto', 'width': 'auto', 'max-height': '115px', 'max-width': '115px'}, className="responsive-img") return html.Img(src=path, style={'height': 'auto', 'width': 'auto', 'max-height': '100px', 'max-width': '100px'}, className="responsive-img")
def get_monthly_abstract_price(company): print("Company: ", company) # get data from iexfinance goal = Stock(company, token=Token) mon_pri_dics = goal.get_historical_prices() # create a new list mon_pri_data = [] # change the data into the form that mpf.candlestick_ochl function can read for dic in mon_pri_dics: # get date open high low close volume list(dic.values())[0:6] # change date into number t = date2num(datetime.datetime.strptime(list(dic.values())[0], '%Y-%m-%d')) # change sequence into the form that mpf.candlestick_ochl function can read ope, close, high, low, vol = list(dic.values())[1:6] # print(ope, close, high, low, vol) # change the data into the form that mpf.candlestick_ochl function can read data = [t, ope, close, high, low, vol] mon_pri_data.append(data) # draw the figure # set ax as the style of figure fig, ax = plt.subplots(figsize = (15,3.5)) plt.rcParams['savefig.dpi'] = 500 # set parameters of plot_day_summary_oclh: ax = ax sample; mon_pri_data = data color up = close > open; color down = open > close plot_day_summary_oclh(ax, mon_pri_data, colorup = 'r', colordown = 'g') ax.set_title('Candlestick Abstract Chart of' + ' ' + company) plt.grid(True) # set price label plt.ylabel('Price') # set x axis as date ax.xaxis_date () plt.show() return plt.savefig('monthabstractprice.png')
def function(input_data, input_date): inputDate = datetime.strptime(input_date, '%Y-%m-%d') # open_status = IsMarketOpen_pd(inputDate, 'NYSE') # if(open_status == True): get_opening_range_dict = GetOpeningRange(datetime(inputDate.year, inputDate.month, inputDate.day), input_data) # l_symbols = ['FB', 'GOOGL', 'AMZN', 'NFLX', 'QQQ', 'SPY'] print("get opening range dict") print(get_opening_range_dict) # edate = datetime(2019,2,8) # sdate = dtutils.MarketDateAdj(edate, -100, 'NYSE') # yhoo_data = web.DataReader([input_data], 'yahoo', sdate, edate) # df_overnight_r = GetReturnsYHF(yhoo_data, l_symbols, overnight=True) # df_returns = GetReturnsYHF(yhoo_data, l_symbols) price = Stock(input_data) px_close = price.get_price() # e_p, e_std = GetOpenRange(px_close, df_overnight_r[f'r({input_data})']) e_p, e_std, actual_open = round(get_opening_range_dict['Expected Px'],2), round(get_opening_range_dict['Std'],2), round(get_opening_range_dict['Actual Open'],2) # print(f'FB closed at {px_close}') # print(f'--- Expected Open Range ---') # print(f'68%: {"{:.2f}".format(e_p - e_std)} - {"{:.2f}".format(e_p + e_std)}') # print(f'95%: {"{:.2f}".format(e_p - 2 * e_std)} - {"{:.2f}".format(e_p + 2 * e_std)}') # print(f'99.7%: {"{:.2f}".format(e_p - 3 * e_std)} - {"{:.2f}".format(e_p + 3 * e_std)}') return generate_open_range_prediction(e_p, e_std, actual_open, e_p)
def get_batch_prices(list_dic): data = list_dic l = [] dic_l = [] if type(data[0]) == dict: for i in data: # print(i,i.keys()) l.append(list(i.keys())[0]) dic_l.append({'Symbol':list(i.keys())[0],'conId':list(i.values())[0]}) # print(data) df0 = pd.DataFrame(dic_l) else: l = data batch = Stock(l, token=token) df = batch.get_quote()[['latestPrice']].rename_axis('Symbol').reset_index() # df=df # df = df.reset_index() # print(df,df0) if type(data[0]) == dict: df = pd.merge(df, df0, on='Symbol') return df
def get_latest_price(self, ticker): """Fetch the current latest price. The date may differ. This routine attempts to fetch the most recent available price, and returns the actual date of the quoted price, which may differ from the date this call is made at. {1cfa25e37fc1} Args: ticker: A string, the ticker to be fetched by the source. This ticker may include structure, such as the exchange code. Also note that this ticker is source-specified, and is not necessarily the same value as the commodity symbol used in the Beancount file. Returns: A SourcePrice instance. If the price could not be fetched, None is returned and another source should be consulted. There is never any guarantee that a price source will be able to fetch its value; client code must be able to handle this. Also note that the price's returned time must be timezone-aware. """ try: theStock = Stock(ticker) theQuote = theStock.get_book()["quote"] # IEX is American markets. us_timezone = tz.gettz("America/New_York") theDate = datetime.datetime.fromtimestamp( theQuote["latestUpdate"] / 1000) theDate = theDate.astimezone(us_timezone) thePrice = D(theQuote["latestPrice"]).quantize(D("0.01")) return source.SourcePrice(thePrice, theDate, "USD") except Exception: raise IEXError("Erreur lors de l'execution de la requete") return None
def favorite_list_data(user_doc, wallet_coins_object, db_cryptocoin_obj): """ This functions creates an object with data for creating cards only for favorite coins which are watched by the user. It discards the coins that are not in the favorite list """ favorite_list = user_doc['favorites'] if favorite_list == '': return False elif favorite_list != '': favorite_list_data = {} if len(favorite_list) == 1: favorite_tuple = favorite_list elif len(favorite_list) > 1: favorite_tuple = favorite_list.split(",") for favorite in favorite_tuple: for coin_symbol, coin_info in wallet_coins_object.items(): if favorite == coin_symbol: favorite_list_data[coin_symbol] = coin_info if favorite not in wallet_coins_object.keys(): new_quote_favorite = Stock(favorite) quote_favorite_data = new_quote_favorite.get_quote() favorite_list_data[favorite] = quote_favorite_data for elem in db_cryptocoin_obj: if favorite == elem['symbol_long']: favorite_list_data[favorite]['name'] = elem['name'] favorite_list_data[favorite]['symbol_short'] = elem[ 'symbol_short'] return favorite_list_data
def request_iexc_depth(self, request): ticker = request.get_ticker() exchange = request.get_exchange() try: try: stock = Stock(ticker.id, token=os.environ["IEXC_KEY"]) depthData = stock.get_book()[ticker.id] rawData = stock.get_quote().loc[ticker.id] if ticker.quote is None and exchange is not None: return None, "Orderbook visualization for `{}` is only available on `{}`.".format( ticker.id, rawData["primaryExchange"]) bestBid = depthData["bids"][0] bestAsk = depthData["asks"][0] lastPrice = (bestBid[0] + bestAsk[0]) / 2 except: return None, None imageData = self.generate_depth_image(depthData, bestBid, bestAsk, lastPrice) return imageData, None except Exception: print(traceback.format_exc()) if os.environ["PRODUCTION_MODE"]: self.logging.report_exception() return None, None