Example #1
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()
Example #2
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()
Example #3
0
    def diff52WeekHigh(self, df):
        allHighs = list()
        for symbol in df.index.values.tolist():
            try:
                baseVal = df.loc[symbol, "PriceCurrent"]
                high52 = float(ystockquote.get_52_week_high(symbol))
                high52 = round(((high52 - baseVal) * 100) / baseVal, 1)
            except:
                high52 = 0
            allHighs.append(high52)

        df[self.diff52Col] = pd.Series(allHighs, index=df.index)
        return df
Example #4
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()
Example #5
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)))
Example #6
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)
 def test_get_52_week_high(self):
     value = ystockquote.get_52_week_high(self.symbol)
     self.assertIsInstance(value, str)
Example #8
0
 def test_get_52_week_high(self):
     value = ystockquote.get_52_week_high(self.symbol)
     self.assertIsInstance(value, str)
Example #9
0
print(ystockquote.get_price_eps_estimate_current_year('GOOG'))



##Some of the methods available
name = ystockquote.get_company_name('GOOG')

mktcap = ystockquote.get_market_cap('GOOG')

print ("Name: %s , Market Cap %s" %(name,mktcap))

ystockquote.get_200_sma()
ystockquote.get_50_sma()
ystockquote.get_annualized_gain()
ystockquote.get_1_year_target()
ystockquote.get_52_week_high()
ystockquote.get_52_week_low()
ystockquote.get_change_200_sma()
ystockquote.get_52_week_range()
ystockquote.get_book_value()
ystockquote.get_eps_estimate_current_year()
ystockquote.get_eps()
ystockquote.get_ticker_trend()
ystockquote.get_short_ratio()
ystockquote.get_revenue()
ystockquote.get_average_daily_volume()
ystockquote.get_float_shares()
ystockquote.get_dividend_yield()
ystockquote.get_notes()
ystockquote.get_pe()
ystockquote.get_all()
Example #10
0
class Stocks(peewee.Model):
    week_high_52 = peewee.FloatField()
    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')
Example #11
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)
Example #12
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)
Example #13
0
				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)
					commaData.append(commaInt)
				
				if float(price) > 0.00:
			
					try:
						stockInfo = ('\n'
Example #14
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)
Example #15
0
				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)
					commaData.append(commaInt)
				
				if float(price) > 0.00:
			
					try:
						stockInfo = ('\n'
Example #16
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)