Ejemplo n.º 1
0
 def test_get_all_alignment_new(self):
     """ Compare bulk 'all_info' values to individual values.
     Currently broken due to misalignment from invalid CSV in
     fields: f6, k3, and maybe j2, a5, b6.
     """
     symbol = 'GOOG'
     all_info = quote_properties.get_all(symbol)
     self.assertIsInstance(all_info, dict)
     self.assertEquals(
         all_info['PreviousClose'],
         ystockquote.get_previous_close(symbol))
     self.assertEquals(
         all_info['Volume'],
         ystockquote.get_volume(symbol))
     self.assertEquals(
         all_info['BidRealtime'],
         ystockquote.get_bid_realtime(symbol))
     self.assertEquals(
         all_info['AskRealtime'],
         ystockquote.get_ask_realtime(symbol))
     self.assertEquals(
         all_info['LastTradePriceOnly'],
         ystockquote.get_last_trade_price(symbol))
     self.assertEquals(
         all_info['Open'],
         ystockquote.get_today_open(symbol))
     self.assertEquals(
         all_info['DaysHigh'],
         ystockquote.get_todays_high(symbol))
     self.assertEquals(
         all_info['LastTradeDate'],
         ystockquote.get_last_trade_date(symbol))
Ejemplo n.º 2
0
 def test_get_all_alignment(self):
     """ Compare bulk 'all_info' values to individual values.
     Currently broken due to misalignment from invalid CSV in
     fields: f6, k3, and maybe j2, a5, b6.
     """
     symbol = 'GOOG'
     all_info = ystockquote.get_all(symbol)
     self.assertIsInstance(all_info, dict)
     self.assertEquals(
         all_info['previous_close'],
         ystockquote.get_previous_close(symbol))
     self.assertEquals(
         all_info['volume'],
         ystockquote.get_volume(symbol))
     self.assertEquals(
         all_info['bid_realtime'],
         ystockquote.get_bid_realtime(symbol))
     self.assertEquals(
         all_info['ask_realtime'],
         ystockquote.get_ask_realtime(symbol))
     self.assertEquals(
         all_info['last_trade_price'],
         ystockquote.get_last_trade_price(symbol))
     self.assertEquals(
         all_info['today_open'],
         ystockquote.get_today_open(symbol))
     self.assertEquals(
         all_info['todays_high'],
         ystockquote.get_todays_high(symbol))
     self.assertEquals(
         all_info['last_trade_date'],
         ystockquote.get_last_trade_date(symbol))
Ejemplo n.º 3
0
 def run(self):
     """
     Main loop
     """
     properties = {"app_id": self.app_id}
     while True:
         # Loop over the tickers and lookup the stock price and volume
         for ticker in self.tickers:
             measurements = []
             price = ystockquote.get_price(ticker)
             volume = ystockquote.get_volume(ticker)
             timestamp = int(time.time())
             if volume == 'N/A' or price == 'N/A':
                 sys.stderr.write(
                     'Could not find ticker \"{0}\", skipping'.format(
                         ticker))
             else:
                 print("ticker: {0}, price: {1}, volume: {2}".format(
                     ticker, price, volume))
                 measurements.append(
                     Measurement(metric='STOCK_PRICE',
                                 value=price,
                                 source=ticker,
                                 properties=properties))
                 measurements.append(
                     Measurement(metric='STOCK_VOLUME',
                                 value=volume,
                                 source=ticker,
                                 properties=properties))
                 self.send_measurements(measurements)
         time.sleep(self.interval)
Ejemplo n.º 4
0
 def run(self):
     """
     Main loop
     """
     properties = {"app_id": self.app_id}
     while True:
         # Loop over the tickers and lookup the stock price and volume
         for ticker in self.tickers:
             measurements = []
             price = ystockquote.get_price(ticker)
             volume = ystockquote.get_volume(ticker)
             timestamp = int(time.time())
             if volume == 'N/A' or price == 'N/A':
                 sys.stderr.write('Could not find ticker \"{0}\", skipping'.format(ticker))
             else:
                 print("ticker: {0}, price: {1}, volume: {2}".format(ticker, price, volume))
                 measurements.append(Measurement(metric='STOCK_PRICE',
                                                 value=price,
                                                 source=ticker,
                                                 properties=properties))
                 measurements.append(Measurement(metric='STOCK_VOLUME',
                                                 value=volume,
                                                 source=ticker,
                                                 properties=properties))
                 self.send_measurements(measurements)
         time.sleep(self.interval)
Ejemplo n.º 5
0
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()
Ejemplo n.º 6
0
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()
Ejemplo n.º 7
0
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()
Ejemplo n.º 8
0
	def run(self):
		"""Plugin main loop"""
		self.loadParameters()
		self.sendEvent("Plugin started","Starting ticker plugin","info",int(time.time()))
		while True:
			# Loop over the items and lookup the stock price and volume
			for i in self.items:
				ticker = str(i["ticker"]).upper()
				price = ystockquote.get_price(ticker)
				volume = ystockquote.get_volume(ticker)
				timestamp = int(time.time())
				if volume == 'N/A' or price == 'N/A':
					self.sendEvent('Ticker Not Found','Could not find ticker \"{0}\", skipping'.format(ticker),"error",timestamp)
				else:
					self.sendMeasurement('BOUNDARY_STOCK_PRICE',price,ticker,timestamp)
					self.sendMeasurement('BOUNDARY_STOCK_VOLUME',volume,ticker,timestamp)
			time.sleep(self.pollInterval)
Ejemplo n.º 9
0
def _main():

    for s in ["NA.TO", "XBB.TO", "NOU.V", "AP-UN.TO", "BRK-A", "AAPL"]:
        print("=============================================")
        print("s: {}".format(s))

        print("get_name: {}".format(ysq.get_name(s)))
        print("get_price: {}".format(ysq.get_price(s)))
        print("get_volume: {}".format(ysq.get_volume(s)))
        print("get_stock_exchange: {}".format(ysq.get_stock_exchange(s)))
        print("get_market_cap: {}".format(ysq.get_market_cap(s)))
        print("get_dividend_yield: {}".format(ysq.get_dividend_yield(s)))
        print("get_price_earnings_ratio: {}".format(
            ysq.get_price_earnings_ratio(s)))

        print("get_52_week_low: {}".format(ysq.get_52_week_low(s)))
        print("get_52_week_high: {}".format(ysq.get_52_week_high(s)))
        print("get_currency: {}".format(ysq.get_currency(s)))
Ejemplo n.º 10
0
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
Ejemplo n.º 11
0
    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)
Ejemplo n.º 12
0
	def getData(self):
		print ("program start");
		self.now  = datetime.now() - timedelta(minutes = 1);
		while True:
			if self.openTime < datetime.now() <= self.closeTime and datetime.now().minute != self.now.minute:
				start_time = time.time();
				self.now = datetime.now()
				for name in self.company_name:
					tmpdict = getQuotes(name);
					price = tmpdict[0]['LastTradePrice'];
					volume = ystockquote.get_volume(name);
					sql = "insert into stockPrediction_onedaystock(name,time,price,volume) values('%s','%s','%s','%s')" % (str(name),str(self.now),str(price),str(volume))
					self.sqlImplement(sql);
				time.sleep(60 - (time.time() - start_time));
			if datetime.now().hour > 18:
				sql = "truncate table stockPrediction_onedaystock";
				self.sqlImplement(sql);
				while self.today == (date.today() - timedelta(days = 1)):
					time.sleep(3600);
				sql = "truncate table stockPrediction_oneyearstock";
				self.initializeOneYear();
				while self.openTime > datetime.now():
					sleep(60);
					'''
Ejemplo n.º 13
0
 def test_get_volume(self):
     value = ystockquote.get_volume(self.symbol)
     self.assertIsInstance(value, str)
Ejemplo n.º 14
0
    week_low_52 = peewee.FloatField()
    price = peewee.FloatField()
    volume = peewee.IntegerField()

    company = peewee.CharField()

    class Meta:
        database = db


Stocks.create_table()

google_arg1 = ystockquote.get_52_week_high('GOOG')
google_arg2 = ystockquote.get_52_week_low('GOOG')
google_arg3 = ystockquote.get_price('GOOG')
google_arg4 = ystockquote.get_volume('GOOG')

google_stocks = Stocks(week_high_52=google_arg1,
                       week_low_52=google_arg2,
                       price=google_arg3,
                       volume=google_arg4,
                       company='Google')
google_stocks.save()

adobe_arg1 = ystockquote.get_52_week_high('ADBE')
adobe_arg2 = ystockquote.get_52_week_low('ADBE')
adobe_arg3 = ystockquote.get_price('ADBE')
adobe_arg4 = ystockquote.get_volume('ADBE')

adobe_stocks = Stocks(week_high_52=adobe_arg1,
                      week_low_52=adobe_arg2,
Ejemplo n.º 15
0
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">&nbsp;</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)
Ejemplo n.º 16
0
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)
Ejemplo n.º 17
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)
Ejemplo n.º 18
0
def get_volume(symbol):
    return ystockquote.get_volume(symbol)
Ejemplo n.º 19
0
				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:
					commaInt = humanize.intcomma(individData)
Ejemplo n.º 20
0
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)
Ejemplo n.º 21
0
def volume(ticker):
    volume = get_volume(ticker)
    data = {"ticker": ticker, "volume": volume}
    return data
Ejemplo n.º 22
0
def get_volume(symbol):
        cur_volume = ystockquote.get_volume(symbol)
        if ('N/A' == cur_volume):
                return 1
	return cur_volume
Ejemplo n.º 23
0
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">&nbsp;</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)
Ejemplo n.º 24
0
 def test_get_volume(self):
     value = ystockquote.get_volume(self.symbol)
     self.assertIsInstance(value, str)
Ejemplo n.º 25
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)
Ejemplo n.º 26
0
				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:
					commaInt = humanize.intcomma(individData)