def exec_script(): with open(file_name, 'r') as csvfile: data = [item for item in csv.reader(csvfile)] LTP_list = getQuotes(portfolio1) LTP_list2 = getQuotes(portfolio2) LTP_list3 = getQuotes(portfolio3) LTP_list.extend(LTP_list2) LTP_list.extend(LTP_list3) t = time.ctime() new_col = [t] new_data = [] for i in range(0, len(LTP_list)): new_col = new_col + [LTP_list[i][attribute]] for i, row in enumerate(data): row.append(new_col[i]) new_data.append(row) with open(file_name, 'w') as csvfile: writer = csv.writer(csvfile) writer.writerows(new_data) print 'Successfully appended to file "{0}" at {1}'.format( file_name, time.ctime())
def getCurrentData(self): self.portfolioValue = 0 for stock in self.listOfStocks: time.sleep(.5) self.listOfStocks[stock].setEquityValue(gf.getQuotes(stock)[0]['LastTradePrice']) self.portfolioValue += (float((gf.getQuotes(stock)[0]['LastTradePrice'])) * self.listOfStocks[stock].getShares()) self.refreshWeights() self.portfolioPerformance = (1 - (self.totalAmountInvested / self.portfolioValue)) * 100
def test_timeout(self): # ensure timeout will always happen googlefinance.setTimeout(0.0001) with self.assertRaisesRegexp(URLError, 'timed out'): googlefinance.getQuotes(['GOOG']) # reset timeout (for other tests) googlefinance.setTimeout(googlefinance.DEFAULT_TIMEOUT)
def getStockData(): appleStr = json.dumps(getQuotes('AAPL')) apple = json.loads(appleStr) applePrice = apple[0]["LastTradePrice"] googleStr = json.dumps(getQuotes('GOOG')) google = json.loads(googleStr) googlePrice = google[0]["LastTradePrice"] pack = {"AAPL":applePrice,"GOOG":googlePrice} return pack
def getStockData(): appleStr = json.dumps(getQuotes('AAPL')) apple = json.loads(appleStr) applePrice = apple[0]["LastTradePrice"] googleStr = json.dumps(getQuotes('GOOG')) google = json.loads(googleStr) googlePrice = google[0]["LastTradePrice"] pack = {"AAPL": applePrice, "GOOG": googlePrice} return pack
def update(self): self.current_price = round( float(getQuotes(self.symbol)[0]['LastTradePrice']), 2) self.percent_change = round( (float(getQuotes(self.symbol)[0]['LastTradePrice']) / float(getQuotes(self.symbol)[0]['PreviousClosePrice']) - 1) * 100, 2) self.percent_change_from_trigger = round( (self.current_price - self.trigger_price) / self.trigger_price * 100, 2) self.update_volume() self.update_earnings()
def get_stock_price(s): """ For given stock, return dictionary containing stock symbol, last traded price, last trade datetime, and index on which stock is traded. """ stock_dict = { 'stock_symbol': s, 'last_traded_price': getQuotes(s)[0]['LastTradePrice'], 'last_trade_datetime': getQuotes(s)[0]['LastTradeDateTime'] } return stock_dict
def fetchData(s): print(json.dumps(getQuotes(s), indent=2)) # Print out information for debugging stock = getQuotes(s) Sym = stock[0]['StockSymbol'] LTP = stock[0]['LastTradePrice'] LTT = stock[0]['LastTradeTime'] LTDT = stock[0]['LastTradeDateTime'] return { 'StockSymbol': Sym, 'LastTradePrice': LTP, 'LastTradeTime': LTT } # next line returns important stock info in dictionary form
def get_google_finance_quotes(cls, symbol): """ https://pypi.python.org/pypi/googlefinance :param symbol: stock symbol, e.g. 'AAPL', or list of stock symbols :return: list of dictionary """ return googlefinance.getQuotes(symbol)
def storeLiveData(symbol): company = symbol if (internet()): try: now = datetime.datetime.now() data = getQuotes(company) #open_stock_price = float(data[0]['PreviousClosePrice']) curr_stock_price = float(data[0]['LastTradeWithCurrency']) client = MongoClient() db = client.cmpe285_StockEngine collection = db.live_data_value #date = now.strftime("%Y-%m-%d %H:%M:%S") date = datetime.datetime.now() # Create the document to add data = {"symbol": company, "date": date, "price": curr_stock_price} # Add the document objId = collection.insert_one(data).inserted_id except Exception, exc: print "Exc: " + str(exc) print "Incorrect symbol entered. Quitting" looping = 0
def change_finance_values(): """ Uses the Google Finance API to get most recent data. """ current_price = float( getQuotes('MUTF_CA:INI220')[0]['LastTradePrice']) if datetime.datetime.now().strftime('%H') == '00': self.yesterday_closing = current_price if self.yesterday_closing: # could be initialized to None day_over_day = current_price - self.yesterday_closing if day_over_day >= 0: display_string = "${0} (+{1})".format( current_price, day_over_day) else: display_string = "${0} ({1})".format( current_price, day_over_day) else: display_string = "${0}".format(current_price) if self.the_finances != display_string: self.the_finances = display_string self.display_finances.config(text=self.the_finances, font=("Helvetica", font_size), bg='black', fg='white', justify='right') self.display_finances.after(30 * 60 * 60 * 15, change_finance_values)
def change_finance_values(): """ Uses the Google Finance API to get most recent data. """ current_price = float(getQuotes('MUTF_CA:INI220')[0]['LastTradePrice']) if datetime.datetime.now().strftime('%m') == '00': self.yesterday_closing = current_price if self.yesterday_closing: # could be initialized to None day_over_day = current_price - self.yesterday_closing if day_over_day >= 0: display_string = "${0} (+{1})".format(current_price, day_over_day) else: display_string = "${0} ({1})".format(current_price, day_over_day) else: display_string = "${0}".format(current_price) if self.the_finances != display_string: self.the_finances = display_string self.display_finances.config( text=self.the_finances, font=("Helvetica", font_size), bg='black', fg='white', justify='right' ) self.display_finances.after(30*60*60*15, change_finance_values)
def update_stocks(self): global current_userid if self.prev_userid != current_userid: for i in reversed(range(self.fbox.count())): self.fbox.itemAt(i).widget().setParent(None) self.prev_userid = current_userid if (current_userid != 0): sql_command = " SELECT * from stocks where userid = %s " % current_userid cursor.execute(sql_command) self.obj = cursor.fetchall() self.stockNames = [] for i, stock in enumerate(self.obj): self.stockNames.append(stock[2]) else: self.stockNames = ['SENSEX', 'NIFTY', 'RELIANCE', 'ITC', 'TCS'] for i, stock in enumerate(self.stockNames): stkLbl = QLabel(str(stock)) data = getQuotes(stock) prcLbl = QLabel(data[0]['LastTradePrice']) stkLbl.setFont(font1) prcLbl.setFont(font1) self.fbox.addRow(stkLbl, prcLbl)
def get_quote(self, symbol): result = getQuotes(symbol) quote = 0 if result: quote = float(result[0]['LastTradePrice']) return quote
def update(self): google_data = getQuotes(['GLUU', 'BGMD', 'BGMD', 'HACK']) # Make this the range for your stocks. If you have 5 stocks the range is 0,5 for i in range(0, 4): self.holdings[i].update(google_data[i])
def print_chain_to_files(stock): with open(path + stock.symbol + ".csv", 'wb') as stock_file: current_price = float(getQuotes([stock.symbol])[0]['LastTradePrice']) gain = current_price * stock.num_shares - stock.num_shares * stock.avg_price total_gains = current_price * stock.num_shares - stock.num_shares * stock.avg_price + stock.realized_gains try: percent_gain = 100 - (stock.avg_price * stock.num_shares) / (current_price * stock.num_shares) * 100 except: percent_gain = 0 stock_csv = csv.writer(stock_file) stock_csv.writerow(['symbol','total', 'avg_price', 'current_price', 'gain if sold', 'percent_gain', 'realized_gains', 'total gains']) stock_csv.writerow([stock.symbol, stock.num_shares, stock.avg_price, current_price, gain, percent_gain, stock.realized_gains, total_gains]) stock_csv.writerow('') stock_csv.writerow(keys + ['gain/profit', 'percent_gain', 'timestamp']) for transaction in stock.chain: row = [] for key in keys: row.append(transaction[key]) if(transaction['side'] == 'buy'): row.append(current_price * float(transaction['cumulative_quantity']) - float(transaction['price']) * float(transaction['cumulative_quantity'])) row.append(100 - (float(transaction['price']) * 100.0 / current_price)) if(transaction['side'] == 'sell'): row.append(float(transaction['profit'])) row.append(float(0)) row.append(transaction['timestamp']) stock_csv.writerow(row)
def on_data(self, data): dict_data = json.loads(data) if 'text' in dict_data: tweet = TextBlob(dict_data["text"]) # print tweet.sentiment.polarity if tweet.sentiment.polarity < 0: sentiment = "negative" elif tweet.sentiment.polarity == 0: sentiment = "neutral" else: sentiment = "positive" stock_quote = str(getQuotes('FB')[0]['LastTradePrice']) print sentiment # time_stamp = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(dict_data["created_at"],'%a %b %d %H:%M:%S +0000 %Y')) time_stamp = datetime.strptime(dict_data["created_at"],'%a %b %d %H:%M:%S +0000 %Y').replace(tzinfo=pytz.UTC).strftime("%Y-%m-%d %H:%M:%S") p='%Y-%m-%d %H:%M:%S' epoch = int(time.mktime(time.strptime(time_stamp,p))) scoring = (1-tweet.sentiment.subjectivity)*tweet.sentiment.polarity es.index(index="stocks", doc_type="Facebook", body={"company": dict_data["user"]["screen_name"], "created_at": epoch, "message": dict_data["text"], "polarity": tweet.sentiment.polarity, "subjectivity": tweet.sentiment.subjectivity, "sentiment": sentiment, "scoring": scoring, "current_quote": stock_quote}) return True
def main(): sell_all(sys.argv[1]) exit(0) f = open(sys.argv[1]) investment = json.loads(f.read()) money = 0 invested = 0 for invest in investment: try: if invest["investment"] is False: continue except: continue invested += INVESTMENT_VALUE money -= INVESTMENT_VALUE try: result = getQuotes(str(invest["symbol"]))[0] except: print "error while request google finance" continue new_price = float(result["LastTradePrice"]) old_price = invest["price"] print "[" + str( invest["symbol"] ) + "]", "new price:", new_price, "old price", old_price, "--", new_price > old_price * 1.02 money += new_price / old_price * INVESTMENT_VALUE print "money:", money print "invested:", invested
def fetch_price(producer, symbol): price = json.dumps(getQuotes(symbol)); logger.debug('Get stock price %s', price) try: producer.send(topic=topic_name, value=price, timestamp_ms=time.time()) except Exception: logger.warn('Failed to send msg to kafka')
def get_quote(self, asset): asset = asset_factory(asset) if self._cache.get(asset.symbol) is not None: return self._cache.get(asset.symbol) if isinstance(asset, Option): options = self.get_options(asset.underlying, asset.expiration_date) matches = [_ for _ in options if _.asset == asset] if len(matches) == 0: raise Exception( "GoogleFinanceAdapter.get_quote: No quote found for {}". format(asset.symbol)) return matches[0] else: google_quotes = getQuotes(asset.symbol) if google_quotes is None or len(google_quotes) == 0: raise Exception( "GoogleFinanceAdapter.get_quote: No quote found for {}". format(asset.symbol)) last_trade = google_quotes[0].get('LastTradeWithCurrency', None) if last_trade is None or last_trade == '' or last_trade == '-': raise Exception( "GoogleFinanceAdapter.get_quote: No quote found for {}". format(asset.symbol)) return Quote(quote_date=arrow.now().format('YYYY-MM-DD'), asset=asset, bid=float(last_trade) - 0.01, ask=float(last_trade) + 0.01)
def fetch_stock_data(self): try: stock_data = json.dumps(getQuotes(self.symbol)) self.logger.info('Fetched data for %s' % self.symbol) return stock_data except Exception: self.logger.warn('Failed to fetch data for %s' % self.symbol)
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) try: # price = (json.dumps(getQuotes(symbol))) price_temp = [] for stock in symbol: price_temp.append(getQuotes(stock)) # print('--->stock info price_temp: %s' % price_temp) price = json.dumps(price_temp) print('--->stock info price: %s' % type(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=payload, timestamp_ms=time.time()) producer.send(topic=topic_name, value=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, e: logger.warn('Failed to fetch stock price for %s', e)
def yahoo_feed(self): rss_link = "http://finance.yahoo.com/rss/headline?s=" rss_url = rss_link + self.ticker feedparser.USER_AGENT = 'Chrome 41.0.2228.0' info = feedparser.parse(rss_url) stream_data = [] for idx, entry in enumerate(info.entries): try: print "\n\n === ", idx date_time = datetime.fromtimestamp( mktime(entry.published_parsed)) # print date_time.date(),date_time.time(),entry.title,article.cleaned_text,entry.summary,news_url,info.feed.title # news_url = entry.link.split('*')[1] news_url = str(entry.link) print entry.title response = self.opener.open(news_url).read() article = self.go_obj.extract(raw_html=response) stock_price = str( getQuotes(self.ticker.upper())[0] ['LastTradePrice']) if idx == 0 else '' data = [ str(date_time.date()), str(date_time.time()), stock_price, entry.title, article.cleaned_text, news_url ] stream_data.append(data) except Exception, e: print e
def fetch_price(producer, symbol): """Use googlefinance's getQuotes() api to quote a stock's info. Store the info into Kafka Args: producer (KafkaProducer): A kafka client that publishes records to the Kafka cluster symbol (str): Abbreviation of the stock we want to record """ try: stock_info = json.dumps(getQuotes(symbol)) logger.debug('received stock price for {}'.format(symbol)) producer.send(topic=topic_name, value=stock_info, timestamp_ms=time.time()) logger.debug('sending stock price for {}'.format(symbol)) except KafkaTimeoutError as timeout_error: logger.warn( 'failed to send stock price for {} to kafka due to timeout'.format( symbol)) print(timeout_error) except Exception: logger.error( 'failed to send stock price for {} due to unknown reason'.format( symbol))
def animate(i,ticker): animate.n = animate.n+1 width = 1 data = senti_val(ticker) if data: sentiment.append(data) else: sentiment.append(sentiment[0]) ax1.clear() ax1.set_ylim([-1,1]) for i in range(len(sentiment)): if sentiment[i] >=0 : rec = ax1.bar(i, sentiment[i], width, color='g') else : rec = ax1.bar(i, sentiment[i], width, color='r') ax1.set_title("Comparison between stock price and Compnay sentiment") ax1.set_ylabel("Sentiment Strength") stock_price = float(getQuotes(ticker.upper())[0]['LastTradePrice']) print stock_price pullData.append(stock_price) time_data.append(datetime.datetime.now()) ax2.clear() ax2.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d-%H:%M')) ax2.plot(time_data,pullData,linewidth=2.0) plt.gcf().autofmt_xdate() ax2.set_ylabel('Stock Price') ax2.set_xlabel('Time')
def getQuote(stockTicker): stackInfo = json.dumps(getQuotes(stockTicker), indent=2) stockInfo = json.loads(stackInfo) closePrice = stockInfo[0]['LastTradePrice'] getcontext().prec = 3 close = Decimal(closePrice) return close
def update_stock(dial, stock): stk = Share(stock) prev_close_price = float(stk.get_prev_close()) stk_data = json.loads(json.dumps(getQuotes(stock), indent=2))[0] stk_price = float(stk_data['LastTradePrice']) NIMBUS.set_dial_value(dial, percentage(stk_price, prev_close_price), "%s:%.2f" % (stock, stk_price))
def _parse_and_respond(self, event): """Streams stock data to the channel for the given event. Args: event: Slack event dictionary """ if self._ismessage(event) and self._contains_stock(event['text']): stocks = self._get_stocks(event['text']) for stock in stocks: ticker = self._strip_non_alphabet(stock) # Do not respond if ticker is invalid. if not ticker: continue channel = event['channel'] # Lookup ticker data with google finance try: gfin = getQuotes(ticker)[0] # We want to display the ticker and the price symbol = gfin.get("StockSymbol") price = gfin.get("LastTradePrice") date = gfin.get("LastTradeDateTimeLong") # We aren't going to bother with localization... response = "{} traded at ${} on {}".format( symbol, price, date) self.client.rtm_send_message(channel, response) except Exception: msg = "I was unable to find data on {}.".format(ticker) self.client.rtm_send_message(channel, msg)
def getCurStockPrice(symbol): try: data = getQuotes(symbol) stock_price = float(data[0]['LastTradeWithCurrency']) return stock_price except: return 0.0
def getStock(): company = ['AAPL','GOOGL','MSFT','CSCO','INTC','AMZN','VOD','QCOM','EBAY','INFY','DVMT','FB','TRIP','BBRY','PBYI','NVDA','TXN','SBUX','NFLX','ADBE','TSLA','MAR','EA','WDC','ADSK','ATVI','TMUS','MAT','FOXA','CTSH','DISCA','PYPL','GPRO','CTXS'] company_name = ['Apple Inc.','Google Inc.','Microsoft Corporation','Cisco Systems','Intel Corporation','Amazon.com Inc','Vodafone Group Plc','Qualcomm, Inc.','eBay Inc.','Infosys Technologies Limited','Dell Inc.','Facebook, Inc.','TripAdvisor, Inc.','BlackBerry Limited','Puma Biotechnology Inc.','NVIDIA Corporation','Texas Instruments Incorporated','Starbucks Corporation','Netflix, Inc.','Adobe Systems Incorporated','Tesla, Inc.','Marriott International','Electronic Arts Inc.','Western Digital Corporation','Autodesk, Inc.','Activision Blizzard Inc.','T-Mobile US','Mattel Inc','21st Century Fox Class A','Cognizant Technology','Discovery Communications Inc.','Paypal Holdings Inc','GoPro, Inc.','Citrix Systems, Inc.'] stock = [] k=0 for name in company: stock.append([]) stock[k].append("NA") stock[k].append("NA") stock[k].append("NA") stock[k].append("NA") stock[k].append("NA") stock[k].append("NA") stock[k].append("NA") stock[k][0]=company_name[k] newarray = json.dumps(getQuotes(name)) array = newarray.split('"') j=0 for temp in array: j=j+1 if temp.find('Index') != -1 : stock[k][1]=array[j+1] if temp.find('LastTradePrice') != -1: stock[k][2]=array[j+1] if temp.find('LastTradeTime') != -1: stock[k][3]=array[j+1] if temp.find('StockSymbol') != -1: stock[k][4]=array[j+1] if temp.find('Dividend') != -1: stock[k][5]=array[j+1] if temp.find('Yield') != -1: stock[k][6]=array[j+1] k=k+1 return stock
def _parse_and_respond(self, event): """Streams stock data to the channel for the given event. Args: event: Slack event dictionary """ if self._ismessage(event) and self._contains_stock(event['text']): stocks = self._get_stocks(event['text']) for stock in stocks: ticker = self._strip_non_alphabet(stock) # Do not respond if ticker is invalid. if not ticker: continue channel = event['channel'] # Lookup ticker data with google finance try: gfin = getQuotes(ticker)[0] # We want to display the ticker and the price symbol = gfin.get("StockSymbol") price = gfin.get("LastTradePrice") date = gfin.get("LastTradeDateTimeLong") # We aren't going to bother with localization... response = "{} traded at ${} on {}".format(symbol, price, date) self.client.rtm_send_message(channel, response) except Exception: msg = "I was unable to find data on {}.".format(ticker) self.client.rtm_send_message(channel, msg)
def getActualStock(companies): stocks = {} quotes = getQuotes(companies) for quote in quotes: if quote["Index"] == "NASDAQ": return float(quote["LastTradePrice"]) return 0
def get_update(): current_Time = time.strftime("%H:%M") while current_Time != t1: current_Time = time.strftime("%H:%M") if current_Time == t1: stock = getQuotes(stock_input) print('Stock: {0}'.format(stock[0]['StockSymbol'])) print('Current price: ${0}'.format(stock[0]['LastTradePrice']))
def __init__(self, name, symbol): self.name = name self.symbol = symbol try: self.share = Share(symbol) self.quotes = getQuotes(symbol)[0] except urllib.error.HTTPError: a = 2
def get_price_GOOGLE(ticker): #for ticker in list_of_symbols: trade_price = "" try: trade_price = getQuotes(ticker)[0]["LastTradePrice"] #print(trade_price) return float(trade_price) except: f=0
def GoogleFinance(vTarget = '2330'): jsontxt = json.dumps(getQuotes(vTarget), indent=2) #print jsontxt config = json.loads(jsontxt) #print config[0]['LastTradeDateTime'].replace('u\'','').replace('\'','') + ',' + \ #config[0]['LastTradePrice'].replace('u\'','').replace('\'','') return config[0]['LastTradeDateTime'].replace('u\'','').replace('\'','') + ',' + \ config[0]['LastTradePrice'].replace('u\'','').replace('\'','')
def getStockData(stock): # Returns stock price try: data = getQuotes(stock) for i in data: sentence = i["StockSymbol"] + " was traded at " + i["LastTradePrice"] + " at " + i["LastTradeTime"] return sentence except: say("Error, could not find stock " + stock)
def buystock(self, e): stock2buy = random.choice(self.stocklist) quote = getQuotes(stock2buy)[0] price = quote['LastTradePrice'] price = price.strip("'") price = float(price) self.msg_one(e,"I think I'll buy %s for %.2f" % (stock2buy, price)) self.mybalance = self.mybalance - price self.msg_one(e,"My new balance is %.2f" % self.mybalance)
def get_indexes(index_names): symbols = [] prices = [] indexes = getQuotes(index_names) for index in indexes: symbols.append(index['Index'].replace('INDEX','')) prices.append(index['LastTradePrice']) return pd.DataFrame(prices, index=symbols).transpose()
def animate( self, i ): try: print 'animating data on', self.stock self.liveStock = getQuotes( self.stock )[0] self.livePrice = self.liveStock['LastTradePrice'] self.lastDateTime = self.liveStock['LastTradeDateTime'] print self.stock, self.livePrice, self.lastDateTime except Exception, e: print str(e), 'failed to pull price data'
def updatePrices(): print("======= updating prices ==========") for i in models.Stock.objects.all(): try: newprice=float(getQuotes(str(i.code))[0]["LastTradePrice"].replace(',','')) i.diff = newprice-i.price i.price = newprice i.save() except: print("NOT UPDATED")
def getQuote(fundname): """retrieves the last price for fund""" try: info = json.dumps(getQuotes(fundname)) data = json.loads(info) data_dict = {k: v for d in data for k, v in d.items()} return(data_dict['LastTradePrice']) except URLError: msg = """Cannot connect to URL right now, check web connection or try later.""" return msg
def compareData(price): time.sleep(1) data = getQuotes(company) stock = json.dumps(data) data = json.loads(stock) update = data[0]['LastTradePrice'] if price != update: winsound.PlaySound('notif.wav', winsound.SND_FILENAME) print('\n'+update) with open("stocks.dat", "a") as f: f.write('\n'+update+','+str(datetime.datetime.now()))
def analyze(stockTicker): """ Feed the ticker string to googlefinance's "getQuotes" function-- allowing us to retrieve the real time price. At least I hope it is in real time. :param stockTicker: String of the stock ticker you wish to analyze """ quotes = getQuotes(stockTicker) print json.dumps(quotes, indent=2)
def get_quotes(quotes): prices = [0,0,0,0,0] ## Intializes the prices list. prevtime = [dt.utcnow().minute, dt.utcnow().second, dt.utcnow().microsecond] ## Our comparitor for i in range(20): time = [dt.utcnow().minute, dt.utcnow().second, dt.utcnow().microsecond] ## 'Present' time if time[2] > prevtime[2] or time[1] > prevtime[1]: ## Compares our time q = getQuotes(quotes) for j in range(len(q)): prices[j] = q[j]['LastTradePrice'] print(prices) prevtime = time
def getPrice(self, chosenStock): """ Retrieves the last trade price of a stock. :param chosenStock: stock symbol :return: float value of last trade price """ allInfo = getQuotes(chosenStock) theStock = allInfo[0] price = theStock["LastTradePrice"] return float(price)
def index(): main_dict = { 'holdings': p.total_value_readable(), 'day_change_percent': p.total_day_change_readable(perct=True), 'day_change_dollar': p.total_day_change_readable(), 'total_change_percent': p.total_true_change(perct=True), 'total_change_dollar': p.total_true_change(), 'date': date(), 'gluu_q': getQuotes('GLUU')[0]['LastTradePrice'], 'hack_q': getQuotes('HACK')[0]['LastTradePrice'], 'bgmd_q': getQuotes('BGMD')[0]['LastTradePrice'], 'list1': list1, 'list2': list2, 'list3': list3, 'list4': list4, 'list5': list5, 'list6': list6, 'list7': list7 } p.update() return template('index', **main_dict)
def get_quotes(tickers=TICKERS): """Get stock quotes using `googlefinance` Python module. @param: tickers: Dict with ticker symbol as key, and company name as value. Example output from googlefinance.getQuotes() [ { "Index": "NASDAQ", "LastTradeWithCurrency": "114.65", "LastTradeDateTime": "2016-09-22T14:00:40Z", "LastTradePrice": "114.65", "LastTradeTime": "2:00PM EDT", "LastTradeDateTimeLong": "Sep 22, 2:00PM EDT", "StockSymbol": "AAPL", "ID": "22144" }, ... ] """ if not tickers: return error_response() try: # Get the quotes quote_list = getQuotes(tickers.keys()) # Parse the quotes and build a list of phrases quote_phrases = [] for quote in quote_list: symbol = quote['StockSymbol'] price = quote['LastTradePrice'] name = tickers[symbol] quote_phrases.append("{name} is trading at ${price}".format( name=name, price=price)) # Build the speech output sentence speech_output = "Here's how your stocks are doing, {}.".format( ", ".join(quote_phrases)) except Exception as e: print("Failed to get quotes: {}".format(str(e))) return error_response() card_title = "Stock Report" session_attributes = {} should_end_session = True reprompt_text = None return build_response( session_attributes, build_speechlet_response( card_title, speech_output, reprompt_text, should_end_session) )
def get_intraday_quotes(self): if not Prices.get_intraday_prices().get(self.name): Prices.get_intraday_prices()[self.name] = [] price_list = Prices.get_intraday_prices().get(self.name) # self.yahoo_handle = self.yahoo_handle or Share(self.y_symbol) # price = self.yahoo_handle.get_price() # price = float(self.yahoo_handle.get_price()) from googlefinance import getQuotes price = float(getQuotes(self.g_symbol)[0].get('LastTradePrice')) price_list.append((price, len(price_list))) return price_list
def get_stock_prices(self, stocks): for stock in stocks.all(): try: sd = googlefinance.getQuotes(stock.symbol)[0] logger.debug(sd) sa = StockActivity(symbol=stock.symbol, index=self._exist_or_blank(sd['Index']), lasttradedatetime=self._exist_or_blank(sd['LastTradeDateTimeLong']), lasttradeprice=self._exist_or_blank(sd['LastTradePrice']), lasttradewithcurrency=self._exist_or_blank(sd['LastTradeWithCurrency']), stockid=self._exist_or_blank(sd['ID'])) sa.save() stock.latestactivity = sa stock.save() except Exception as e: logger.info("Could not get prices for symbol {0} {1}".format(stock.symbol, e))
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) try: price = json.dumps(getQuotes(symbol)) producer.send(topic=topic_name, value=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 as e: logger.warn('Failed to fetch stock price for %s, caused by: %s', (symbol, e.message))
def savequote(stockid, lastquotestamp, conn): c = conn.cursor() c.execute("select symbolgoogle, symbolyahoo, type from stocks where id=:id", {'id':int(stockid)}) row = c.fetchone() if row['type'].upper() == 'STOCK': symbol = str(row['symbolgoogle']) quote = getQuotes(symbol) #get quote value = quote[0]["LastTradePrice"] #parse uses posix stype for timezone offsets. ISO requires inversion in sign!! correcteddate = quote[0]["LastTradeDateTimeLong"] if correcteddate.find('+'): correcteddate=correcteddate.replace('+', '-') elif correcteddate.find('-'): correcteddate=correcteddate.replace('-', '+') date = dateutil.parser.parse(correcteddate, tzinfos=tzd) timestamp = date.isoformat() if date.tzinfo is None: timestamp += 'Z' elif row['type'].upper() == 'CURRENCY': symbol = str(row['symbolyahoo']) value = float(get_price(symbol)) #get quote date = datetime.datetime.utcnow().replace(tzinfo = pytz.utc) timestamp = date.isoformat() if (lastquotestamp is None) or (dateutil.parser.parse(lastquotestamp, tzinfos=tzd) != date): #Date changed since last quote => save to database c.execute(""" insert into quotes(stockid,timestamp,value) values(?,?,?) """, (int(stockid), timestamp, float(value))) if not(timestamp is None): c = conn.cursor() c.execute(""" UPDATE stocks SET lastquotestamp = ?, lastquote = ? WHERE id = ?; """, (timestamp, float(value), int(stockid))) #update last quote timestamp conn.commit() return timestamp, float(value) else: return None, None
def job(): users = models.User.query.all() for user in users: subs = models.Subscription.query.filter_by(subscriber=user).all() if subs: symbols = list() for sub in subs: symbols.append(sub.symbol) stocks = getQuotes(symbols) prices = ['%s: %s'%(stock['StockSymbol'],stock['LastTradePrice']) for stock in stocks] try: sms = client.messages.create(body=', '.join(prices), to=user.phone, from_=TWILIO_PHONE) print('sending message') except: print('number not verified, remove from database')
def fetch(self): self.logger.info('fetch starting: %s', self.SBL) ''' find the most recent price of the symbol ''' try: x = getQuotes(self.SBL)[0] # 1 = 1 min interval, This is a fetch of the current price. Not sure how often can hit api # so going to fetch every miniute self.GOBJ = Tick(ONE_MINUTE, self.SBL, x[GOOGLE_FINAL_PRICE_FIELD], x[GOOGLE_DATE_FIELD], dividend=x[GOOGLE_DIVIDEND_FIELD], _id=x[GOOGLE_ID_FIELD], _yield=x[GOOGLE_YIELD_FIELD], _type=GOOGLE_TYPE) except: self.GOBJ = None self.logger.warn('issue fetching for: %s', self.SBL) self.logger.info('fetch complete: %s', self.GOBJ) return self.GOBJ
def get_quote(self): text=self.entry.get() s=text.split() stock=s[0] index=s[1] final_quote=stock+":"+index decoded_json=json.dumps(getQuotes(final_quote)) parsed_json = json.loads(decoded_json) self.Value_of_stock.set(parsed_json[0]['LastTradeWithCurrency']) self.time_Stamp_of_stock.set(parsed_json[0]['LastTradeDateTimeLong']) mes="Quote for "+index+" indexed on "+stock+" is "+parsed_json[0]['LastTradeWithCurrency']+" timestamp "+parsed_json[0]['LastTradeDateTimeLong'] client.messages.create( to=to_number, from_=from_number, body=mes ) yfinance=Share(index) historic_data=yfinance.get_historical('2015-11-01','2015-12-31') stock_high_values=map(operator.itemgetter('High'),historic_data) stock_trading_date=map(operator.itemgetter('Date'),historic_data) plt.plot(stock_high_values) plt.show()
def getstockreturn(stockid, conn): comission, taxondividends = getmarketoptions(stockid, conn) c = conn.cursor() c.execute("select * from movements where stockid=:id order by date ASC", {'id':int(stockid)}) movements = c.fetchall() investment = 0.0 cash = 0.0 for movement in movements: exchange = getexchangerate(stockid,movement['date'],conn) if movement['action'].upper() == 'BUY': investment += movement['qty'] * movement['value'] / exchange + comission elif movement['action'].upper() == 'SELL': cash += movement['qty'] * movement['value'] / exchange - comission elif movement['action'].upper() == 'DIVIDEND': cash += movement['qty'] * movement['value'] / exchange * (1-taxondividends) # If stock in portfolio check its current martket value c.execute("select symbolgoogle from stocks where id=:id", {'id':int(stockid)}) symbol = str(c.fetchone()['symbolgoogle']) quote = getQuotes(symbol)[0]["LastTradePrice"] #get quote c.execute("select qty from portfolio where stockid=:id", {'id':int(stockid)}) try: qty = float(c.fetchone()['qty']) cash += qty * float(quote) / exchange except: pass if investment!=0: ireturn = (cash/investment-1)*100 else: ireturn = 0 return ireturn
def list(request): time=datetime.now() day=time.strftime('%A') wea=weather(request) context=[] stock=Stock.objects.filter(username=request.user) for stk in stock: stk_username=str(stk.username) request_user=str(request.user) context_str=[] stk_quote=str(stk.quote) context_str.append(stk_quote) tick=getQuotes(str(stk_quote))[0] ticker=tick["LastTradeWithCurrency"] ticker=str(ticker) context_str.append(ticker) ticker=float(ticker) price=ticker*stk.qty price=round(price,2) context_str.append(stk.qty) context_str.append(price) context.append(context_str) return render(request,'list.html',{'full_name':request.user,'context':context,'weather':wea,'time':time,'day':day})
def update_company_info(yql_result,result_string,db): #global none_stock_list START_SQL="INSERT INTO company_info(" + column_names + ")" + "VALUES" END_SQL= "" VALUES_LIST=[] stored_stock_ask_dict={} result_string_list=result_string.split(",") for stock in result_string_list: stock = "'" + stock + "'" result_string = str(result_string_list).strip("[]") SQL="SELECT Symbol, Ask FROM company_info WHERE Symbol in (" + result_string + ")" previous_ask_list = db.query(SQL) for stock_ask in previous_ask_list: stored_stock_ask_dict[stock_ask['Symbol']]=stock_ask['Ask'] for x in range(int(yql_result['query']['count'])): values=[] ask = str(yql_result['query']['results']['quote'][x]['Ask']).replace(",","") symbol = str(yql_result['query']['results']['quote'][x]['Symbol']) goog_ask = "" try: previous_ask=stored_stock_ask_dict[symbol] except Exception, e: error="key doesn't exist" continue if ask == "None": ##if yql ask is None try: goog_json=getQuotes(symbol) goog_ask = str(goog_json[0]['LastTradePrice']) if goog_ask == "None": SQL = "DELETE FROM company_info WHERE Symbol = '" + symbol + "';" db.query(SQL) continue except Exception, e: if previous_ask == 'None' or previous_ask == 'NULL': ##if stored ask is null or None skip calculation SQL = "DELETE FROM company_info WHERE Symbol ='" + symbol + "';" db.query(SQL) continue