def printStocks(sL) : # Prints the stocks for x in sL: # A for each loop lcd.clear() # Clears the LCD print x + " " + ystockquote.get_price(x) # Gets the price of x and prints it to console lcd.message(x + " " + ystockquote.get_price(x)) # Gets the price and shows it on the lcd print ystockquote.get_change(x) # Gets the price change and prints it to the console lcd.message(ystockquote.get_change(x)) # Gets the price change and shows it on the lcd sleep(10) # Sleeps so it user can read the info
def getChange(self): """Returns the net change in stocks for the group of stocks looked at""" sum = 0; for item in self.stockList: sum += float(ystockquote.get_change(item)) print sum return True
def get_percent_change(symbol): change = ystockquote.get_change(symbol) price = ystockquote.get_price(symbol) percent_change = 100*float(change)/(float(price)-float(change)) percent_decimal = round(Decimal(percent_change), 2) if percent_decimal > 0: return '+'+str(percent_decimal) elif percent_decimal==0: return '0' else: return '-'+str(abs(percent_decimal))
def update(stock1): stock1.lastprice = ystockquote.get_price(stock1) stock1.volume = ystockquote.get_volume(stock1) price_change = ystockquote.get_change(stock1) market_cap = ystockquote.get_market_cap(stock1) get_high = ystockquote.get_52_week_high(stock1) get_low = ystockquote.get_52_week_low(stock1) pb_ratio = ystockquote.get_price_book_ratio(stock1) ebitda = ystockquote.get_ebitda(stock1) dividend = ystockquote.get_dividend_yield(stock1) stock1.save()
def update(stock1): stock1.lastprice = ystockquote.get_price(stock1) stock1.volume = ystockquote.get_volume(stock1) stock1.price_change = float(ystockquote.get_change(stock1)) stock1.market_cap = ystockquote.get_market_cap(stock1) stock1.get_high = ystockquote.get_52_week_high(stock1) stock1.get_low = ystockquote.get_52_week_low(stock1) stock1.pb_ratio = ystockquote.get_price_book_ratio(stock1) stock1.pe_ratio = ystockquote.get_price_earnings_ratio(stock1) stock1.dividend = ystockquote.get_dividend_yield(stock1) stock1.peg = get_peg(stock1) stock1.revenue = get_revenue(stock1) stock1.a_gain = get_annualized_gain(stock1) stock1.save()
def stock_properties(stock): """ Retrieves properties for a given stock and returns a dictionary containing it. """ stock_dict = {} stock_dict["stock_name"] = stock.name stock_dict["stock_ask_realtime"] = ystockquote.get_ask_realtime(stock.symbol) stock_dict["stock_today_open"] = ystockquote.get_today_open(stock.symbol) stock_dict["stock_volume"] = ystockquote.get_volume(stock.symbol) stock_dict["stock_change"] = ystockquote.get_change(stock.symbol) stock_dict["stock_change_percent"] = ystockquote.get_change_percent(stock.symbol)[1:-1] stock_dict["stock_todays_range"] = ystockquote.get_todays_range(stock.symbol)[1:-1] # Gets past dates stock_dict["historical_prices_dict"] = collections.OrderedDict( sorted(eval(stock.historical_prices).items(), key=lambda t: t[0]) ) return stock_dict
def do_thread_loop(self): if ( self.running ): if ( self.mqtt_connected ): for stock in self.tickerlist: ticker = stock.ticker print "querrying for ", ticker now = datetime.datetime.now() open_time = now.replace( hour=self.openhour, minute=self.openmin, second=0 ) close_time = now.replace( hour=self.closehour, minute=self.closemin, second=0 ) open_day = False for day in self.tradingdow: if ( day == datetime.datetime.today().weekday() ): open_day = True if (( now > open_time) and ( now < close_time ) and open_day): self.mqttc.publish( self.basetopic + "/" + ticker + "/name", stock.name, qos = 2, retain=True) try: price = ystockquote.get_price( ticker ) self.mqttc.publish( self.basetopic + "/" + ticker + "/price", price, qos = 2, retain=True) #TODO add previous close value!!!!!!1 change = ystockquote.get_change( ticker ) self.mqttc.publish( self.basetopic + "/" + ticker + "/change", change, qos = 2, retain=True) volume = ystockquote.get_volume( ticker ) self.mqttc.publish( self.basetopic + "/" + ticker + "/volume", volume, qos = 2, retain=True) if ( stock.high_low ): yrhigh = ystockquote.get_52_week_high( ticker ) self.mqttc.publish( self.basetopic + "/" + ticker + "/yrhigh", yrhigh, qos = 2, retain=True) yrlow = ystockquote.get_52_week_low( ticker ) self.mqttc.publish( self.basetopic + "/" + ticker + "/yrlow", yrlow, qos = 2, retain=True) if ( stock.mavg ): avg50 = ystockquote.get_50day_moving_avg( ticker ) self.mqttc.publish( self.basetopic + "/" + ticker + "/50day-ma", avg50, qos = 2, retain=True) avg200 = ystockquote.get_200day_moving_avg( ticker ) self.mqttc.publish( self.basetopic + "/" + ticker + "/200day-ma", avg200, qos = 2, retain=True) self.mqttc.publish( self.basetopic + "/" + ticker + "/time", time.strftime( "%x %X" ), qos = 2, retain=True) except: print "querry error in ystockquote." else: print "Markets closed" self.mqttc.publish( self.basetopic + "/" + ticker + "/null", "", qos = 2, retain=True)
def stock(bot, trigger): if not trigger.group(2): bot.reply('Type .stock followed by the stock you wish to lookup.') else: chosenOne = trigger.group(2) change = ystockquote.get_change(chosenOne) change = change.split("\n")[0] price = ystockquote.get_last_trade_price(chosenOne) price = price.split("\n")[0] allOf = "Current Price: $" + price + " ... " + change bot.reply(allOf) if not trigger.group(4): return else: shares = trigger.group(4) shares = int(shares) change = float(change) if change > 0: winOrLose = "up $" else: winOrLose = "down $" bot.reply("At " + str(shares) + " shares, you are currently " + winOrLose + str(change*shares) + " today.")
symbolList = [] for letter in comment.body[start:end]: symbolList.append(letter) symbol = ''.join(str(e) for e in symbolList if e.isalpha()) #turn list of letters in symbol into string symbol.strip() summaryPage = requests.get('http://finance.yahoo.com/q/pr?s=' + symbol, stream=False) d = summaryPage.content soup1 = BeautifulSoup(d) getSummary = soup1.find_all('p') price = str(ystockquote.get_price(symbol)) change = str(ystockquote.get_change(symbol)) volume = str(ystockquote.get_volume(symbol)) stockExchange = str(ystockquote.get_stock_exchange(symbol)) marketCap = str(ystockquote.get_market_cap(symbol)) bValue = str(ystockquote.get_book_value(symbol)) ebitda = str(ystockquote.get_ebitda(symbol)) mvavg = str(ystockquote.get_200day_moving_avg(symbol)) High = str(ystockquote.get_52_week_high(symbol)) Low = str(ystockquote.get_52_week_low(symbol)) commaData = [] data=[price, change, volume, stockExchange, mvavg, bValue, ebitda, marketCap, High, Low] for individData in data:
def test_get_change(self): value = ystockquote.get_change(self.symbol) self.assertIsInstance(value, str)
def stock(self): """Function that display different stocke's values """ for i in self.trying: i.Destroy() self.trying = [] # values to get from the actual stock exchange text2 = wx.StaticText(self.box, -1, str(ystockquote.get_volume('AC.PA')), pos=(self.Grid * 50 / 10, self.Grid * 50 / 10)) text3 = wx.StaticText(self.box, -1, str(ystockquote.get_volume('AIR.PA')), pos=(self.Grid * 350 / 10, self.Grid * 50 / 10)) text4 = wx.StaticText(self.box, -1, str(ystockquote.get_volume('EN.PA')), pos=(self.Grid * 650 / 10, self.Grid * 50 / 10)) text5 = wx.StaticText(self.box, -1, str(ystockquote.get_volume('CAP.PA')), pos=(self.Grid * 50 / 10, self.Grid * 290 / 10)) text6 = wx.StaticText(self.box, -1, str(ystockquote.get_volume('UG.PA')), pos=(self.Grid * 350 / 10, self.Grid * 290 / 10)) text7 = wx.StaticText(self.box, -1, str(ystockquote.get_volume('ORA.PA')), pos=(self.Grid * 650 / 10, self.Grid * 290 / 10)) text2.SetForegroundColour(wx.Colour(0, 0, 0)) text3.SetForegroundColour(wx.Colour(0, 0, 0)) text4.SetForegroundColour(wx.Colour(0, 0, 0)) text5.SetForegroundColour(wx.Colour(0, 0, 0)) text6.SetForegroundColour(wx.Colour(0, 0, 0)) text7.SetForegroundColour(wx.Colour(0, 0, 0)) font = wx.Font(18, wx.DECORATIVE, wx.NORMAL, wx.NORMAL) text2.SetFont(font) text3.SetFont(font) text4.SetFont(font) text5.SetFont(font) text6.SetFont(font) text7.SetFont(font) stockValue2 = self.trying.append(text2) stockValue3 = self.trying.append(text3) stockValue4 = self.trying.append(text4) stockValue5 = self.trying.append(text5) stockValue6 = self.trying.append(text6) stockValue7 = self.trying.append(text7) #getting the change figure of each value to display the right evolution for j in self.getChange: j.Destroy() self.getChange = [] test2 = ystockquote.get_change('AC.PA') value2 = wx.StaticText(self.box, -1, test2, pos=(self.Grid * 150 / 10, self.Grid * 50 / 10)) changeValue2 = self.getChange.append(value2) test3 = str(ystockquote.get_change('AIR.PA')) value3 = wx.StaticText(self.box, -1, test3, pos=(self.Grid * 450 / 10, self.Grid * 50 / 10)) changeValue3 = self.getChange.append(value3) test4 = str(ystockquote.get_change('EN.PA')) value4 = wx.StaticText(self.box, -1, test4, pos=(self.Grid * 750 / 10, self.Grid * 50 / 10)) changeValue4 = self.getChange.append(value4) test5 = ystockquote.get_change('CAP.PA') value5 = wx.StaticText(self.box, -1, test5, pos=(self.Grid * 150 / 10, self.Grid * 290 / 10)) changeValue5 = self.getChange.append(value5) test6 = str(ystockquote.get_change('UG.PA')) value6 = wx.StaticText(self.box, -1, test6, pos=(self.Grid * 450 / 10, self.Grid * 290 / 10)) changeValue6 = self.getChange.append(value6) test7 = str(ystockquote.get_change('ORA.PA')) value7 = wx.StaticText(self.box, -1, test7, pos=(self.Grid * 750 / 10, self.Grid * 290 / 10)) changeValue7 = self.getChange.append(value7) #changing the color of labels depending on the change if test2.find('-') != -1: value2.SetForegroundColour(wx.Colour(255, 0, 0)) elif test2.find('+') != -1: value2.SetForegroundColour(wx.Colour(0, 150, 0)) if test3.find('-') != -1: value3.SetForegroundColour(wx.Colour(255, 0, 0)) elif test3.find('+') != -1: value3.SetForegroundColour(wx.Colour(0, 150, 0)) if test4.find('-') != -1: value4.SetForegroundColour(wx.Colour(255, 0, 0)) elif test4.find('+') != -1: value4.SetForegroundColour(wx.Colour(0, 150, 0)) if test5.find('-') != -1: value5.SetForegroundColour(wx.Colour(255, 0, 0)) elif test5.find('+') != -1: value5.SetForegroundColour(wx.Colour(0, 150, 0)) if test6.find('-') != -1: value6.SetForegroundColour(wx.Colour(255, 0, 0)) elif test6.find('+') != -1: value6.SetForegroundColour(wx.Colour(0, 150, 0)) if test7.find('-') != -1: value7.SetForegroundColour(wx.Colour(255, 0, 0)) elif test7.find('+') != -1: value7.SetForegroundColour(wx.Colour(0, 150, 0)) value2.SetFont(font) value3.SetFont(font) value4.SetFont(font) value5.SetFont(font) value6.SetFont(font) value7.SetFont(font) wx.CallLater(5000, self.stock)
def get_change(symbol): ''' Return change ''' change = float(ystockquote.get_change(symbol)) return(change)
import ystockquote print ystockquote.get_change('UNXL')
def getQuote(change): if debug == 1: print "Function getQuote" try: change = ystockquote.get_change(tickerSymbol) except urllib2.HTTPError as err: if err.code == 404: print "404 ERROR" else: print "err.code: ", err.code # pass except SocketError as err: if err.errno == errno.ECONNRESET: print "Connection reset by peer." pass # price = ystockquote.get_price(tickerSymbol) while change == 'N/A': print "ERROR: NO PRICE CHANGE DATA!" time.sleep(60) change = ystockquote.get_change(tickerSymbol) changedecimal = Decimal(change) # pricedecimal = Decimal(price) # changedecimal = 0 print "$ Change: ", changedecimal # print pricedecimal # lastclose = Decimal(pricedecimal) - Decimal(changedecimal) # print lastclose # Negative if changedecimal < 0: LED_BRIGHTNESS = abs(int(round(100 * changedecimal))) if LED_BRIGHTNESS > 255: LED_BRIGHTNESS = 255 if LED_BRIGHTNESS < 50: LED_BRIGHTNESS = 50 if debug == 1: print "Brightness: ", LED_BRIGHTNESS sense.clear([LED_BRIGHTNESS, 0, 0]) # Positive if changedecimal > 0: LED_BRIGHTNESS = int(round(100 * changedecimal)) if LED_BRIGHTNESS > 255: LED_BRIGHTNESS = 255 if LED_BRIGHTNESS < 50: LED_BRIGHTNESS = 50 if debug == 1: print "Brightness: ", LED_BRIGHTNESS sense.clear([0, LED_BRIGHTNESS, 0]) # Zero if changedecimal == 0: if debug == 1: print "Zero Change!" sense.clear([50, 50, 50]) time.sleep(1)
def isValid(self, stock): """Checks whether a stock symbol is valid""" if (ystockquote.get_change(stock) == 'N/A'): return False else: return True
def view_stock(request, ticker): if request.user.__class__.__name__ is "CustomUser": c_user = get_object_or_404(CustomUser, pk=request.user.pk) account = Account.objects.get(user=c_user) else: account = False stock = get_object_or_404(Stock, ticker=ticker) companyName = stock.ticker companyName = companyName.upper() stock = Stock.objects.get(ticker=companyName) namer = "'" + companyName + "'" ystock = Share(companyName) the_price = ystock.get_price() regex = 'Business Summary</span></th><th align="right"> </th></tr></table><p>(.+?)</p>' pattern = re.compile(regex) root_url = urllib.urlopen("http://finance.yahoo.com/q/pr?s=" + companyName + "+Profile") htmltext = root_url.read() decoded_str = str(re.findall(pattern, htmltext)).decode("utf8") encoded_str = decoded_str.encode("ascii", "ignore") stock.description = encoded_str stock.description = stock.description[:-2] stock.description = stock.description[2:] stock.book_value = ystockquote.get_book_value(companyName) stock.change = ystockquote.get_change(companyName) # stock.dividend_per_share = ystockquote.get_dividend_per_share(companyName) # stock.dividend_yield = ystockquote.get_dividend_yield(companyName) stock.ebitda = ystockquote.get_ebitda(companyName) stock.fifty_two_week_high = ystockquote.get_52_week_high(companyName) stock.fifty_two_week_low = ystockquote.get_52_week_low(companyName) stock.market_cap = ystockquote.get_market_cap(companyName) stock.short_ratio = ystockquote.get_short_ratio(companyName) stock.stock_exchange = ystockquote.get_stock_exchange(companyName) stock.volume = ystockquote.get_volume(companyName) stock.price = ystock.get_price() # yahoo_finance stock.average_daily_volume = ystock.get_avg_daily_volume() stock.earnings_per_share = ystock.get_price_earnings_ratio() stock.fifty_day_moving_avg = ystock.get_50day_moving_avg() stock.two_hundred_day_moving_avg = ystock.get_200day_moving_avg() stock.price_book_ratio = ystock.get_price_book() stock.last_sale = ystock.get_price() stock.price_earnings_growth_ratio = ystock.get_price_earnings_growth_ratio() stock.price_earnings_ratio = ystock.get_price_earnings_ratio() stock.price_sales_ratio = ystock.get_price_sales() stock.save() vl = [] acl = [] hl = [] ll = [] cl = [] ol = [] days_list = [] d = 0 seven_days_ago = datetime.datetime.now() + datetime.timedelta(-30) today = datetime.datetime.now() days = ystockquote.get_historical_prices("GOOGL", seven_days_ago.strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d")) for day in days.keys(): d += 1 date_label = datetime.datetime.now() + datetime.timedelta(-d) days_list.append(date_label.strftime("%b-%d")) day_info = days.get(day) vol = int(day_info.get("Volume")) vl.append(vol) adjcl = float(day_info.get("Adj Close")) acl.append(adjcl) highs = float(day_info.get("High")) hl.append(highs) lows = float(day_info.get("Low")) ll.append(lows) closes = float(day_info.get("Close")) cl.append(closes) opens = float(day_info.get("Open")) ol.append(opens) volume = vl lows = ll opens = ol highs = hl averages = acl closes = cl days_l = days_list[::-1] context = RequestContext( request, dict( account=account, request=request, stock=stock, volume=volume, lows=lows, highs=highs, opens=opens, closes=closes, averages=averages, days_l=days_l, ), ) return render_to_response("scrapyr_app/stock.html", context=context)
def getQuote(change): if debug == 1: print "Function getQuote" try: change = ystockquote.get_change(tickerSymbol) except urllib2.HTTPError as err: if err.code == 404: print "404 ERROR" else: print "err.code: ", err.code # pass except SocketError as err: if err.errno == errno.ECONNRESET: print "Connection reset by peer." pass # price = ystockquote.get_price(tickerSymbol) while change == 'N/A': print "ERROR: NO PRICE CHANGE DATA!" time.sleep(60) change = ystockquote.get_change(tickerSymbol) changedecimal = Decimal(change) # pricedecimal = Decimal(price) # changedecimal = 0 print "$ Change: ", changedecimal # print pricedecimal # lastclose = Decimal(pricedecimal) - Decimal(changedecimal) # print lastclose # Negative if changedecimal < 0: LED_BRIGHTNESS = abs(int(round(100 * changedecimal))) if LED_BRIGHTNESS > 255: LED_BRIGHTNESS = 255 if debug == 1: print "Brightness: ", LED_BRIGHTNESS strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS) strip.begin() # Colors: GREEN, RED, BLUE solidColor(strip, Color(0, 255, 0)) # Positive if changedecimal > 0: LED_BRIGHTNESS = int(round(100 * changedecimal)) if LED_BRIGHTNESS > 255: LED_BRIGHTNESS = 255 if debug == 1: print "Brightness: ", LED_BRIGHTNESS strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS) strip.begin() # Colors: GREEN, RED, BLUE solidColor(strip, Color(255, 0, 0)) # Zero if changedecimal == 0: if debug == 1: print "Zero Change!" LED_BRIGHTNESS = 10 strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS) strip.begin() strip.setPixelColor(0, Color(0, 255, 0)) strip.setPixelColor(1, Color(255, 0, 0)) strip.setPixelColor(2, Color(0, 255, 0)) strip.setPixelColor(3, Color(255, 0, 0)) strip.setPixelColor(4, Color(0, 255, 0)) strip.setPixelColor(5, Color(255, 0, 0)) strip.setPixelColor(6, Color(0, 255, 0)) strip.setPixelColor(7, Color(255, 0, 0)) strip.show() time.sleep(1)
def individual_stock(request, stock_id): stock1 = get_object_or_404(Stock, pk=stock_id) # Stock Information per Stock stock1.lastprice = ystockquote.get_price(stock1) stock1.volume = ystockquote.get_volume(stock1) price_change = ystockquote.get_change(stock1) market_cap = ystockquote.get_market_cap(stock1) get_high = ystockquote.get_52_week_high(stock1) get_low = ystockquote.get_52_week_low(stock1) pb_ratio = ystockquote.get_price_book_ratio(stock1) ebitda = ystockquote.get_ebitda(stock1) dividend = ystockquote.get_dividend_yield(stock1) # Graph # Last known weekday current_day = weekday().isoformat() # Retrieve live data YYYY-MM-DD historical_price = ystockquote.get_historical_prices( stock1, '2010-01-24', current_day) correct_order = sorted(historical_price) stock_prices = [] dates = [] for values in correct_order: stock_prices.append(historical_price[values]['Adj Close']) dates.append(values) # Convert to Float for p in range(len(stock_prices)): stock_prices[p] = float(stock_prices[p]) # Convert to Datetime Format dates_objects = [] for d in dates: dates_objects.append(datetime.strptime(d, '%Y-%m-%d')) source = ColumnDataSource( data=dict(x=dates_objects, y=stock_prices, time=dates)) # Tools hover = HoverTool(tooltips=[ ('Stock Price', '@y'), ('time', '@time'), ], mode='vline') crosshair = CrosshairTool(dimensions=['height']) TOOLS = [hover, crosshair] plot = figure(x_axis_type="datetime", responsive=True, plot_height=250, tools=TOOLS, toolbar_location=None) plot.line('x', 'y', source=source) first_date = dates[0] last_date = dates[-1] callback = CustomJS(args=dict(x_range=plot.x_range), code=""" var start = cb_obj.get("value"); x_range.set("start", start); x_range.set("end", start+2); """) slider = vform( Slider(start=0, end=100, title="Start Date", callback=callback)) widget_script, widget_div = components(slider) script, div = components(plot) stock1.save() context = { 'stock': stock1, 'hprice': stock_prices, 'widget_script': widget_script, 'widget_div': widget_div, 'the_script': script, 'the_div': div, 'thedate': dates_objects, 'dates': dates } return render(request, 'stocktracker/individual.html', context)
def change(ticker): change = get_change(ticker) data = {"ticker": ticker, "change": change} return data
def view_stock(request, ticker): if request.user.__class__.__name__ is 'CustomUser': c_user = get_object_or_404(CustomUser, pk=request.user.pk) account = Account.objects.get(user=c_user) else: account = False stock = get_object_or_404(Stock, ticker=ticker) companyName = stock.ticker companyName = companyName.upper() stock = Stock.objects.get(ticker=companyName) namer = "'" + companyName + "'" ystock = Share(companyName) the_price = ystock.get_price() regex = 'Business Summary</span></th><th align="right"> </th></tr></table><p>(.+?)</p>' pattern = re.compile(regex) root_url = urllib.urlopen("http://finance.yahoo.com/q/pr?s=" + companyName + "+Profile") htmltext = root_url.read() decoded_str = str(re.findall(pattern, htmltext)).decode("utf8") encoded_str = decoded_str.encode('ascii', 'ignore') stock.description = encoded_str stock.description = stock.description[:-2] stock.description = stock.description[2:] stock.book_value = ystockquote.get_book_value(companyName) stock.change = ystockquote.get_change(companyName) #stock.dividend_per_share = ystockquote.get_dividend_per_share(companyName) #stock.dividend_yield = ystockquote.get_dividend_yield(companyName) stock.ebitda = ystockquote.get_ebitda(companyName) stock.fifty_two_week_high = ystockquote.get_52_week_high(companyName) stock.fifty_two_week_low = ystockquote.get_52_week_low(companyName) stock.market_cap = ystockquote.get_market_cap(companyName) stock.short_ratio = ystockquote.get_short_ratio(companyName) stock.stock_exchange = ystockquote.get_stock_exchange(companyName) stock.volume = ystockquote.get_volume(companyName) stock.price = ystock.get_price() #yahoo_finance stock.average_daily_volume = ystock.get_avg_daily_volume() stock.earnings_per_share = ystock.get_price_earnings_ratio() stock.fifty_day_moving_avg = ystock.get_50day_moving_avg() stock.two_hundred_day_moving_avg = ystock.get_200day_moving_avg() stock.price_book_ratio = ystock.get_price_book() stock.last_sale = ystock.get_price() stock.price_earnings_growth_ratio = ystock.get_price_earnings_growth_ratio( ) stock.price_earnings_ratio = ystock.get_price_earnings_ratio() stock.price_sales_ratio = ystock.get_price_sales() stock.save() vl = [] acl = [] hl = [] ll = [] cl = [] ol = [] days_list = [] d = 0 seven_days_ago = datetime.datetime.now() + datetime.timedelta(-30) today = datetime.datetime.now() days = ystockquote.get_historical_prices( 'GOOGL', seven_days_ago.strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d")) for day in days.keys(): d += 1 date_label = datetime.datetime.now() + datetime.timedelta(-d) days_list.append(date_label.strftime("%b-%d")) day_info = days.get(day) vol = int(day_info.get('Volume')) vl.append(vol) adjcl = float(day_info.get('Adj Close')) acl.append(adjcl) highs = float(day_info.get('High')) hl.append(highs) lows = float(day_info.get('Low')) ll.append(lows) closes = float(day_info.get('Close')) cl.append(closes) opens = float(day_info.get('Open')) ol.append(opens) volume = vl lows = ll opens = ol highs = hl averages = acl closes = cl days_l = days_list[::-1] context = RequestContext( request, dict(account=account, request=request, stock=stock, volume=volume, lows=lows, highs=highs, opens=opens, closes=closes, averages=averages, days_l=days_l)) return render_to_response('scrapyr_app/stock.html', context=context)
def individual_stock(request, stock_id): stock1 = get_object_or_404(Stock, pk=stock_id) # Stock Information per Stock stock1.lastprice = ystockquote.get_price(stock1) stock1.volume = ystockquote.get_volume(stock1) price_change = ystockquote.get_change(stock1) market_cap = ystockquote.get_market_cap(stock1) get_high = ystockquote.get_52_week_high(stock1) get_low = ystockquote.get_52_week_low(stock1) pb_ratio = ystockquote.get_price_book_ratio(stock1) ebitda = ystockquote.get_ebitda(stock1) dividend = ystockquote.get_dividend_yield(stock1) # Graph # Last known weekday current_day = weekday().isoformat() # Retrieve live data YYYY-MM-DD historical_price = ystockquote.get_historical_prices(stock1, '2010-01-24', current_day) correct_order = sorted(historical_price) stock_prices = [] dates = [] for values in correct_order: stock_prices.append(historical_price[values]['Adj Close']) dates.append(values) # Convert to Float for p in range(len(stock_prices)): stock_prices[p] = float(stock_prices[p]) # Convert to Datetime Format dates_objects = [] for d in dates: dates_objects.append(datetime.strptime(d,'%Y-%m-%d')) source = ColumnDataSource(data=dict(x=dates_objects,y=stock_prices, time=dates)) # Tools hover = HoverTool(tooltips=[('Stock Price','@y'),('time','@time'),], mode='vline') crosshair = CrosshairTool(dimensions=['height']) TOOLS = [hover, crosshair] plot = figure(x_axis_type="datetime", responsive = True ,plot_height=250, tools = TOOLS, toolbar_location=None) plot.line('x','y',source=source) first_date = dates[0] last_date = dates[-1] callback = CustomJS(args=dict(x_range=plot.x_range), code=""" var start = cb_obj.get("value"); x_range.set("start", start); x_range.set("end", start+2); """) slider = vform(Slider(start=0, end=100, title="Start Date", callback=callback)) widget_script, widget_div = components(slider) script, div = components(plot) stock1.save() context = {'stock':stock1, 'hprice': stock_prices, 'widget_script': widget_script, 'widget_div': widget_div, 'the_script': script, 'the_div':div, 'thedate': dates_objects, 'dates':dates } return render(request, 'stocktracker/individual.html', context)
def raising(symbol): return float(ystockquote.get_change(symbol)) > 0
#!/usr/bin/env python """Display stock quotes on LEDs.""" import RPi.GPIO as GPIO from seven_segment import print_leds from ystockquote import get_price, get_change pins = [17, 23, 24, 22, 27, 25, 5] GPIO.setmode(GPIO.BCM) GPIO.setup(pins, GPIO.OUT) print_leds(' ', pins) symbols = ['AAPL', 'MSFT', 'F', 'T', 'KO', 'GOOG', 'SYK'] for s in symbols: try: ticker_string = s + ' ' + get_price(s) + ' ' + get_change(s) + ' ' except KeyboardInterrupt: break print_leds(ticker_string, pins, 1) GPIO.cleanup()
#Convert the raw text into an nltk Text object tokens = nltk.wordpunct_tokenize(fulltext) text = nltk.Text(tokens) fdist = FreqDist(text) #Get all words with length > 5 that are not on the stopword list stopwords = nltk.corpus.stopwords.words('english') words = sorted([w for w in set(text) if len(w) >= min_word_length and fdist[w] >= min_word_frequency and w.lower() not in stopwords]) return words for row in companies : #get the stock change and price stock_name = row[0] stock_ticker = row[1] stock_change = ystockquote.get_change(row[1]) stock_price = float(ystockquote.get_price(row[1])) continue_check = False try: float(stock_change[1:]) continue_check = True except Exception, e: continue_check = False if continue_check: new_stock_change = 0 # convert the stock change into a number
def raising(symbol): return float(ystockquote.get_change(symbol))>0
def stock(self): """Function that display different stocke's values """ for i in self.trying: i.Destroy() self.trying = [] # values to get from the actual stock exchange text2 = wx.StaticText(self.box,-1,str(ystockquote.get_volume('AC.PA')),pos=(self.Grid*50/10,self.Grid*50/10)) text3 = wx.StaticText(self.box,-1,str(ystockquote.get_volume('AIR.PA')),pos=(self.Grid*350/10,self.Grid*50/10)) text4 = wx.StaticText(self.box,-1,str(ystockquote.get_volume('EN.PA')),pos=(self.Grid*650/10,self.Grid*50/10)) text5 = wx.StaticText(self.box,-1,str(ystockquote.get_volume('CAP.PA')),pos=(self.Grid*50/10,self.Grid*290/10)) text6 = wx.StaticText(self.box,-1,str(ystockquote.get_volume('UG.PA')),pos=(self.Grid*350/10,self.Grid*290/10)) text7 = wx.StaticText(self.box,-1,str(ystockquote.get_volume('ORA.PA')),pos=(self.Grid*650/10,self.Grid*290/10)) text2.SetForegroundColour(wx.Colour(0,0,0)) text3.SetForegroundColour(wx.Colour(0,0,0)) text4.SetForegroundColour(wx.Colour(0,0,0)) text5.SetForegroundColour(wx.Colour(0,0,0)) text6.SetForegroundColour(wx.Colour(0,0,0)) text7.SetForegroundColour(wx.Colour(0,0,0)) font = wx.Font(18, wx.DECORATIVE, wx.NORMAL, wx.NORMAL) text2.SetFont(font) text3.SetFont(font) text4.SetFont(font) text5.SetFont(font) text6.SetFont(font) text7.SetFont(font) stockValue2 = self.trying.append(text2) stockValue3 = self.trying.append(text3) stockValue4 = self.trying.append(text4) stockValue5 = self.trying.append(text5) stockValue6 = self.trying.append(text6) stockValue7 = self.trying.append(text7) #getting the change figure of each value to display the right evolution for j in self.getChange: j.Destroy() self.getChange = [] test2 = ystockquote.get_change('AC.PA') value2 = wx.StaticText(self.box,-1,test2,pos=(self.Grid*150/10,self.Grid*50/10)) changeValue2 = self.getChange.append(value2) test3 = str(ystockquote.get_change('AIR.PA')) value3 = wx.StaticText(self.box,-1,test3,pos=(self.Grid*450/10,self.Grid*50/10)) changeValue3 = self.getChange.append(value3) test4 = str(ystockquote.get_change('EN.PA')) value4 = wx.StaticText(self.box,-1,test4,pos=(self.Grid*750/10,self.Grid*50/10)) changeValue4 = self.getChange.append(value4) test5 = ystockquote.get_change('CAP.PA') value5 = wx.StaticText(self.box,-1,test5,pos=(self.Grid*150/10,self.Grid*290/10)) changeValue5 = self.getChange.append(value5) test6 = str(ystockquote.get_change('UG.PA')) value6 = wx.StaticText(self.box,-1,test6,pos=(self.Grid*450/10,self.Grid*290/10)) changeValue6 = self.getChange.append(value6) test7 = str(ystockquote.get_change('ORA.PA')) value7 = wx.StaticText(self.box,-1,test7,pos=(self.Grid*750/10,self.Grid*290/10)) changeValue7 = self.getChange.append(value7) #changing the color of labels depending on the change if test2.find('-')!=-1: value2.SetForegroundColour(wx.Colour(255,0,0)) elif test2.find('+')!=-1: value2.SetForegroundColour(wx.Colour(0,150,0)) if test3.find('-')!=-1: value3.SetForegroundColour(wx.Colour(255,0,0)) elif test3.find('+')!=-1: value3.SetForegroundColour(wx.Colour(0,150,0)) if test4.find('-')!=-1: value4.SetForegroundColour(wx.Colour(255,0,0)) elif test4.find('+')!=-1: value4.SetForegroundColour(wx.Colour(0,150,0)) if test5.find('-')!=-1: value5.SetForegroundColour(wx.Colour(255,0,0)) elif test5.find('+')!=-1: value5.SetForegroundColour(wx.Colour(0,150,0)) if test6.find('-')!=-1: value6.SetForegroundColour(wx.Colour(255,0,0)) elif test6.find('+')!=-1: value6.SetForegroundColour(wx.Colour(0,150,0)) if test7.find('-')!=-1: value7.SetForegroundColour(wx.Colour(255,0,0)) elif test7.find('+')!=-1: value7.SetForegroundColour(wx.Colour(0,150,0)) value2.SetFont(font) value3.SetFont(font) value4.SetFont(font) value5.SetFont(font) value6.SetFont(font) value7.SetFont(font) wx.CallLater(5000, self.stock)
def getQuote(change): if debug == 1: print "Function getQuote" try: signal.alarm(10) change = ystockquote.get_change(tickerSymbol) except urllib2.HTTPError as err: if err.code == 404: print "Error: 404 Not Found." else: print "Error: ", err.code except urllib2.URLError as err: print "Error: Connection reset by peer." except SocketError as err: if err.errno == errno.ECONNRESET: print "Error: Connection reset by peer." # price = ystockquote.get_price(tickerSymbol) while change == 'N/A': print "Error: No price change data." time.sleep(60) change = ystockquote.get_change(tickerSymbol) changedecimal = decimal.Decimal(change) # pricedecimal = Decimal(price) # changedecimal = 0 # Reset timeout signal.alarm(0) # Console message with price change print "$ Change: ", changedecimal # print pricedecimal # lastclose = Decimal(pricedecimal) - Decimal(changedecimal) # print lastclose # Negative if changedecimal < 0: LED_BRIGHTNESS = abs(int(round(100 * changedecimal))) if LED_BRIGHTNESS > 255: LED_BRIGHTNESS = 255 if LED_BRIGHTNESS < 50: LED_BRIGHTNESS = 50 if debug == 1: print "Brightness: ", LED_BRIGHTNESS R = [LED_BRIGHTNESS, 0, 0] # Red G = [0, LED_BRIGHTNESS, 0] # Green B = [0, 0, 0] # Black down_arrow = [ R, R, R, R, R, R, R, R, R, R, R, R, R, R, R, R, B, R, R, R, R, R, R, B, B, R, R, R, R, R, R, B, B, B, R, R, R, R, B, B, B, B, R, R, R, R, B, B, B, B, B, R, R, B, B, B, B, B, B, R, R, B, B, B ] sense.set_pixels(down_arrow) time.sleep(1.5) sense.show_message(str(changedecimal), text_colour=[LED_BRIGHTNESS, 0, 0]) # Positive if changedecimal > 0: LED_BRIGHTNESS = int(round(100 * changedecimal)) if LED_BRIGHTNESS > 255: LED_BRIGHTNESS = 255 if LED_BRIGHTNESS < 50: LED_BRIGHTNESS = 50 if debug == 1: print "Brightness: ", LED_BRIGHTNESS R = [LED_BRIGHTNESS, 0, 0] # Red G = [0, LED_BRIGHTNESS, 0] # Green B = [0, 0, 0] # Black up_arrow = [ B, B, B, G, G, B, B, B, B, B, B, G, G, B, B, B, B, B, G, G, G, G, B, B, B, B, G, G, G, G, B, B, B, G, G, G, G, G, G, B, B, G, G, G, G, G, G, B, G, G, G, G, G, G, G, G, G, G, G, G, G, G, G, G ] sense.set_pixels(up_arrow) time.sleep(1.5) sense.show_message(str(changedecimal), text_colour=[0, LED_BRIGHTNESS, 0]) # Zero if changedecimal == 0: if debug == 1: print "Zero Change!" # sense.clear([50, 50, 50]) sense.show_message(str(changedecimal), text_colour=[50, 50, 50]) time.sleep(.5)
def data_type(): print "From the list above, enter the data type you'd like to see" data = raw_input("> ") print "What stock would you like to see data on?" stock = raw_input("> ") if data == 'price' or data == 'Price': print ystockquote.get_price(stock) elif data == 'change' or data == 'Change': print ystockquote.get_change(stock) elif data == 'Volume' or data == 'volume': print ystockquote.get_avg_daily_vol(stock) elif data == 'exchange' or data == 'Exchange': print ystockquote.get_stock_exchange(stock) elif data == 'market cap' or data == 'Market cap' or data == 'Market Cap': print ystockquote.get_market_cap(stock) elif data == 'book value' or data == 'Book value' or data == 'Book Value': print ystockquote.get_book_value(stock) elif data == 'eps' or data == 'EPS': print ystockquote.get_earnings_per_share(stock) elif data == 'short ratio' or data == 'Short Ratio': print ystockquote.get_short_ratio(stock) elif data == 'dividend yield' or data == 'Dividend Yield' or data == 'div yield': print ystockquote.get_dividend_yield(stock) elif data == 'ebitda' or data == 'EBITDA': print ystockquote.get_ebitda(stock) else: print 'Sorry, we don\'t have that data type' quit()