Exemplo n.º 1
0
def createInfos():
    if db.infos.count() == 0:
        print("Creating Infos!!")
        with open('static/sp100.json', 'rb') as f:
            ls = json.load(f)
            for i in ls:
                timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                symbol = Share(i['name'])
                item = {
                    'name': i['name'],
                    'price': symbol.get_price(),
                    'time': timestamp,
                    'prev_close': symbol.get_prev_close(),
                    'open': symbol.get_open(),
                    'volume': symbol.get_volume(),
                    'pe': symbol.get_price_earnings_ratio(),
                    'eps': symbol.get_earnings_share(),
                    'price_sales': symbol.get_price_sales(),
                    'ebitda': symbol.get_ebitda(),
                    'hotness': ms.hotness_function(i['name']),
                    'BS': ms.bs_function(i['name'])}
                db.infos.insert_one({
                    "name": i['name'],
                    "sector": i['sector'],
                    "data": [item]
                })
        print('Collection Infos Created.')
        return Response('Collection Infos Created.')
Exemplo n.º 2
0
def updateInfos():
    print("Updating Infos!")
    with open('static/sp100.json', 'rb') as f:
        ls = json.load(f)
        for i in ls:
            timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            print (i['name'])
            symbol = Share(i['name'])
            item = {
                'name': i['name'],
                'price': symbol.get_price(),
                'time': timestamp,
                'prev_close': symbol.get_prev_close(),
                'open': symbol.get_open(),
                'volume': symbol.get_volume(),
                'pe': symbol.get_price_earnings_ratio(),
                'eps': symbol.get_earnings_share(),
                'price_sales': symbol.get_price_sales(),
                'ebitda': symbol.get_ebitda(),
                'hotness': ms.hotness_function(i['name']),
                'BS': ms.bs_function(i['name'])}
            db.infos.update(
                {"name": i['name']},
                {
                    "$push": {"data": item}
                }
            )
    print('Collection Infos Updated.')
    return Response('Collection Infos Updated.')
Exemplo n.º 3
0
def fundamentalStats(stock):

	try:

		stokOutput = Share(stock)

		openPrice = stokOutput.get_open()
		closePrice = stokOutput.get_prev_close()	
		dailyDelta = stokOutput.get_change()
		earningsShare = stokOutput.get_earnings_share()	
		fiddyDay = stokOutput.get_50day_moving_avg()
		priceBook = stokOutput.get_price_book()
		peeEee = stokOutput.get_price_earnings_ratio()
		pegRatio = stokOutput.get_price_earnings_growth_ratio()


		if (float(priceBook) < 1.5 and float(peeEee) < 50 and float(pegRatio) < 2 and float(peeEee) > 0):
			csvList = [stock, "open price:", openPrice, "previous close:", closePrice, "daily deltas:", dailyDelta, "earnings per share:", earningsShare, "50 day moving avg:", fiddyDay, "price/book:", priceBook, "price/earnings:", peeEee, "peg:", pegRatio, "\n"]
			print (stock, "will be imported to Excel.") 

			stockPicks = open("picks.csv", "a", newline='')

			writeCSV = csv.writer(stockPicks, dialect='excel')
			for stock in csvList:
				writeCSV.writerow([stock])

		else:
			print (stock, "does not meet criteria.")


	except:
		print(stock, "is missing a defined key statistic.")
Exemplo n.º 4
0
def update_stock(dial, stock):
    stk = Share(stock)
    prev_close_price = float(stk.get_prev_close())
    stk_data = json.loads(json.dumps(getQuotes(stock), indent=2))[0]
    stk_price = float(stk_data['LastTradePrice'])
    NIMBUS.set_dial_value(dial, percentage(stk_price, prev_close_price),
                          "%s:%.2f" % (stock, stk_price))
Exemplo n.º 5
0
def get_stock_info(symbols, moreInfo=False):
	""" 
	Scrape stock info from Yahoo finance
	@Param 'moreInfo': False for getting price, True for getting more information
	@Return 'message': "symbol: Price-number, Open Price-number, Pre Close Price-number, High Price-number, 
						Low price-number"
	"""
	message = ''
	for symbol in symbols:
		try:
			stock = Share(symbol)
			price = stock.get_price()
		except AttributeError:
			price = None
		
		if price == None: # Stock symbol not exists, replace with an alert message
			message += '#' + symbol + ': ' + 'The stock symbol does not exit' + '\n'
		elif moreInfo: 
			message += '#%s: Price-%s, Open Price-%s, Pre Close Price-%s, High Price-%s, Low price-%s\n' \
						% (symbol, price, stock.get_open(), stock.get_prev_close(), stock.get_days_high(), stock.get_days_low())
		else:
			message += '#' + symbol + ': ' + price + '\n'

	alert_message = 'Please type #1 followed by stock symbols to get more information' if moreInfo == True else \
					'Please type #0 followed by stock symbols to get stock price'
	return message if message != '' else alert_message
Exemplo n.º 6
0
def getAllData(ticker):
    stock = Share(ticker)
    data = {
        'name': stock.get_name(),
        'price': stock.get_price(),
        'open': stock.get_open(),
        'prev_close': stock.get_prev_close()
    }
    return data
Exemplo n.º 7
0
def get_stock_price(symbol):
    """ Return [price, open, close, high, low, volume]"""
    stock = Share(symbol)
    return [
        stock.get_price(),
        stock.get_open(),
        stock.get_prev_close(), stock.get_days_high, stock.get_days_low,
        stock.get_volume
    ]
Exemplo n.º 8
0
def stock_search(symbol="YHOO"):
    stock = Share(symbol)
    open_price = stock.get_open()
    close_price = stock.get_prev_close()
    price = stock.get_price()
    high = stock.get_days_high()
    low = stock.get_days_low()
    volume = stock.get_volume()

    return stock, open_price, close_price, price, high, low, volume
Exemplo n.º 9
0
def print_stats(ticker,is_trading_hours):
  stock = Share(ticker)
  stock.refresh()
  
  if(is_trading_hours == True):
    print("Current Price:  $" + stock.get_price() + "\n--------------------------------------")
  else:
    print("Previous Close: $" + stock.get_prev_close())
    print("Opening Price:  $" + stock.get_open())
    print("Current Price:  $" + stock.get_price() + "\n--------------------------------------")
Exemplo n.º 10
0
def makefile():
    # Create the daily quote file
    stocks = open("./symbols.txt", "r")
    for s in stocks:
        s = s.replace("\n", "")
        p = Share(s)
        pc = (p.get_prev_close())
        new_s = s + " " + str(pc) + " 0 0 0 0 0 0 0\n"
        dailyfile.write(new_s)
    stocks.close()
def stock_summary(request, symbol=None):
    if symbol == None:
        symbol = request.POST['symbol']

    current_stock = Stock()
    stock = Share(symbol)
    current_stock.symbol = symbol.upper()
    current_stock.price = stock.get_price()
    current_stock.change = stock.get_change()
    current_stock.volume = stock.get_volume()
    current_stock.prev_close = stock.get_prev_close()
    current_stock.stock_open = stock.get_open()
    current_stock.avg_daily_volume = stock.get_avg_daily_volume()
    current_stock.stock_exchange = stock.get_stock_exchange()
    current_stock.market_cap = stock.get_market_cap()
    current_stock.book_value = stock.get_book_value()
    current_stock.ebitda = stock.get_ebitda()
    current_stock.dividend_share = stock.get_dividend_share()
    current_stock.dividend_yield = stock.get_dividend_yield()
    current_stock.earnings_share = stock.get_earnings_share()
    current_stock.days_high = stock.get_days_high()
    current_stock.days_low = stock.get_days_low()
    current_stock.year_high = stock.get_year_high()
    current_stock.year_low = stock.get_year_low()
    current_stock.fifty_day_moving_avg = stock.get_50day_moving_avg()
    current_stock.two_hundred_day_moving_avg = stock.get_200day_moving_avg()
    current_stock.price_earnings_ratio = stock.get_price_earnings_ratio()
    current_stock.price_earnings_growth_ratio = stock.get_price_earnings_growth_ratio()
    current_stock.price_sales = stock.get_price_sales()
    current_stock.price_book = stock.get_price_book()
    current_stock.short_ratio = stock.get_short_ratio()

    date_metrics = []
    url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+symbol+'/chartdata;type=quote;range=1y/csv'
    page = urllib2.urlopen(url).read()
    pagebreaks = page.split('\n')
    for line in pagebreaks:
        items = line.split(',')
        if 'Company-Name:' in line:
            current_stock.company_name = line[13:len(line)]
            current_stock.save()
        if 'values' not in items:
            if len(items)==6:
                hd = HistoricalData(
                    stock_id = Stock.objects.get(id=int(current_stock.id)).id,
                    date = items[0][4:6]+'/'+items[0][6:9]+'/'+items[0][0:4],
                    close = items[1][0:(len(items[1])-2)],
                    high = items[2][0:(len(items[2])-2)],
                    price_open = items[3][0:(len(items[3])-2)],
                    low = items[4][0:(len(items[4])-2)],
                    volume = items[5][0:-6]+","+items[5][-6:-3]+","+items[5][-3:len(items[5])])
                hd.save()
                date_metrics.append(hd)
    del date_metrics[0]
    return render(request, "stock_summary.html", {'current_stock': current_stock, 'date_metrics': date_metrics})
Exemplo n.º 12
0
def getAllStockData(ticker):
    '''Get a few random tickers.'''
    stock = Share(ticker)
    stock.refresh()
    data = {
        'name': stock.get_name(),
        'price': stock.get_price(),
        'change': stock.get_change(),
        'volume': stock.get_volume(),
        'prev_close': stock.get_prev_close(),
        'open': stock.get_open(),
        'avg_daily_volume': stock.get_avg_daily_volume(),
        'stock_exchange': stock.get_stock_exchange,
        'market_cap': stock.get_market_cap(),
        'book_value': stock.get_book_value(),
        'ebitda': stock.get_ebitda(),
        'dividend_share': stock.get_dividend_share(),
        'dividend_yield': stock.get_dividend_yield(),
        'earnings_share': stock.get_earnings_share(),
        'days_high': stock.get_days_high(),
        'days_low': stock.get_days_low(),
        'year_high': stock.get_year_high(),
        'year_low': stock.get_year_low(),
        '50day_moving_avg': stock.get_50day_moving_avg(),
        '200day_moving_avg': stock.get_200day_moving_avg(),
        'price_earnings_ratio': stock.get_price_earnings_ratio(),
        'price_earnings_growth_ratio': stock.get_price_earnings_growth_ratio(),
        'get_price_sales': stock.get_price_sales(),
        'get_price_book': stock.get_price_book(),
        'get_short_ratio': stock.get_short_ratio(),
        'trade_datetime': stock.get_trade_datetime(),
        'percent_change_from_year_high': stock.get_percent_change_from_year_high(),
        'percent_change_from_year_low': stock.get_percent_change_from_year_low(),
        'change_from_year_low': stock.get_change_from_year_low(),
        'change_from_year_high': stock.get_change_from_year_high(),
        'percent_change_from_200_day_moving_average': stock.get_percent_change_from_200_day_moving_average(),
        'change_from_200_day_moving_average': stock.get_change_from_200_day_moving_average(),
        'percent_change_from_50_day_moving_average': stock.get_percent_change_from_50_day_moving_average(),
        'change_from_50_day_moving_average': stock.get_change_from_50_day_moving_average(),
        'EPS_estimate_next_quarter': stock.get_EPS_estimate_next_quarter(),
        'EPS_estimate_next_year': stock.get_EPS_estimate_next_year(),
        'ex_dividend_date': stock.get_ex_dividend_date(),
        'EPS_estimate_current_year': stock.get_EPS_estimate_current_year(),
        'price_EPS_estimate_next_year': stock.get_price_EPS_estimate_next_year(),
        'price_EPS_estimate_current_year': stock.get_price_EPS_estimate_current_year(),
        'one_yr_target_price': stock.get_one_yr_target_price(),
        'change_percent_change': stock.get_change_percent_change(),
        'divended_pay_date': stock.get_dividend_pay_date(),
        'currency': stock.get_currency(),
        'last_trade_with_time': stock.get_last_trade_with_time(),
        'days_range': stock.get_days_range(),
        'years_range': stock.get_year_range()
    }
    return data
Exemplo n.º 13
0
	def get_close_ticker(self):
		date = datetime.datetime.now()
		weekday = date.weekday()
		if (datetime.time(16,00,30) < date.time() < datetime.time(16,01,30)) and (weekday != 5 or weekday != 6) and (self.posted_close == None or self.posted_close < date.date()):		
			stock_prices = []
			all_stocks = self.get_all_stocks()
			if all_stocks:
				for stock in all_stocks:
					stock_info = Share(stock)
					stock_prices.append('%s: $%s [%s]' % (stock_info.symbol.upper(), stock_info.get_prev_close(), stock_info.get_change()))
				self.posted_close = date.date()
				return ' - '.join(stock_prices)
Exemplo n.º 14
0
def get_stock_prices(stocks):

    data = []
    for s in stocks:
        stock_data = {}
        share = Share(s)
        percent_change = round(float(share.get_change()) / float(share.get_prev_close()) * 100, 2)
        stock_data['symbol'] = s
        stock_data['price'] = round(float(share.get_price()), 2)
        stock_data['change_percent'] = percent_change
        data.append(stock_data)
    return data
Exemplo n.º 15
0
def get_pead_quotes(date):
    '''date = datetime.date(2016,12,6)'''
    previous_businessDt = (date - BDay(1)).date()
    days90backDt = previous_businessDt - datetime.timedelta(days=90)

    asofDate = date.strftime("%Y%m%d")
    previousDt = previous_businessDt.strftime("%Y%m%d")

    interestingQuotes = marketData.getInterestingQuotes(asofDate, previousDt)
    pead_results = []
    for interestingQuote in interestingQuotes:
        yahoo = Share(interestingQuote['symbol'])
        if yahoo.get_open() is None: continue
        quotes = yahoo.get_historical(str(days90backDt),
                                      str(previous_businessDt))
        size = len(quotes)
        total = 0
        for i in range(0, size - 1):
            total += abs(
                float(quotes[i]['Close']) - float(quotes[i + 1]['Open']))

        avg = total / (size - 1)

        squared_deviations_total = 0
        for i in range(0, size - 1):
            squared_deviations_total += math.pow(
                abs(float(quotes[i]["Close"]) - float(quotes[i + 1]["Open"])) -
                avg, 2)

        variance = squared_deviations_total / (size - 1)
        std_dv90days = math.sqrt(variance)

        previous_close = yahoo.get_prev_close()
        today_open = yahoo.get_open()

        todaysmoving = float(today_open) - float(previous_close)

        if (abs(todaysmoving) > std_dv90days):
            if (todaysmoving > 0):
                pead_results.append({
                    'symbol': interestingQuote['symbol'],
                    'action': 'Long'
                })
                #print(interestingQuote['symbol']+' Long '+str(todaysmoving)+' '+str(std_dv90days))
            else:
                pead_results.append({
                    'symbol': interestingQuote['symbol'],
                    'action': 'Short'
                })
                #print(interestingQuote['symbol']+' Short '+str(todaysmoving)+' '+str(std_dv90days))

    return pead_results
Exemplo n.º 16
0
def getStockInfoNow(request):
	if request.method == 'GET':
		sid = request.GET['sid']
		try:
			s = Share(sid+'.TW')
			p = float(s.get_price())
			c = float(s.get_change())
			v = float(s.get_volume())/1000
			pc = float(s.get_prev_close())
		except:
			return JsonResponse({"success": 'false', 'error': 'wrong sid'})
		return JsonResponse({'price': p, 'change': c, 'volume': v, 'prev_close': pc})
	else:
		return JsonResponse({"success": 'false', 'error': 'wrong method'})
def rec(p):
    yahoo = Share(p)
    a = yahoo.get_prev_close()
    b = yahoo.get_year_high()
    c = yahoo.get_year_low()
    d = yahoo.get_open()
    e = yahoo.get_ebitda()
    f = yahoo.get_market_cap()
    g = yahoo.get_avg_daily_volume()
    h = yahoo.get_dividend_yield()
    i = yahoo.get_earnings_share()
    j = yahoo.get_days_low()
    k = yahoo.get_days_high()
    l = yahoo.get_50day_moving_avg()
    m = yahoo.get_200day_moving_avg()
    n = yahoo.get_price_earnings_ratio()
    o = yahoo.get_price_earnings_growth_ratio()
    print p
    print "Previous Close: ", a
    print "Year High", b
    print "Year Low", c
    print "Open:", d
    print "EBIDTA", e
    print "Market Cap", f
    print "Average Daily Volume", g
    print "Dividend Yield", h
    print "Earnings per share", i
    print "Days Range:", j, "-", k
    print "50 Days Moving Average", l
    print "200 Days Moving Average", m
    print "Price Earnings Ratio", n
    print "Price Earnings Growth Ratio", o

    import MySQLdb
    db = MySQLdb.connect(host="127.0.0.1",
                         user="******",
                         passwd="1111",
                         db="stocks",
                         local_infile=1)
    cur = db.cursor()
    cur.execute(
        """
	            INSERT INTO stockapp_info (symbol, prev_close, year_high, year_low, open_price , ebidta, market_cap, avg_daily_vol , dividend_yield, eps , days_low ,days_high, moving_avg_50, moving_avg_200, price_earnings_ratio, price_earnings_growth_ratio)
	            VALUES
	                (%s, %s, %s, %s, %s, %s, %s,%s,%s,%s,%s,%s,%s,%s,%s,%s)

	        """, (p, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o))
    db.commit()
    cur.close()
 def get_today_stock_data(ticker):
     try:
         s = Share(ticker)
         data = {
             'Open': float(s.get_open()),
             'Close': float(s.get_prev_close()),
             'High': float(s.get_days_high()),
             'Low': float(s.get_days_low()),
             'Volume': int(s.get_volume()),
             'Date': datetime.date.today(),
         }
         return data
     except YQLQueryError:
         logger.error("Daily data not found for {}".format(ticker))
     except Exception as e:
         logger.error("Unexpected error occurred: {}".format(e))
     return {}
Exemplo n.º 19
0
def stocks(dict_response):
    message = ""
    try:
        query_text = dict_response['_text'].lower()
        if query_text.find("stocks ") != -1:
            query_text = query_text[7:]
        y = Share(query_text)
        message += "Trading information for " + y.get_name(
        ) + " (" + query_text + ") :\n"
        message += "Opened: " + y.get_open() + "\n"
        message += "Current: " + y.get_price() + "\n"
        message += "Earnings share: " + y.get_earnings_share() + "\n"
        message += "Short ratio: " + y.get_short_ratio() + "\n"
        message += "Previous close: " + y.get_prev_close() + "\n"
    except:
        message = technical_issues()
    return message
 def get_today_stock_data(ticker):
     try:
         s = Share(ticker)
         data = {
             'Open': float(s.get_open()),
             'Close': float(s.get_prev_close()),
             'High': float(s.get_days_high()),
             'Low': float(s.get_days_low()),
             'Volume': int(s.get_volume()),
             'Date': datetime.date.today(),
         }
         return data
     except YQLQueryError:
         logger.error("Daily data not found for {}".format(ticker))
     except Exception as e:
         logger.error("Unexpected error occurred: {}".format(e))
     return {}
Exemplo n.º 21
0
def post():
	## Update stock info
	try:
		stock_list = Stock.objects.all()
		for stock in stock_list:
			try:
				s = Share(stock.symbol)
				stock.price = s.get_price()
				stock.open_price = s.get_open()
				stock.pre_close_price = s.get_prev_close()
				stock.high_price = s.get_days_high()
				stock.low_price = s.get_days_low()
				stock.save()
			except Exception, e:
				pass
	except Exception, e:
		pass
def rec(p):
	yahoo = Share(p)
	a=yahoo.get_prev_close()
	b=yahoo.get_year_high()
	c=yahoo.get_year_low()
	d=yahoo.get_open()
	e=yahoo.get_ebitda()
	f=yahoo.get_market_cap()
	g=yahoo.get_avg_daily_volume()
	h=yahoo.get_dividend_yield()
	i=yahoo.get_earnings_share()
	j=yahoo.get_days_low()
	k=yahoo.get_days_high()
	l=yahoo.get_50day_moving_avg()
	m=yahoo.get_200day_moving_avg()
	n=yahoo.get_price_earnings_ratio()
	o=yahoo.get_price_earnings_growth_ratio()
	print p
	print "Previous Close: ",a
	print "Year High",b
	print "Year Low",c
	print "Open:",d
	print "EBIDTA",e 
	print "Market Cap",f
	print "Average Daily Volume",g 
	print "Dividend Yield",h
	print "Earnings per share",i 
	print "Days Range:", j ,"-",k
	print "50 Days Moving Average",l 
	print "200 Days Moving Average",m
	print"Price Earnings Ratio", n
	print"Price Earnings Growth Ratio",o

	import MySQLdb
	db = MySQLdb.connect(host="127.0.0.1", user="******",passwd="1111", db="stocks",local_infile = 1)  
	cur=db.cursor()
	cur.execute ("""
	            INSERT INTO stockapp_info (symbol, prev_close, year_high, year_low, open_price , ebidta, market_cap, avg_daily_vol , dividend_yield, eps , days_low ,days_high, moving_avg_50, moving_avg_200, price_earnings_ratio, price_earnings_growth_ratio)
	            VALUES
	                (%s, %s, %s, %s, %s, %s, %s,%s,%s,%s,%s,%s,%s,%s,%s,%s)

	        """, (p,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o))
	db.commit() 
	cur.close()
Exemplo n.º 23
0
    def fetch_stock_price(self, stock_unit_key):
        # Step 1: Make HTTP Call to fetch the Stock Details
        # Step 2: Once received, create it into its corresponding model
        # Step 2.1 : Between the models, exchange packet as a native dictionary, rather as a JSON object

        # Get the share price
        share_item = Share(stock_unit_key)

        if share_item.get_open() is None:
            return

        share_item_dict = share_item.data_set

        st_model = StockModel()
        st_model.stock_unit = stock_unit_key
        st_model.stock_title = share_item_dict['Name']

        # Share Price + Unit of Currency
        st_model.stock_price = share_item.get_price(
        ) + " " + share_item_dict['Currency']

        deviation_price = share_item.get_change()
        st_model.stock_deviation = deviation_price + " (" + share_item_dict[
            'ChangeinPercent'] + ") "  # Ex: '-1.83 (-1.59%)'
        if deviation_price[0] == '-':
            st_model.stock_deviation_status = 'Decline'
        else:
            st_model.stock_deviation_status = 'Incline'

        st_model.stock_equity = share_item.get_stock_exchange()
        st_model.stock_last_update_time = 'At close: ' + share_item_dict[
            'LastTradeDateTimeUTC']

        st_model.stock_52wkrange = share_item.get_year_low(
        ) + " - " + share_item.get_year_high()
        st_model.stock_open = share_item.get_open()
        st_model.stock_market_cap = share_item.get_market_cap()
        st_model.stock_prev_close = share_item.get_prev_close()
        st_model.stock_peratio_tte = share_item.get_price_earnings_ratio()

        st_model_to_publish = self.payload_to_publish_dict.get_stock_payload_to_publish(
            st_model)
        self.push_stock_to_delivery_queue(st_model_to_publish, stock_unit_key)
Exemplo n.º 24
0
def getStockInfoNow(request):
    if request.method == 'GET':
        sid = request.GET['sid']
        try:
            s = Share(sid + '.TW')
            p = float(s.get_price())
            c = float(s.get_change())
            v = float(s.get_volume()) / 1000
            pc = float(s.get_prev_close())
        except:
            return JsonResponse({"success": 'false', 'error': 'wrong sid'})
        return JsonResponse({
            'price': p,
            'change': c,
            'volume': v,
            'prev_close': pc
        })
    else:
        return JsonResponse({"success": 'false', 'error': 'wrong method'})
Exemplo n.º 25
0
def selectStock(stocks):
    '''
    select the stock with today's trading volume at least 6 fold higher than 
    average historical trading volume
    '''
    start_time = time()
    resultStock = {}
    count = 0
    num = 0
    for symb in stocks.keys():
        try:
            stock = Share(symb)
            vol = int(stock.get_volume())
            daily_avg_vol = int(stock.get_avg_daily_volume())
            price = float(stock.get_price())
            prevPrice = float(stock.get_prev_close())
            avg_50day = float(stock.get_50day_moving_avg())
            avg_200day = float(stock.get_200day_moving_avg())
        except (TypeError, AttributeError):
            continue
        num += 1
        volRatio = vol / daily_avg_vol
        print num, stocks[symb][0], volRatio

        if volRatio > 6 and price > prevPrice and price > avg_50day:
            count += 1
            stocks[symb].extend([
                vol, daily_avg_vol, volRatio, price, prevPrice, avg_50day,
                avg_200day,
                stock.get_price_earnings_ratio(),
                stock.get_price_book(),
                stock.get_short_ratio(),
                stock.get_dividend_yield()
            ])

    resultStock = {
        symb: stocks[symb]
        for symb in stocks.keys() if len(stocks[symb]) > 1
    }
    print '{} stock(s) has marvelous volume'.format(count)
    print 'total time of running: {} seconds'.format(time() - start_time)
    return resultStock
Exemplo n.º 26
0
class YahooFinanceData:
    """Get data from Yahoo Finance."""
    def __init__(self, symbol):
        """Initialize the data object."""
        from yahoo_finance import Share

        self._symbol = symbol
        self.state = None
        self.price_change = None
        self.price_open = None
        self.prev_close = None
        self.stock = Share(self._symbol)

    def update(self):
        """Get the latest data and updates the states."""
        self.stock.refresh()
        self.state = self.stock.get_price()
        self.price_change = self.stock.get_change()
        self.price_open = self.stock.get_open()
        self.prev_close = self.stock.get_prev_close()
Exemplo n.º 27
0
class YahooFinanceData:
    """Get data from Yahoo Finance."""

    def __init__(self, symbol):
        """Initialize the data object."""
        from yahoo_finance import Share

        self._symbol = symbol
        self.state = None
        self.price_change = None
        self.price_open = None
        self.prev_close = None
        self.stock = Share(self._symbol)

    def update(self):
        """Get the latest data and updates the states."""
        self.stock.refresh()
        self.state = self.stock.get_price()
        self.price_change = self.stock.get_change()
        self.price_open = self.stock.get_open()
        self.prev_close = self.stock.get_prev_close()
Exemplo n.º 28
0
def getStock(ticker):
    stock = Share(ticker)
    #name = stock.get_name()
    po = str(stock.get_open())
    pn =  str(stock.get_price())
    pcl =  str(stock.get_prev_close())
    pc = str(stock.get_percent_change())
    low = str(stock.get_days_low())
    high = str(stock.get_days_high())
    h = datetime.now().strftime("%I")
    p = datetime.now().strftime("%p")
    x = ticker.upper() + "\nCurrent: " + pn +"\nClose: " + pcl + "\nChange: "+ pc + "\nLow: " + low + "\nHigh: " + high
    y = ticker.upper() + "\nCurrent: " + pn + "\nOpen: " + po + "\nChange: " + pc + "\nLow: " + low + "\nHigh: " + high
    
    if h <= "4" and p == "PM":
        return x
    elif h >= "4" and p == "PM":
        return y
    elif h <= "8" and p == "AM":
        return y
    else:
        return x
Exemplo n.º 29
0
def moreInfo(from_number):
    #query to find the stock the user last looked up
    conn = mysql.connect()
    cur = conn.cursor()
    q = '''SELECT * FROM last_lookup WHERE phone = %s'''
    cur.execute(q, [from_number])
    rv = cur.fetchone()

    #get stock information
    quote = Share(str(rv[1]))
    prevClose = quote.get_prev_close()
    openPrice = quote.get_open()
    volume = quote.get_volume()

    #if we get all the information back respond back with more info
    if prevClose and openPrice and volume:
        retStr = "PrevClose: " + prevClose + " OpenPrice: " + openPrice + " Volume: " + volume
    #else the user has not looked up a stock yet
    else:
        retStr = "ticker still not found"

    return retStr
Exemplo n.º 30
0
def moreInfo(from_number):
    #query to find the stock the user last looked up
    conn = mysql.connect()
    cur = conn.cursor()
    q = '''SELECT * FROM last_lookup WHERE phone = %s'''
    cur.execute(q,[from_number])
    rv = cur.fetchone()
    
    #get stock information
    quote = Share(str(rv[1]))
    prevClose = quote.get_prev_close()
    openPrice = quote.get_open()
    volume = quote.get_volume()
    
    #if we get all the information back respond back with more info
    if prevClose and openPrice and volume:
        retStr = "PrevClose: "+prevClose+" OpenPrice: "+openPrice+" Volume: "+ volume
    #else the user has not looked up a stock yet
    else:
        retStr = "ticker still not found"
    
    return retStr
Exemplo n.º 31
0
    def __init__(self, stock, sharesList):
        from yahoo_finance import Share

        self.stock = stock[0]
        self.index = str(self.stock['Index'])
        self.symbol = str(self.stock['StockSymbol'])
        self.shares = int(sharesList[self.symbol])
        self.price = float(self.stock['LastTradePrice'])
        self.time = str(self.stock['LastTradeTime'])
        self.timeLong = str(self.stock['LastTradeDateTimeLong'])
        self.dateTime = str(self.stock['LastTradeDateTime'])
        self.lastCurrency = self.stock['LastTradeWithCurrency']
        self.ident = str(self.stock['ID'])

        # get previous close
        x = Share(self.symbol)
        self.prevClose = float(x.get_prev_close())

        # get changes in stock prices
        self.dayChange = self.price - self.prevClose
        self.gain = self.dayChange * self.shares
        self.change = (self.price - self.prevClose) / self.prevClose * 100
Exemplo n.º 32
0
class YahooFinanceData(object):
    """Get data from Yahoo Finance."""

    def __init__(self, name, symbol):
        """Initialize the data object."""
        from yahoo_finance import Share

        self._name = name
        self._symbol = symbol
        self.state = None
        self.price_change = None
        self.price_open = None
        self.prev_close = None
        self.stock = Share(symbol)

    @Throttle(MIN_TIME_BETWEEN_UPDATES)
    def update(self):
        """Get the latest data and updates the states."""
        self.stock.refresh()
        self.state = self.stock.get_price()
        self.price_change = self.stock.get_change()
        self.price_open = self.stock.get_open()
        self.prev_close = self.stock.get_prev_close()
Exemplo n.º 33
0
#!/usr/bin/python
#coding=utf-8
from yahoo_finance import Share
yahoo = Share('0405.HK')
print yahoo.get_open()
print yahoo.get_price()
print yahoo.get_prev_close();
print yahoo.get_trade_datetime()

#87001.HK  1426.HK  1275.HK 6139.HK

yahoo = Share('87001.HK')
print yahoo.get_open()
print yahoo.get_price()
print yahoo.get_trade_datetime()

Exemplo n.º 34
0
class StockAnalysis:

	stock_symbol = 'YHOO'	
	stock_company_name = "Yahoo Inc,"
	quote = Share(stock_symbol)
	name = quote.get_name()
	stock_company_name = name.split(". ")

	def __init__(self,symbol):
		self.stock_symbol = symbol
		self.quote = Share(self.stock_symbol)
		self.name = self.quote.get_name()
		self.stock_company_name = self.name.split(". ")
		
		
	def getStockSymbol(self):
		return self.stock_symbol 

	def getStockPriceInfo(self,symbol):
		stock_price = self.quote.get_price()
		currency = self.quote.get_currency()
		#name = self.quote.get_name()
		#stock_company_name = name.split(". ")
		price_info = {'Symbol':symbol,'Price':stock_price,'Currency':currency,'Name':self.stock_company_name[0]}
		return price_info

	def getDividendYieldInfo(self,symbol):
		dividend_yield = self.quote.get_dividend_yield()
		dividend_info = {'Symbol':symbol,'DividendYield':dividend_yield,'Unit':'%'}
		return dividend_info

	def getPayOurRatio(self,symbol):
		dividend_per_share = self.quote.get_dividend_share()
		EPS_current_year = self.quote.get_EPS_estimate_current_year()
		pay_out_ratio = (float(dividend_per_share) / float(EPS_current_year))*100
		pay_out_ratio =  float("{0:.2f}".format(pay_out_ratio))
		pay_out_info = {'Symbol':symbol,'PayOut Ratio':pay_out_ratio, "Unit":"%",'Name':self.stock_company_name[0]}
		return pay_out_info

	def getDeividendDetails(self,symbol):
		dividend_per_share = self.quote.get_dividend_share()
		EPS_current_year = self.quote.get_EPS_estimate_current_year()
		dividend_yield = self.quote.get_dividend_yield()
		hold_date = self.quote.get_ex_dividend_date()
		payout_date = self.quote.get_dividend_pay_date()

		if dividend_per_share is None:
			dividend_per_share = "0"
			dividend_yield = "0%"
			payout_date = "None"
			hold_date = "None"
		pay_out_ratio = (float(dividend_per_share) / float(EPS_current_year))*100
		pay_out_ratio =  str(float("{0:.2f}".format(pay_out_ratio)))+"%"
		
		dividend_info = {'Symbol':symbol, 'DividedPerShare':dividend_per_share, 'EPSCurrentYearEstimation': EPS_current_year, 'PayOutRatio':pay_out_ratio,'ExDividedDate':hold_date,'LastPayoutDate':payout_date,'DividendYield':dividend_yield,'Name':self.stock_company_name[0]}
		return dividend_info
	
	def getExDividedDate(self,symbol):
		hold_date = self.quote.get_ex_dividend_date()
		payout_date = self.quote.get_dividend_pay_date()
		data = {'Symbol':symbol,'ExDividedDate':hold_date,'LastPayoutDate':payout_date,'Name':self.stock_company_name[0]}
		return data
		
	def isDividedRateHealthy(self):
		pass

	def getDividendDateDetails(self):
		pass
	def getNumberOfOutStandingShares(self,symbol):
		total_market_cap = self.quote.get_market_cap()
		current_price = self.quote.get_prev_close()
		if "B" in total_market_cap:
			total_market_cap = total_market_cap.rstrip("B")
			total_market_cap = float(total_market_cap)*1000000000
		elif "M" in total_market_cap:
			total_market_cap = total_market_cap.rstrip("M")
			total_market_cap = float(total_market_cap)*100000000
		out_standing_shares = (total_market_cap/float(current_price))/1000000
		out_standing_shares = round(out_standing_shares,2)
		data = {'Symbol':symbol,'OutStandingShares':out_standing_shares,'Name':self.stock_company_name[0]}
		return data

	def get200DaysLowPrice(self,symbol):
		pass
	def get200DaysHighPrice(self,symbol):
		pass
	
	def get50DaysLowPrice(self,symbol):
		pass
	def get50DaysHighPrice(self,symbol):
		pass
	def getPERation(self):
		pass
Exemplo n.º 35
0
		
	if datetime.now().hour > 16:
		sql = "truncate table oneDayStock";
		sqlImplement(sql, cursor, db);
		for name in company_name:
			stock = Share(name);
			Open = stock.get_open();
			Volume = stock.get_volume();
			High = stock.get_days_high();
			Low = stock.get_days_low();
			sql = "delete from oneYearStock where time = '%s'" %oneYearBefore;
			sqlImplement(sql, cursor, db);
			today = date.today();
			while True:
				if today != date.today():
					Close = stock.get_prev_close();
					sql = "insert into oneYearStock(name,time,open,close,high,low,volume) values('%s','%s','%s','%s','%s','%s','%s')" %(str(name),str(today),str(Open),str(Close),str(High),str(Low),str(Volume));
					sqlImplement(sql, cursor, db);
				else:
					time.sleep(3600);
			oneYearBefore = today - timedelta(days = 365);
	print ("give u 10 sec to click y to jummp out of the program");
	start_time = time.time();
	while 1:
		while msvcrt.kbhit():
			msvcrt.getch();
		if msvcrt.kbhit():
			key = ord(msvcrt.getche());
			if key in map(ord, 'yY'):
				print ('');
				print ('jump out of program');
Exemplo n.º 36
0
def getAllDataList(ticker):
    '''Get the all data for the given ticker in a list'''
    stock = Share(ticker)
    data = [ticker, stock.get_name(), stock.get_price(), stock.get_open(), stock.get_prev_close()]
    return data
Exemplo n.º 37
0
# The "extract" phase loops through stocks from a list stored in stocks.py
# daily and stores it in a Pandas dataframe

print("Extracting stock data from Yahoo Finance for the following stocks:")
print(stocks_list)
print("Extracting...")

df = pd.DataFrame(
    columns=["stock", "open", "high", "low", "close", "volume", "date"])

i = 1
for item in stocks_list:
    stock = Share(item)
    df.loc[i] = [
        item,
        stock.get_open(),
        stock.get_days_high(),
        stock.get_days_low(),
        stock.get_prev_close(),
        stock.get_volume(),
        dt.date.today()
    ]
    i += 1

print("Returning generated DataFrame:")
print(df)

# The "load" phase takes the formatted dataframe and loads it into a Postgresql
# database where they will be available for analysis
Exemplo n.º 38
0
class Company:
    def __init__(self, name, symbol):
        self.name = name
        self.symbol = symbol
        try:
            self.share = Share(symbol)
            self.quotes = getQuotes(symbol)[0]
        except urllib.error.HTTPError:
            a = 2

    def __init__(self, symbol):
        self.name = symbol
        self.symbol = symbol
        try:
            self.share = Share(symbol)
            self.quotes = getQuotes(symbol)[0]
        except urllib.error.HTTPError:
            a = 2

    def refresh(self):
        self.share = Share(self.symbol)
        self.quotes = getQuotes(self.symbol)[0]

    def get_last_close(self):
        return self.share.get_prev_close()

    def get_price(self):
        self.refresh()
        return self.quotes["LastTradePrice"]

    def get_historical(self, start, end):
        return self.share.get_historical(start, end)

    def check_history(self, daysback):
        self.refresh()
        low = counter = high = close = 0
        historical = self.get_historical(
            str(date.today() - timedelta(int(daysback))), str(date.today()))
        #pprint(historical)
        print("Current Price", self.quotes["LastTradePrice"])
        higher = float(historical[0]["High"])
        higher_date = lower_date = historical[0]["Date"]
        lower = float(historical[0]["Low"])

        for h in historical:
            if (lower > float(h["Low"])):
                lower = float(h["Low"])
                lower_date = h["Date"]
            if (higher < float(h["High"])):
                higher = float(h["High"])
                higher_date = h["Date"]
            close += float(h["Close"])
            low += float(h["Low"])
            high += float(h["High"])
            counter += 1

        self.close_avg = float(int(1000 * close / counter) / 1000)

        self.low_avg = float(int(1000 * low / counter) / 1000)
        self.lower = lower
        self.lower_date = lower_date

        self.high_avg = float(int(1000 * high / counter) / 1000)
        self.higher = higher
        self.higher_date = higher_date
        self.general_info = {
            "Close Avg": self.close_avg,
            "Low Avg": self.low_avg,
            "Lower": self.lower,
            "Lower Date": self.lower_date,
            "High Avg": self.high_avg,
            "Higher": self.higher,
            "Higher Date": self.higher_date
        }

        return self.general_info
Exemplo n.º 39
0
class Market:
    __PULL_INTERVAL_IN_MIN = 5

    def __init__(self, s):
        self.share_string = s
        self.share = Share(s)

        self.current_price = self.share.get_price()
        self.price = self.current_price
        self.market_cap = self.share.get_market_cap()
        self.open_price = self.share.get_open()
        self.prev_close_price = self.share.get_prev_close()
        self.percent_change = self.share.get_percent_change()

        self.price_array = []
        self.time_array = []

    def pullPrices(self):
        file_string = "share_" + self.share_string + ".dat"
        dataFile = open(file_string, "w+")
        start_time = int(time.strftime("%-S"))
        last_time = start_time

        while (1 == 1):
            current_time = int(time.strftime("%-S"))
            if (current_time >= 60):
                current_time = 0

            if (current_time - last_time < 0):
                last_time = -60 - (current_time - last_time)

            if (int(time.strftime("%-S")) - last_time >=
                    self.__PULL_INTERVAL_IN_MIN):
                dataFile.write(time.strftime('%l:%M%p, %b %d, %Y') + "\t")
                dataFile.write(self.share.get_price())
                dataFile.write("\n")
                dataFile.flush()
                last_time = int(time.strftime("%-S"))

    def __storeData(self, filename):
        dataFile = open(filename, "r")
        lineList = dataFile.readLines()

        for i in range(len(lineList)):
            index1 = lineList[i].index('\t')
            price = float(lineList[i][index1:])
            price_array.append(price)

        dataFile.close()

    def getSlope(self, filename):
        __storeData(filename)

        length = len(self.price_array)
        current_slope = (
            self.price_array[length] - self.price_array[length - 1]) / (
                self.time_array[length] - self.time_array[length - 1])
        return current_slope

    def getSecondDegreeSlope(self, filename):
        __storeData(filename)

        length = len(price_array)
        current_slope = (
            self.price_array[length] - self.price_array[length - 1]) / (
                self.time_array[length] - self.time_array[length - 1])
        last_slope = (
            self.price_array[length - 1] - self.price_array[length - 2]) / (
                self.time_array[length - 1] - self.time_array[length - 2])

        current_secondDegreeSlope = (current_slope - last_slope) / (
            self.time_array[length] - self.time_array[length - 1])

        return current_secondDegreeSlope
Exemplo n.º 40
0
class Market:
    __PULL_INTERVAL_IN_MIN = 5
            
    def __init__ (self, s):
        self.share_string       = s
        self.share              = Share(s)
        
        self.current_price      = self.share.get_price()
        self.price              = self.current_price
        self.market_cap         = self.share.get_market_cap()
        self.open_price         = self.share.get_open()
        self.prev_close_price   = self.share.get_prev_close()
        self.percent_change     = self.share.get_percent_change()
        
        self.price_array = []
        self.time_array = []
    
    
    def pullPrices(self):
        file_string = "share_" + self.share_string + ".dat"
        dataFile = open(file_string, "w+")
        start_time = int(time.strftime("%-S"))
        last_time = start_time
        
        while (1 == 1):
            current_time = int(time.strftime("%-S"))
            if (current_time >= 60):
                current_time = 0
            
            if (current_time - last_time < 0):
                last_time = -60 - (current_time - last_time)
                
            if (int(time.strftime("%-S")) - last_time >= self.__PULL_INTERVAL_IN_MIN):
                dataFile.write (time.strftime('%l:%M%p, %b %d, %Y') + "\t")
                dataFile.write (self.share.get_price())
                dataFile.write ("\n")
                dataFile.flush ()
                last_time = int(time.strftime("%-S"))
    
    
    
    def __storeData(self, filename):
        dataFile = open(filename, "r")
        lineList = dataFile.readLines()
        
        for i in range(len(lineList)):
            index1 = lineList[i].index('\t')
            price = float(lineList[i][index1:])
            price_array.append(price)
        
        dataFile.close() 
    
    
    def getSlope(self, filename):
        __storeData(filename)
        
        length = len(self.price_array)
        current_slope = (self.price_array[length] - self.price_array[length-1])/(self.time_array[length] - self.time_array[length-1])
        return current_slope
        
        
    def getSecondDegreeSlope(self, filename):
        __storeData(filename)
        
        length = len(price_array)
        current_slope = (self.price_array[length] - self.price_array[length-1])/(self.time_array[length] - self.time_array[length-1])
        last_slope = (self.price_array[length-1] - self.price_array[length-2])/(self.time_array[length-1] - self.time_array[length-2])
        
        current_secondDegreeSlope = (current_slope - last_slope)/(self.time_array[length] - self.time_array[length-1])
        
        return current_secondDegreeSlope
Exemplo n.º 41
0
    "    avg_200"

i = 0
for ticker in stocks:

    sys.exit()
    try:
        if (i % 10) == 0:
            print(row_title)
        ticker = ticker.rstrip()
        if len(ticker) == 0:
            continue
        stock = Share(ticker)
        stock.refresh()
        change = (float(stock.get_price()) - float(
            stock.get_prev_close())) / float(stock.get_prev_close())
        change = round(change * 100.0, 2)
        if change > 0.0:
            change = '+' + str(change)
        else:
            change = str(change)

        line = ticker.ljust(7)
        line += stock.get_price().ljust(9)+ change.ljust(8)+ stock.get_volume().ljust(11) + \
            str(round(float(stock.get_volume())/float(stock.get_avg_daily_volume())*100.0)).ljust(8) +\
            stock.get_open().ljust(10)+ \
            stock.get_days_low().ljust(10)+ \
            stock.get_days_high().ljust(10)+ \
            stock.get_year_low().ljust(10)+ \
            stock.get_year_high().ljust(10)
        line = line + str(stock.get_market_cap()).ljust(11) + \
Exemplo n.º 42
0
def find_prev_closing_price(sym):
    p = Share(sym)
    return p.get_prev_close()
Exemplo n.º 43
0
def stock_quote_get():
    print(request.args.get('symbol'))
    symbol = str(request.args.get('symbol'))

    # get all the relevant data from the Yahoo Finance API
    stock = Share(symbol)

    stock_name = stock.get_name()
    stock_symbol = stock.symbol
    stock_price = stock.get_price()
    stock_change = stock.get_change()
    stock_change_pct = stock.get_percent_change()

    prev_close = stock.get_prev_close()
    open = stock.get_open()
    day_range = stock.get_days_range()
    year_range = stock.get_year_range()
    volume = stock.get_volume()
    avg_volume = stock.get_avg_daily_volume()
    market_cap = stock.get_market_cap()
    pe_ratio = stock.get_price_earnings_ratio()
    eps = stock.get_earnings_share()
    dividend = stock.get_dividend_share()
    dividend_yld = stock.get_dividend_yield()
    dividend_ex_date = stock.get_ex_dividend_date()
    yr_target = stock.get_one_yr_target_price()

    historical = stock.get_historical('2017-01-01',
                                      date.isoformat(date.today()))

    # put the data into the DynamoDB database
    table = dynamodb.Table('Stocks')
    response = table.put_item(
        Item={
            'symbol': symbol,
            'date': date.isoformat(date.today()),
            'prev_close': prev_close,
            'open': open,
            'day_range': day_range,
            'year_range': year_range,
            'volume': volume,
            'avg_volume': avg_volume,
            'market_cap': market_cap,
            'pe_ratio': pe_ratio,
            'eps': eps,
            'dividend': dividend,
            'dividend_yld': dividend_yld,
            'dividend_ex_date': dividend_ex_date,
            'yr_target': yr_target,
        })

    close_history = []

    for point in historical:
        close_date = point['Date']
        close_date = int(
            time.mktime(datetime.strptime(close_date, "%Y-%m-%d").timetuple()))
        close_price = point['Adj_Close']
        close_price = float(close_price)
        close_history.append([close_date, close_price])

    return render_template("stock/stock_detail.html",
                           stock_name=stock_name,
                           stock_symbol=stock_symbol,
                           stock_price=stock_price,
                           stock_change=stock_change,
                           stock_change_pct=stock_change_pct,
                           prev_close=prev_close,
                           open=open,
                           day_range=day_range,
                           year_range=year_range,
                           volume=volume,
                           avg_volume=avg_volume,
                           market_cap=market_cap,
                           pe_ratio=pe_ratio,
                           eps=eps,
                           dividend=dividend,
                           dividend_yld=dividend_yld,
                           dividend_ex_date=dividend_ex_date,
                           yr_target=yr_target,
                           close_history=close_history)
Exemplo n.º 44
0
# Give me a list of symbols in the S&P500 that are down more than 10% in one day.
# 
# Joey <*****@*****.**>
# pip install yahoo-finance
# pip install finsymbols

from finsymbols import get_sp500_symbols
from yahoo_finance import Share

sp500 = get_sp500_symbols()

for d in sp500:
    symbol = d['symbol']
    #print "Checking: %s" % symbol
    stockblob = Share(symbol)
    close = stockblob.get_prev_close()
    close = float(close)
    change = stockblob.get_change()
    change = float(change)

    if change < 0:  # Negative number (stock is down)
        change = abs(change)
        percent = (change / close) * 100
        if percent > 10: # Down more than 10%, looks interesting.
            print "%s is down %s" % (symbol, percent)
Exemplo n.º 45
0
row_title = "\nticker price    price%  volume     volume% open      day_low   day_high  year_low  year_high market_cap P/E     avg_50" +\
    "    avg_200"

i=0
for ticker in stocks:

    sys.exit()
    try:
        if (i%10) == 0:
            print(row_title)
        ticker = ticker.rstrip()
        if len(ticker) == 0:
            continue
        stock = Share(ticker)
        stock.refresh()
        change = (float(stock.get_price()) - float(stock.get_prev_close()))/float(stock.get_prev_close()) 
        change = round(change *100.0, 2)
        if change > 0.0:
            change= '+' + str(change)
        else:    
            change =str(change)
          
        line = ticker.ljust(7) 
        line += stock.get_price().ljust(9)+ change.ljust(8)+ stock.get_volume().ljust(11) + \
            str(round(float(stock.get_volume())/float(stock.get_avg_daily_volume())*100.0)).ljust(8) +\
            stock.get_open().ljust(10)+ \
            stock.get_days_low().ljust(10)+ \
            stock.get_days_high().ljust(10)+ \
            stock.get_year_low().ljust(10)+ \
            stock.get_year_high().ljust(10)
        line = line + str(stock.get_market_cap()).ljust(11) + \
Exemplo n.º 46
0
    def on_message(self, message):
        print_logger.debug("Received message: %s" % (message))

        if "ValidateTicker" in message:
            message = message.split(":")

            if len(message) != 2:
                print_logger.error("Malformed ticker validation request")
                self.write_message("ValidationFailed:Malformed")
                return

            ticker = message[1]

            if validate_ticker(ticker):
                self.write_message("ValidationSucceeded:%s" % ticker)
                print_logger.debug("Ticker was valid")
            else:
                self.write_message("ValidationFailed:%s" % ticker)
                print_logger.debug("Ticker was bad")

            return

        elif "GetCompanyName" in message:
            print_logger.debug("You got here")
            message = message.split(":")
            company_ticker = message[1]
            company_name = get_company_title(company_ticker)

            self.write_message("CompanyName:%s" % company_name)

        elif "GetStockData" in message:
            message = message.split(":")

            if len(message) != 2:
                print_logger.error("Malformed Message from Client")
                return

            ticker = message[1]

            # Get ticker information
            share_data = Share(ticker)
            price = share_data.get_price()
            percent_change = share_data.get_change()
            previous_close = share_data.get_prev_close()
            open_price = share_data.get_open()
            volume = share_data.get_volume()
            pe_ratio = share_data.get_price_earnings_ratio()
            peg_ratio = share_data.get_price_earnings_growth_ratio()
            market_cap = share_data.get_market_cap()
            book_value = share_data.get_price_book()
            average_volume = share_data.get_avg_daily_volume()
            dividend_share = share_data.get_dividend_share()
            dividend_yield = share_data.get_dividend_yield()
            earnings_per_share = share_data.get_earnings_share()
            ebitda = share_data.get_ebitda()
            fifty_day_ma = share_data.get_50day_moving_avg()
            days_high = share_data.get_days_high()
            days_low = share_data.get_days_low()
            year_high = share_data.get_year_high()
            year_low = share_data.get_year_low()
            two_hundred_day_ma = share_data.get_200day_moving_avg()

            # Build a string to send to the server containing the stock data
            share_string = "price:" + str(price) + "|"\
                         + "percentChange:" + str(percent_change) + "|"\
                         + "previousClose:" + str(previous_close) + "|"\
                         + "openPrice:" + str(open_price) + "|"\
                         + "volume:" + str(volume) + "|"\
                         + "peRatio:" + str(pe_ratio) + "|"\
                         + "pegRatio:" + str(peg_ratio) + "|"\
                         + "marketCap:" + str(market_cap) + "|"\
                         + "bookValue:" + str(book_value) + "|"\
                         + "averageVolume:" + str(average_volume) + "|"\
                         + "dividendShare:" + str(dividend_share) + "|"\
                         + "dividendYield:" + str(dividend_yield) + "|"\
                         + "earningsPerShare:" + str(earnings_per_share) + "|"\
                         + "ebitda:" + str(ebitda) + "|"\
                         + "50DayMa:" + str(fifty_day_ma) + "|"\
                         + "daysHigh:" + str(days_high) + "|"\
                         + "daysLow:" + str(days_low) + "|"\
                         + "yearHigh:" + str(year_high) + "|"\
                         + "yearLow:" + str(year_low) + "|"\
                         + "200DayMa:" + str(two_hundred_day_ma) + "|"

            self.write_message("StockData;%s" % (share_string))
            print_logger.debug("Sending Message: StockData;%s" % (share_string))

        elif "GetCompanyDesc" in message:
            message = message.split(":")

            if len(message) != 2:
                print_logger.error("Malformed Message from Client")
                return

            ticker = message[1]

            description = update_description_oneoff(ticker)

            self.write_message("CompanyDescription:%s" % str(description))

        elif "GetCompanyDividend" in message and "Record" not in message:
            message = message.split(":")

            if len(message) != 2:
                print_logger.error("Malformed Message from Client")
                return

            ticker = message[1]

            # Grab the dividend data from dividata.com
            dividend_url = "https://dividata.com/stock/%s/dividend" % ticker

            # This should potentially be a
            dividend_data = requests.get(dividend_url)
            dividend_soup = BeautifulSoup(dividend_data.text, 'html5lib')

            if len(dividend_soup.find_all("table")) > 0:
                dividend_soup = dividend_soup.find_all("table")[0]
            else:
                dividend_soup = "<h3>No dividend history found.</h3>"

            # Send this div up to the server
            self.write_message("DividendHistoryData:" + str(dividend_soup))

        elif "GetCompanyDividendRecord" in message:
            message = message.split(":")

            if len(message) != 2:
                print_logger.error("Malformed Message from Client")
                return

            ticker = message[1]

            # Get the dividend record html for the table and send it up
            #dividend_record = strip_dividends(ticker, req_proxy)

            #print_logger.debug("Writing message: " + str(dividend_record))
            #self.write_message("DividendRecord:" + str(dividend_record))

        elif "GetBollinger" in message:
            message = message.split(":")

            if len(message) != 2:
                print_logger.error("Malformed Message from Client")
                return

            ticker = message[1]

            # Switch into the tmp directory
            old_dir = os.getcwd()
            os.chdir(TEMP_DIR)

            # Update the historical data for the ticker symbol
            YAHOO_FINANCE_HISTORICAL_OBJECT.read_ticker_historical(ticker)

            bands = BollingerBandStrategy(data_storage_dir="%s/historical_stock_data" % TEMP_DIR\
                    , ticker_file="%s/stock_list.txt" % TEMP_DIR, filtered_ticker_file=\
                    "%s/filtered_stock_list.txt" % TEMP_DIR)

            # Save the graph so that we can show it on the website
            bands.save_stock_chart(ticker, "%s" % TEMP_DIR)

            # Also let the server know that we found an answer
            result = bands.test_ticker(ticker)

            if result is not None:
                print_logger.debug("BB:GoodCandidate")
                self.write_message("BB:GoodCandidate")
            else:
                print_logger.debug("BB:BadCandidate")
                self.write_message("BB:BadCandidate")
        elif "CheckRobinhoodLogin" in message:
            print "HELLO WORLD!!! HELLO WORLD!!! HELLO WORLD!!!%s" % ROBINHOOD_INSTANCE
            if ROBINHOOD_INSTANCE.is_logged_in() is True:
                self.write_message("RobinhoodLoggedIn:%s" % ROBINHOOD_INSTANCE.username)
            else:
                self.write_message("RobinhoodNotLoggedIn")
                
        elif "GetPosition" in message:

            ticker = message.replace("GetPosition:", "")

            account_positions = ROBINHOOD_INSTANCE.get_position_history(active=True)
            user_owns_stock = False
            position_string = ""
            for position in account_positions:
                
                # Get data about the position, including current price.  
                position_data = requests.get(position["instrument"])
                position_data = json.loads(position_data._content)
                position.update(position_data)

                if position["symbol"] != ticker:
                    continue

                quote_data = requests.get(position["quote"]);
                quote_data = json.loads(quote_data._content)
                position.update(quote_data)
                
                position_string = json.dumps(position)
                user_owns_stock = True
                
            if user_owns_stock is True:
                self.write_message("Position:%s" % position_string)
            else:
                self.write_message("Position:None")
Exemplo n.º 47
0
def getStocksFromSource(indexes=data, sortBy=SORT_BY_TOP):
    ''' '''
    stocks = []
    index = ['AGTC']
    # for stock in data["Ticker"][:100]:
    # for stock in index:
    for stock in data:
        try:
            print(stock)
            # print(type(stock))
            yf_data = yqd.load_yahoo_quote(stock, '20170301', '20170830')
            # yf_data = yqd.load_yahoo_quote('ABEO', '20170712', '20170725')
            # print(yf_data)
            share = Share(stock)

            # history part
            history = []
            for i, day in enumerate(yf_data[1:-1]):
                daily_data = day.split(',')
                history.append([
                    i,
                    str(daily_data[0]),
                    float(daily_data[1]),
                    float(daily_data[2]),
                    float(daily_data[3]),
                    float(daily_data[4]),
                    float(daily_data[6])
                ])

            # print(history)
            # comments part
            comments = []
            new_StockTwits_comments = []
            url = 'https://api.stocktwits.com/api/2/streams/symbol/{0}.json'.format(
                stock)
            print(url)
            try:
                r = requests.get(url).json()
                print(len(r['messages']))
                for message in r['messages']:
                    try:
                        new_tweet = {
                            'id':
                            message['id'],
                            'body':
                            message['body'],
                            'created_at':
                            message['created_at'],
                            'core_body':
                            nltk_service.clean_tweet(message['body']),
                            'nltk_sentiment':
                            nltk_service.get_tweet_sentiment(message['body']),
                            # 'azure_sentiment': azure_sentiment_service.GetSentiment(message['body'])
                        }
                        try:
                            new_tweet[
                                'azure_sentiment'] = azure_sentiment_service.GetSentiment(
                                    message['body'])
                        except Exception as e:
                            new_tweet['azure_sentiment'] = 0.5
                            print(e)
                        # print(new_tweet['azure_sentiment'])
                        new_StockTwits_comments.append(new_tweet)
                    except Exception as e:
                        print(e)
                        # pass
            except Exception as e:
                print('stock tweets part problem')
                print(e)
            # new_StockTwits_comments = [{'id': message['id'], 'body': message['body'], 'created_at': message['created_at']} for message in r['messages']]

            print(len(new_StockTwits_comments))
            stock = {
                'index': stock,
                'open': share.get_open(),
                'change': share.get_change(),
                'percent_change': share.get_percent_change(),
                'prev_close': share.get_prev_close(),
                'price': share.get_price(),
                'volume': share.get_volume(),
                'history': history,
                'new_StockTwits_comments': new_StockTwits_comments
            }
            # stock_json = json.dumps(stock)
            # print(type(stock_json))
            print(len(history))
            if len(history) != 0:
                # f.write(stock['index']+'/n')
                stocks.append(stock)
        except Exception as e:
            print(e)
            pass
    print(len(stocks))
    return stocks


# f.close()

# get_price()
# get_change()
# get_percent_change()
# get_volume()
# get_prev_close()
# get_open()
# get_avg_daily_volume()
# get_stock_exchange()
# get_market_cap()
# get_book_value()
# get_ebitda()
# get_dividend_share()
# get_dividend_yield()
# get_earnings_share()
# get_days_high()
# get_days_low()
# get_year_high()
# get_year_low()
# get_50day_moving_avg()
# get_200day_moving_avg()
# get_price_earnings_ratio()
# get_price_earnings_growth_ratio()
# get_price_sales()
# get_price_book()
# get_short_ratio()
# get_trade_datetime()
# get_historical(start_date, end_date)
# get_name()
# refresh()
# get_percent_change_from_year_high()
# get_percent_change_from_year_low()
# get_change_from_year_low()
# get_change_from_year_high()
# get_percent_change_from_200_day_moving_average()
# get_change_from_200_day_moving_average()
# get_percent_change_from_50_day_moving_average()
# get_change_from_50_day_moving_average()
# get_EPS_estimate_next_quarter()
# get_EPS_estimate_next_year()
# get_ex_dividend_date()
# get_EPS_estimate_current_year()
# get_price_EPS_estimate_next_year()
# get_price_EPS_estimate_current_year()
# get_one_yr_target_price()
# get_change_percent_change()
# get_dividend_pay_date()
# get_currency()
# get_last_trade_with_time()
# get_days_range()
# get_year_range()