Пример #1
0
def get_ma(stock):
    prices_10 = []
    prices_20 = []
    stock = Share(stock)
    if (stock.get_price() < 5):
        return 0, 0, 0
    dma_10 = now - timedelta(days=30)
    date10 = str(dma_10.year) + "-" + str(dma_10.month) + "-" + str(dma_10.day)
    time.sleep(0.5)
    try:
        data = stock.get_historical(date10, theDate)
        prices_50 = stock.get_50day_moving_avg()

        count = 0
        for theData in data:
            if count < 10:
                count = count + 1
                prices_10.append(float(theData['Adj_Close']))
            else:
                continue
        count = 0
        for theData in data:
            if count < 20:
                count = count + 1
                prices_20.append(float(theData['Adj_Close']))
            else:
                continue
    except:
        return 0, 0, 0
    print prices_50
    return prices_10, prices_20, prices_50
Пример #2
0
def combine(onedayago, twodaysago, threedaysago, fivedaysago, oneweekago, companyname):
    print "Analyzing data from the past few days..."
    dates = [onedayago, twodaysago, threedaysago, fivedaysago, oneweekago]
    for i in dates:
        i == i.format('YYYY-MM-DD')


    # Just gets the info and puts it into programmer friendly names
    def getclosing(date, company):
        # Thanks to stackoverflow user 'TessellatingHeckler' for helping me out with this next function! At the time dictionaries were a foreign concept to me.
        readings = company.get_historical(date, date)
        for reading in readings:
            close = reading['Close']
            return close

    company = Share(companyname)
    closingonedayago = getclosing(str(dates[0]), company)
    closingtwodaysago = getclosing(str(dates[1]), company)
    closingthreedaysago = getclosing(str(dates[2]), company)
    closingfivedaysago = getclosing(str(dates[3]), company)
    closingoneweekago = getclosing(str(dates[4]), company)
    twohundredavg = company.get_200day_moving_avg()
    fiftyavg = company.get_50day_moving_avg()
    today = company.get_price()
    decision(today, closingonedayago, closingtwodaysago, closingthreedaysago, closingfivedaysago, closingoneweekago, twohundredavg, fiftyavg)
Пример #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.")
Пример #4
0
def combine(onedayago, twodaysago, threedaysago, fivedaysago, oneweekago,
            companyname):
    print("Analyzing data from the past few days...")
    dates = [onedayago, twodaysago, threedaysago, fivedaysago, oneweekago]
    for i in dates:
        i == i.format('YYYY-MM-DD')

    # Just gets the info and puts it into programmer friendly names
    def getclosing(date, company):
        readings = company.get_historical(date, date)
        for reading in readings:
            close = reading['Close']
            return close

    company = Share(companyname)
    closingonedayago = getclosing(str(dates[0]), company)
    closingtwodaysago = getclosing(str(dates[1]), company)
    closingthreedaysago = getclosing(str(dates[2]), company)
    closingfivedaysago = getclosing(str(dates[3]), company)
    closingoneweekago = getclosing(str(dates[4]), company)
    twohundredavg = company.get_200day_moving_avg()
    fiftyavg = company.get_50day_moving_avg()
    today = company.get_price()
    decision(today, closingonedayago, closingtwodaysago, closingthreedaysago,
             closingfivedaysago, closingoneweekago, twohundredavg, fiftyavg)
Пример #5
0
def combine(onedayago, twodaysago, threedaysago, fivedaysago, oneweekago,
            companyname):
    print "Analyzing data from the past few days..."
    dates = [onedayago, twodaysago, threedaysago, fivedaysago, oneweekago]
    for i in dates:
        i == i.format('YYYY-MM-DD')

    # Just gets the info and puts it into programmer friendly names
    def getclosing(date, company):
        # Thanks to stackoverflow user 'TessellatingHeckler' for helping me out with this next function! At the time dictionaries were a foreign concept to me.
        readings = company.get_historical(date, date)
        for reading in readings:
            close = reading['Close']
            return close

    company = Share(companyname)
    closingonedayago = getclosing(str(dates[0]), company)
    closingtwodaysago = getclosing(str(dates[1]), company)
    closingthreedaysago = getclosing(str(dates[2]), company)
    closingfivedaysago = getclosing(str(dates[3]), company)
    closingoneweekago = getclosing(str(dates[4]), company)
    twohundredavg = company.get_200day_moving_avg()
    fiftyavg = company.get_50day_moving_avg()
    today = company.get_price()
    decision(today, closingonedayago, closingtwodaysago, closingthreedaysago,
             closingfivedaysago, closingoneweekago, twohundredavg, fiftyavg)
Пример #6
0
def set_ETF_data():
    etf_data = []

    for index, etf_symbol in enumerate(settings.ETF_MASTER_LIST):
        etf_dict = {
            'model': 'portfolio.ETF',
            'pk': index + 1,
            'fields': {},
        }

        fund = Share(etf_symbol)

        fields = {
            'name': fund.get_name(),
            'symbol': etf_symbol,
            'last_trade': fund.get_price(),
            'dividend_yield': fund.get_dividend_yield(),
            'absolute_change': fund.get_change(),
            'percentage_change': fund.get_percent_change(),
            'year high': fund.get_year_high(),
            'year low': fund.get_year_low(),
            '50 day moving average': fund.get_50day_moving_avg(),
            '200 day moving average': fund.get_200day_moving_avg(),
            'average_daily_volume': fund.get_avg_daily_volume()
        }

        etf_dict['fields'] = fields
        etf_data.append(etf_dict)
    json_data = json.dumps(etf_data)

    # print(json_data)

    output_dict = [y for y in etf_data if y['fields']['dividend_yield'] > 1]

    output_dict = [
        x for x in output_dict if x['fields']['average_daily_volume'] > 100000
    ]

    output_dict = [
        z for z in output_dict
        if z['fields']['200 day moving average'] < z['fields']['last_trade']
    ]

    sorted_list = sorted(output_dict,
                         key=lambda k: k['fields']['dividend_yield'],
                         reverse=True)

    for etf in sorted_list[:5]:
        ETF.objects.create(
            portfolio=Portfolio.objects.get(pk=1),
            name=etf['fields']['name'],
            symbol=etf['fields']['symbol'],
            investment_style=1,
            last_trade=etf['fields']['last_trade'],
            dividend_yield=etf['fields']['dividend_yield'],
            absolute_change=etf['fields']['absolute_change'],
            percentage_change=etf['fields']['percentage_change'],
            currency='USD',
            last_updated=timezone.now())
Пример #7
0
class Stock:
    """

    """

    def __init__(self, n):
        self.name = n
        self.confidence_list = []
        self.fifty_day_moving_average = None
        self.two_hundred_day_moving_average = None
        self.price_earnings_growth_ratio = None
        self.confidence_string = None
        self.current_price = None
        self.stock = Share(self.name)

    def calculate_confidence_percentage(self):
        self.confidence_list = []
        self.confidence_list.append(sc.formula_00_is_stock_above_50_day_moving_average(self.get_current_price(), self.get_fifty_day_moving_average()))
        self.confidence_list.append(sc.formula_01_is_stock_above_200_day_moving_average(self.get_current_price(), self.get_two_hundred_day_moving_average()))
        self.confidence_list.append(sc.formula_02_pattern_guesser_confidence_for_tomorrow(self.name))

        confidence_string = ''
        for c in self.confidence_list:
            confidence_string += str(c) + ", "

        self.confidence_string = 'Confidence List: ' + confidence_string + '\tAverage Confidence: ' + str(sum(self.confidence_list) / len(self.confidence_list))

    def get_name(self):
        """TODO:...
        :return:
        """
        return self.name

    def get_current_price(self):
        if self.current_price is None:
            self.current_price = self.stock.get_price()

    def get_confidence_string(self):
        if self.confidence_string is None:
            self.calculate_confidence_percentage()
        return self.confidence_string

    def get_fifty_day_moving_average(self):
        if self.fifty_day_moving_average is None:
            self.fifty_day_moving_average = self.stock.get_50day_moving_avg()
        return self.fifty_day_moving_average

    def get_two_hundred_day_moving_average(self):
        if self.two_hundred_day_moving_average is None:
            self.two_hundred_day_moving_average = self.stock.get_200day_moving_avg()
        return self.two_hundred_day_moving_average

    def get_price_earnings_growth_ratio(self):
        if self.price_earnings_growth_ratio is None:
            self.price_earnings_growth_ratio = self.stock.get_price_earnings_growth_ratio()
        return self.price_earnings_growth_ratio
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})
Пример #9
0
def portfolio_stocks(stocks):
	tickers = []
	index = 0
	for stock in stocks:
		names = [
		'Company Name', 
		'Ticker', 
		'Price',
		'Market Cap', 
		'P/E Ratio', 
		'Earnings Yield', 
		'Div Yield',
		'50 Day MA',
		'200 Day MA',
		'Price Target'
		]
		ticker = Share(stock)
		
		comp_name = ticker.get_name() #company name
		
		tick = stock #ticker
		
		price = ticker.get_price() #price

		market_cap = ticker.get_market_cap() #market_cap

		pe = ticker.get_price_earnings_ratio() #gets pe as a string 
		pe_two = float(pe) if pe else 0 #returns a float of the p/e if there is a result, otherwise returns 0
		final_pe = pe_two if float(pe_two) > 0 else 0 #returns pe_two if > 0 else returns 0

		EPS = ticker.get_EPS_estimate_current_year() # gets eps as a string
		final_eps = EPS if EPS else 0 #returns eps if there is a result, else returns 0
		
		earn_yield = float(final_eps)/float(price) #returns float of earnings yield
		pos_ey = earn_yield if earn_yield > 0 else 0 #turns negitive numbers to 0
		print(tick, 'earn yield', pos_ey)
		ey = round(pos_ey*100, 2) #returns in % format
		
		div = ticker.get_dividend_yield() #returns div in string
		final_div = 0 if div == None else float(div) #if no result returns 0 else returns float of div 
		
		fifty = ticker.get_50day_moving_avg() #returns as string
		short_fifty = round(float(fifty), 2) #returns div with 2 decimal places
		two_hundred = ticker.get_200day_moving_avg() #returns as string
		short_two = round(float(two_hundred), 2) #returns float with 2 decimal places

		target = ticker.get_one_yr_target_price() #returns as string
		short_target = round(float(target), 2)

		values = [comp_name, tick, price, market_cap, final_pe, ey, final_div, short_fifty, short_two, short_target]
		final_values = list(zip(names, values))
		index += 1
		tickers.append(final_values)
	return tickers
Пример #10
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
Пример #11
0
def get_stock_info(ticker):
    temp_share = Share(ticker)
    real_price = temp_share.get_price()
    adj_price = (float(temp_share.get_open()) + float(temp_share.get_close()) +
                 float(temp_share.get_high()) +
                 float(temp_share.get_low())) / 4
    real_vol = temp_share.get_volume()
    avg_vol = temp_share.get_avg_daily_volume()
    avg_50_day = temp_share.get_50day_moving_avg()
    avg_200_day = temp_share.get_200day_moving_avg()
    return real_price, adj_price, real_vol, avg_vol, avg_50_day, avg_200_day
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 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()
Пример #14
0
def bot_action(c, symbol):
    stock = Share(symbol)                # Link stock with yahoo_finance module
    print(stock)
    if stock.get_price() == None:
        main()
    #print(stock.get_price())
    head = 'Up to date stock info for **${0}** ({1}):\n\n'.format(symbol.upper(), stock.get_name())
    price = '**Price:** ${0:.2f}\n\n'.format(float(stock.get_price()))
    price_open = '**Open:** ${0:.2f}\n\n'.format(float(stock.get_open()))
    change = '**Change:** {0:.2f} ({1})\n\n'.format(float(stock.get_change()), stock.get_percent_change())
    vol = '**Volume:** {0:,.2f}\n\n'.format(float(stock.get_volume()))
    market_cap = '**Mkt Cap:** {0}\n\n'.format(stock.get_market_cap())
    average = '**Average (50 day):** {0:.2f}\n\n'.format(float(stock.get_50day_moving_avg()))
    exchange = '**Exchange:** {0}\n\n'.format(stock.get_stock_exchange())
    divider = '-----------------------------------------------------------------------------------------\n\n'
    tail = "Don't abuse me, robots have feelings too! | [Source Code](https://github.com/Logicmn/Reddit-Stock-Bot) " \
           "| [Report Bug](https://www.reddit.com/message/compose/?to=Pick-a-Stock) " \
           "| [Suggest Feature](https://www.reddit.com/message/compose/?to=Pick-a-Stock)"
    c.reply(head + divider + price + price_open + change + vol + market_cap + average + exchange+ divider + tail)
Пример #15
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
Пример #16
0
def stock_info(ticker):
    obj = session['objective']
    stock_list = session['stock_list']
    time = session['time']
    stock = Share(ticker)
    name = stock.get_name()
    price = stock.get_price()
    pe = stock.get_price_earnings_ratio()
    final_pe = 0 if not pe else pe
    EPS = float(stock.get_EPS_estimate_current_year())
    earn_yield = 0 if float(EPS) <= 0 else float(price) / EPS
    final_yield = '%.2f' % earn_yield
    div = stock.get_dividend_yield()
    final_div = 0 if div == None else div
    target = stock.get_one_yr_target_price()
    fifty = stock.get_50day_moving_avg()
    two_hundred = stock.get_200day_moving_avg()
    info = Stock(name, price, pe, final_yield, final_div, target, fifty,
                 two_hundred)
    beta = Beta(ticker)
    return render_template("stock-info.html",
                           name=info.name,
                           num_beta=beta.calculate_beta(),
                           beta=beta.compare_beta(),
                           pe_num=final_pe,
                           pe=info.compare_pe(),
                           ey_num=final_yield,
                           ey=info.compare_earn_yield(),
                           div_num=final_div,
                           div=info.compare_div(),
                           fifty=fifty,
                           two=two_hundred,
                           ma_compare=info.compare_ma(),
                           target_num=target,
                           target=info.compare_target(),
                           obj=obj,
                           time=time,
                           stock=stock_list)
Пример #17
0
	#except:
	#	pass
	try:
		russell3000.set_value(s,'Earnings share',shy.get_earnings_share())
	except:
		pass
	try:
		russell3000.set_value(s,'Year high',shy.get_year_high())
	except:
		pass
	try:
		russell3000.set_value(s,'Year low',shy.get_year_low())
	except:
		pass
	try:
		russell3000.set_value(s,'50 days MA',shy.get_50day_moving_avg())
	except:
		pass
	try:
		russell3000.set_value(s,'200 days MA',shy.get_200day_moving_avg())
	except:
		pass
	try:
		russell3000.set_value(s,'Price earnings ratio',shy.get_price_earnings_ratio())
	except:
		pass
	try:
		russell3000.set_value(s,'Price earnings growth ratio',shy.get_price_earnings_growth_ratio())
	except:
		pass
	try:
Пример #18
0
 def refresh_yahoo_api_data(self):
     yahoo_data = Share(self.symbol)
     self.fifty_moving_avg = yahoo_data.get_50day_moving_avg()
     self.two_hundred_moving_avg = yahoo_data.get_200day_moving_avg()
     self.year_high = yahoo_data.get_year_high()
     self.year_low = yahoo_data.get_year_low()
Пример #19
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        '''Creates basic geometry for GUI'''
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.setMinimumSize(QtCore.QSize(490, 400))
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8("DK_icon.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        MainWindow.setWindowIcon(icon)
        MainWindow.setTabShape(QtGui.QTabWidget.Rounded)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.btnPredictPrices = QtGui.QPushButton(self.centralwidget)
        self.btnPredictPrices.setGeometry(QtCore.QRect(300, 330, 161, 23))
        self.btnPredictPrices.setObjectName(_fromUtf8("btnPredictPrices"))
        self.btnPredictPrices.clicked.connect(self.show_predictions)
        self.btnPlotSymbol = QtGui.QPushButton(self.centralwidget)
        self.btnPlotSymbol.setGeometry(QtCore.QRect(300, 90, 161, 23))
        self.btnPlotSymbol.setObjectName(_fromUtf8("btnPlotSymbol"))
        self.btnPlotSymbol.clicked.connect(self.display_plots)
        self.leditEnterTickers = QtGui.QLineEdit(self.centralwidget)
        self.leditEnterTickers.setGeometry(QtCore.QRect(30, 330, 241, 21))
        self.leditEnterTickers.setObjectName(_fromUtf8("leditEnterTickers"))
        self.deditStartDate = QtGui.QDateEdit(self.centralwidget)
        self.deditStartDate.setGeometry(QtCore.QRect(30, 30, 110, 22))
        self.deditStartDate.setAlignment(QtCore.Qt.AlignCenter)
        self.deditStartDate.setDate(QtCore.QDate(2013, 1, 1))
        self.deditStartDate.setCalendarPopup(True)
        self.deditStartDate.setObjectName(_fromUtf8("deditStartDate"))
        self.deditEndDate = QtGui.QDateEdit(self.centralwidget)
        self.deditEndDate.setGeometry(QtCore.QRect(290, 30, 110, 22))
        self.deditEndDate.setAlignment(QtCore.Qt.AlignCenter)
        self.deditEndDate.setDate(QtCore.QDate(2017, 1, 1))
        self.deditEndDate.setCalendarPopup(True)
        self.deditEndDate.setObjectName(_fromUtf8("deditEndDate"))
        self.labelStartDate = QtGui.QLabel(self.centralwidget)
        self.labelStartDate.setGeometry(QtCore.QRect(150, 30, 111, 21))
        self.labelStartDate.setObjectName(_fromUtf8("labelStartDate"))
        self.labelEndDate = QtGui.QLabel(self.centralwidget)
        self.labelEndDate.setGeometry(QtCore.QRect(410, 30, 51, 21))
        self.labelEndDate.setObjectName(_fromUtf8("labelEndDate"))
        self.leditPlotSymb = QtGui.QLineEdit(self.centralwidget)
        self.leditPlotSymb.setGeometry(QtCore.QRect(30, 90, 241, 21))
        self.leditPlotSymb.setObjectName(_fromUtf8("leditPlotSymb"))
        self.dedit1stPDate = QtGui.QDateEdit(self.centralwidget)
        self.dedit1stPDate.setGeometry(QtCore.QRect(30, 210, 110, 22))
        self.dedit1stPDate.setAlignment(QtCore.Qt.AlignCenter)
        self.dedit1stPDate.setDate(QtCore.QDate(2016, 12, 6))
        self.dedit1stPDate.setCalendarPopup(True)
        self.dedit1stPDate.setObjectName(_fromUtf8("dedit1stPDate"))
        self.dedit2ndPDate = QtGui.QDateEdit(self.centralwidget)
        self.dedit2ndPDate.setGeometry(QtCore.QRect(30, 240, 110, 22))
        self.dedit2ndPDate.setAlignment(QtCore.Qt.AlignCenter)
        self.dedit2ndPDate.setDate(QtCore.QDate(2016, 12, 7))
        self.dedit2ndPDate.setCalendarPopup(True)
        self.dedit2ndPDate.setObjectName(_fromUtf8("dedit2ndPDate"))
        self.dedit3rdPDate = QtGui.QDateEdit(self.centralwidget)
        self.dedit3rdPDate.setGeometry(QtCore.QRect(30, 270, 110, 22))
        self.dedit3rdPDate.setAlignment(QtCore.Qt.AlignCenter)
        self.dedit3rdPDate.setDate(QtCore.QDate(2016, 12, 8))
        self.dedit3rdPDate.setCalendarPopup(True)
        self.dedit3rdPDate.setObjectName(_fromUtf8("dedit3rdPDate"))
        self.label1stPDate = QtGui.QLabel(self.centralwidget)
        self.label1stPDate.setGeometry(QtCore.QRect(150, 210, 131, 21))
        self.label1stPDate.setObjectName(_fromUtf8("label1stPDate"))
        self.label3rdPDate = QtGui.QLabel(self.centralwidget)
        self.label3rdPDate.setGeometry(QtCore.QRect(150, 270, 121, 21))
        self.label3rdPDate.setObjectName(_fromUtf8("label3rdPDate"))
        self.label2ndPDate = QtGui.QLabel(self.centralwidget)
        self.label2ndPDate.setGeometry(QtCore.QRect(150, 240, 131, 21))
        self.label2ndPDate.setObjectName(_fromUtf8("label2ndPDate"))
        self.btnFundData = QtGui.QPushButton(self.centralwidget)
        self.btnFundData.setGeometry(QtCore.QRect(300, 120, 161, 23))
        self.btnFundData.setObjectName(_fromUtf8("btnFundData"))
        self.btnFundData.clicked.connect(self.display_fund_data)
        self.deditLastTDate = QtGui.QDateEdit(self.centralwidget)
        self.deditLastTDate.setGeometry(QtCore.QRect(30, 180, 110, 22))
        self.deditLastTDate.setAlignment(QtCore.Qt.AlignCenter)
        self.deditLastTDate.setDate(QtCore.QDate(2016, 12, 5))
        self.deditLastTDate.setCalendarPopup(True)
        self.deditLastTDate.setObjectName(_fromUtf8("deditLastTDate"))
        self.labelStartDate_6 = QtGui.QLabel(self.centralwidget)
        self.labelStartDate_6.setGeometry(QtCore.QRect(150, 180, 91, 21))
        self.labelStartDate_6.setObjectName(_fromUtf8("labelStartDate_6"))
        self.sbox1stPDate = QtGui.QSpinBox(self.centralwidget)
        self.sbox1stPDate.setGeometry(QtCore.QRect(290, 210, 42, 22))
        self.sbox1stPDate.setAlignment(QtCore.Qt.AlignCenter)
        self.sbox1stPDate.setMinimum(0)
        self.sbox1stPDate.setProperty("value", 0)
        self.sbox1stPDate.setObjectName(_fromUtf8("sbox1stPDate"))
        self.dedit4thPDate = QtGui.QDateEdit(self.centralwidget)
        self.dedit4thPDate.setGeometry(QtCore.QRect(30, 300, 110, 22))
        self.dedit4thPDate.setAlignment(QtCore.Qt.AlignCenter)
        self.dedit4thPDate.setDate(QtCore.QDate(2016, 12, 9))
        self.dedit4thPDate.setCalendarPopup(True)
        self.dedit4thPDate.setObjectName(_fromUtf8("dedit4thPDate"))
        self.label4thPDate = QtGui.QLabel(self.centralwidget)
        self.label4thPDate.setGeometry(QtCore.QRect(150, 300, 131, 21))
        self.label4thPDate.setFrameShape(QtGui.QFrame.NoFrame)
        self.label4thPDate.setObjectName(_fromUtf8("label4thPDate"))
        self.label1stPDate_2 = QtGui.QLabel(self.centralwidget)
        self.label1stPDate_2.setGeometry(QtCore.QRect(340, 210, 121, 21))
        self.label1stPDate_2.setObjectName(_fromUtf8("label1stPDate_2"))
        self.label2ndPDate_2 = QtGui.QLabel(self.centralwidget)
        self.label2ndPDate_2.setGeometry(QtCore.QRect(340, 240, 121, 21))
        self.label2ndPDate_2.setObjectName(_fromUtf8("label2ndPDate_2"))
        self.sbox2ndPDate = QtGui.QSpinBox(self.centralwidget)
        self.sbox2ndPDate.setGeometry(QtCore.QRect(290, 240, 42, 22))
        self.sbox2ndPDate.setAlignment(QtCore.Qt.AlignCenter)
        self.sbox2ndPDate.setMinimum(0)
        self.sbox2ndPDate.setProperty("value", 0)
        self.sbox2ndPDate.setObjectName(_fromUtf8("sbox2ndPDate"))
        self.label3rdPDate_2 = QtGui.QLabel(self.centralwidget)
        self.label3rdPDate_2.setGeometry(QtCore.QRect(340, 270, 121, 21))
        self.label3rdPDate_2.setObjectName(_fromUtf8("label3rdPDate_2"))
        self.sbox3rdPDate = QtGui.QSpinBox(self.centralwidget)
        self.sbox3rdPDate.setGeometry(QtCore.QRect(290, 270, 42, 22))
        self.sbox3rdPDate.setAlignment(QtCore.Qt.AlignCenter)
        self.sbox3rdPDate.setMinimum(0)
        self.sbox3rdPDate.setProperty("value", 0)
        self.sbox3rdPDate.setObjectName(_fromUtf8("sbox3rdPDate"))
        self.label4thPDate_2 = QtGui.QLabel(self.centralwidget)
        self.label4thPDate_2.setGeometry(QtCore.QRect(340, 300, 121, 21))
        self.label4thPDate_2.setObjectName(_fromUtf8("label4thPDate_2"))
        self.sbox4thPDate = QtGui.QSpinBox(self.centralwidget)
        self.sbox4thPDate.setGeometry(QtCore.QRect(290, 300, 42, 22))
        self.sbox4thPDate.setAlignment(QtCore.Qt.AlignCenter)
        self.sbox4thPDate.setMinimum(0)
        self.sbox4thPDate.setProperty("value", 0)
        self.sbox4thPDate.setObjectName(_fromUtf8("sbox4thPDate"))
        self.btnLookupSymbol = QtGui.QPushButton(self.centralwidget)
        self.btnLookupSymbol.setGeometry(QtCore.QRect(30, 120, 161, 23))
        self.btnLookupSymbol.setObjectName(_fromUtf8("btnLookupSymbol"))
        self.btnLookupSymbol.clicked.connect(self.lookup_symbol)
        self.line2ndHorizontal = QtGui.QFrame(self.centralwidget)
        self.line2ndHorizontal.setGeometry(QtCore.QRect(30, 140, 431, 20))
        self.line2ndHorizontal.setFrameShape(QtGui.QFrame.HLine)
        self.line2ndHorizontal.setFrameShadow(QtGui.QFrame.Sunken)
        self.line2ndHorizontal.setObjectName(_fromUtf8("line2ndHorizontal"))
        self.labelPricePredictionDates = QtGui.QLabel(self.centralwidget)
        self.labelPricePredictionDates.setGeometry(QtCore.QRect(30, 160, 151, 20))
        self.labelPricePredictionDates.setObjectName(_fromUtf8("labelPricePredictionDates"))
        self.line1stHorizontal = QtGui.QFrame(self.centralwidget)
        self.line1stHorizontal.setGeometry(QtCore.QRect(30, 50, 431, 20))
        self.line1stHorizontal.setFrameShape(QtGui.QFrame.HLine)
        self.line1stHorizontal.setFrameShadow(QtGui.QFrame.Sunken)
        self.line1stHorizontal.setObjectName(_fromUtf8("line1stHorizontal"))
        self.labelHistoricalData = QtGui.QLabel(self.centralwidget)
        self.labelHistoricalData.setGeometry(QtCore.QRect(30, 70, 151, 20))
        self.labelHistoricalData.setObjectName(_fromUtf8("labelHistoricalData"))
        self.labelDateRange = QtGui.QLabel(self.centralwidget)
        self.labelDateRange.setGeometry(QtCore.QRect(30, 10, 261, 20))
        self.labelDateRange.setObjectName(_fromUtf8("labelDateRange"))
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 490, 21))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        self.menuFile = QtGui.QMenu(self.menubar)
        self.menuFile.setObjectName(_fromUtf8("menuFile"))
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)
        self.actionQuit = QtGui.QAction(MainWindow)
        self.actionQuit.triggered.connect(QtGui.qApp.quit)
        self.actionQuit.setObjectName(_fromUtf8("actionQuit"))
        self.actionTo_Find_Stock_Symbol = QtGui.QAction(MainWindow)
        self.actionTo_Find_Stock_Symbol.setObjectName(_fromUtf8("actionTo_Find_Stock_Symbol"))
        self.actionPortfolio_Folder = QtGui.QAction(MainWindow)
        self.actionPortfolio_Folder.setObjectName(_fromUtf8("actionPortfolio_Folder"))
        self.menuFile.addAction(self.actionQuit)
        self.menubar.addAction(self.menuFile.menuAction())

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        '''Adds extra features to GUI's buttons and fields'''
        MainWindow.setWindowTitle(_translate("MainWindow", "Stock Price Predictor", None))
        self.btnPredictPrices.setToolTip(_translate("MainWindow", "<html><head/><body><p>Displays the predicted closing prices for the stock symbols and days entered. Also compares the predicted price to the actual price if possible.</p></body></html>", None))
        self.btnPredictPrices.setText(_translate("MainWindow", "Predict Future Prices", None))
        self.btnPlotSymbol.setToolTip(_translate("MainWindow", "Plots the daily historical stock price and volume information for a given stock symbol.", None))
        self.btnPlotSymbol.setText(_translate("MainWindow", "Plot Historical Data", None))
        self.leditEnterTickers.setToolTip(_translate("MainWindow", "(MAX 5) Enter stock ticker symbols for price prediction, separated by commas.", None))
        self.leditEnterTickers.setPlaceholderText(_translate("MainWindow", "Enter Stock Ticker Symbols for Price Prediction", None))
        self.deditStartDate.setToolTip(_translate("MainWindow", "The beginning of the range of dates to be used for data download and/or stock price prediction.", None))
        self.deditEndDate.setToolTip(_translate("MainWindow", "The end of the range of dates to be used for data download and/or stock price prediction.", None))
        self.labelStartDate.setToolTip(_translate("MainWindow", "The beginning of the range of dates to be used for data download and/or stock price prediction.", None))
        self.labelStartDate.setText(_translate("MainWindow", "Start Date            TO", None))
        self.labelEndDate.setToolTip(_translate("MainWindow", "The end of the range of dates to be used for data download and/or stock price prediction.", None))
        self.labelEndDate.setText(_translate("MainWindow", " End Date", None))
        self.leditPlotSymb.setToolTip(_translate("MainWindow", "(MAX 5) Enter stock ticker symbols to plot, separated by commas.", None))
        self.leditPlotSymb.setPlaceholderText(_translate("MainWindow", "Enter Stock Ticker Symbols to Plot", None))
        self.dedit1stPDate.setToolTip(_translate("MainWindow", "First day for which the closing price will be predicted. Must come after the Last Training Date.", None))
        self.dedit2ndPDate.setToolTip(_translate("MainWindow", "(Optional) Second day for which the closing price will be predicted. Must come after the Last Training Date.", None))
        self.dedit3rdPDate.setToolTip(_translate("MainWindow", "(Optional) Third day for which the closing price will be predicted. Must come after the Last Training Date.", None))
        self.label1stPDate.setToolTip(_translate("MainWindow", "First day for which the closing price will be predicted. Must come after the Last Training Date.", None))
        self.label1stPDate.setText(_translate("MainWindow", "1st Predicted Date      OR", None))
        self.label3rdPDate.setToolTip(_translate("MainWindow", "(Optional) Third day for which the closing price will be predicted. Must come after the Last Training Date.", None))
        self.label3rdPDate.setText(_translate("MainWindow", "3rd Predicted Date      OR", None))
        self.label2ndPDate.setToolTip(_translate("MainWindow", "(Optional) Second day for which the closing price will be predicted. Must come after the Last Training Date.", None))
        self.label2ndPDate.setText(_translate("MainWindow", "2nd Predicted Date     OR", None))
        self.btnFundData.setToolTip(_translate("MainWindow", "Plots the fundamental data for a given stock symbol.", None))
        self.btnFundData.setText(_translate("MainWindow", "Show Fundamental Data", None))
        self.labelStartDate_6.setToolTip(_translate("MainWindow", "Last day used for training the price prediction model.", None))
        self.labelStartDate_6.setText(_translate("MainWindow", "Last Training Date", None))
        self.sbox1stPDate.setToolTip(_translate("MainWindow", "First day for which the closing price will be predicted. Must come after the Last Training Date.", None))
        self.dedit4thPDate.setToolTip(_translate("MainWindow", "(Optional) Fourth day for which the closing price will be predicted. Must come after the Last Training Date.", None))
        self.label4thPDate.setToolTip(_translate("MainWindow", "(Optional) Fourth day for which the closing price will be predicted. Must come after the Last Training Date.", None))
        self.label4thPDate.setText(_translate("MainWindow", "4th Predicted Date      OR", None))
        self.label1stPDate_2.setToolTip(_translate("MainWindow", "First day for which the closing price will be predicted. Must come after the Last Training Date.", None))
        self.label1stPDate_2.setText(_translate("MainWindow", "Trading Days into Future", None))
        self.label2ndPDate_2.setToolTip(_translate("MainWindow", "(Optional) Second day for which the closing price will be predicted. Must come after the Last Training Date.", None))
        self.label2ndPDate_2.setText(_translate("MainWindow", "Trading Days into Future", None))
        self.sbox2ndPDate.setToolTip(_translate("MainWindow", "(Optional) Second day for which the closing price will be predicted. Must come after the Last Training Date.", None))
        self.label3rdPDate_2.setToolTip(_translate("MainWindow", "(Optional) Third day for which the closing price will be predicted. Must come after the Last Training Date.", None))
        self.label3rdPDate_2.setText(_translate("MainWindow", "Trading Days into Future", None))
        self.sbox3rdPDate.setToolTip(_translate("MainWindow", "(Optional) Third day for which the closing price will be predicted. Must come after the Last Training Date.", None))
        self.label4thPDate_2.setToolTip(_translate("MainWindow", "(Optional) Fourth day for which the closing price will be predicted. Must come after the Last Training Date.", None))
        self.label4thPDate_2.setText(_translate("MainWindow", "Trading Days into Future", None))
        self.sbox4thPDate.setToolTip(_translate("MainWindow", "(Optional) Fourth day for which the closing price will be predicted. Must come after the Last Training Date.", None))
        self.btnLookupSymbol.setToolTip(_translate("MainWindow", "Opens web page to help find a stock\'s ticker symbol.", None))
        self.btnLookupSymbol.setText(_translate("MainWindow", "Lookup Symbol", None))
        self.labelPricePredictionDates.setText(_translate("MainWindow", "Stock Price Prediction", None))
        self.labelHistoricalData.setText(_translate("MainWindow", "Historical Stock Data", None))
        self.labelDateRange.setText(_translate("MainWindow", "Date Range for Data Download and Price Prediction", None))
        self.menuFile.setTitle(_translate("MainWindow", "File", None))
        self.actionQuit.setText(_translate("MainWindow", "Quit", None))
        self.actionTo_Find_Stock_Symbol.setText(_translate("MainWindow", "Look Up Stock Symbols", None))
        self.actionPortfolio_Folder.setText(_translate("MainWindow", "Portfolio Folder", None))
        self.actionPortfolio_Folder.setToolTip(_translate("MainWindow", "Location for saved portfolios", None))
        
    def lookup_symbol(self):
        '''Opens web page in browser to help user research stock ticker symbols'''
        webbrowser.open('http://finance.yahoo.com/')
        
    def get_fund_data(self, fund_ticker):
        '''Obtains and displays basic stock information from Yahoo! Finance for each of the tickers'''
        self.yahoo_request = Share(self.fund_ticker)
        self.ADV = self.yahoo_request.get_avg_daily_volume()
        self.market_cap = self.yahoo_request.get_market_cap()
        self.mov_avg50 = self.yahoo_request.get_50day_moving_avg()
        self.mov_avg200 = self.yahoo_request.get_200day_moving_avg()
        self.pe_ratio = self.yahoo_request.get_price_earnings_ratio()
        self.price = self.yahoo_request.get_price()
        self.year_high = self.yahoo_request.get_year_high()
        self.year_low = self.yahoo_request.get_year_low()     
        self.data = {'Ticker': self.fund_ticker, 'Price' : self.price, 'Year High' : self.year_high, 'Year Low' : self.year_low,
                'Market Cap.' : self.market_cap, 'Avg. Daily Volume' : self.ADV,  
                '50 Day Moving Avg.': self.mov_avg50, '200 Day Moving Avg.': self.mov_avg200, 'P/E Ratio' : self.pe_ratio,
                }  
        self.temp_df = pd.DataFrame(data = self.data, index=[0])
        self.temp_df = self.temp_df[['Ticker', 'Price', 'Year High', 'Year Low', 'Market Cap.',
                            'Avg. Daily Volume', '50 Day Moving Avg.', '200 Day Moving Avg.', 'P/E Ratio']]
        return self.temp_df
        
        
    def display_fund_data(self):
        '''Reads ticker symbols entered into GUI's plotting line edit, obtains fundamental data from Yahoo, displays data in FundamentalWidget''' 
        fund_ticker_text = str(self.leditPlotSymb.text())
        fund_tickers = fund_ticker_text.split(',')
        self.fundamental_df = pd.DataFrame()
        
        for self.fund_ticker in fund_tickers:
            self.fund_ticker = self.fund_ticker.strip().upper()
            self.temp_df = self.get_fund_data(self.fund_ticker) 
            self.fundamental_df = self.fundamental_df.append(self.temp_df)
        
        self.fund_window = FundamentalWidget(self.fundamental_df)
        self.fund_window.show()
   
        
    def show_predictions(self):
        '''Reads ticker symbols and dates entered into GUI's fields, makes Predictor object, displays results in PredictionWidget'''
        self.start_date = self.deditStartDate.date().toPyDate() 
        self.end_date = self.deditEndDate.date().toPyDate()
        self.last_train_date = self.deditLastTDate.date().toPyDate()
        
        future_date1 = self.dedit1stPDate.date().toPyDate()
        future_date2 = self.dedit2ndPDate.date().toPyDate()
        future_date3 = self.dedit3rdPDate.date().toPyDate()
        future_date4 = self.dedit4thPDate.date().toPyDate()
        self.future_dates = [future_date1, future_date2, future_date3, future_date4]
        
        future_num_day1 = self.sbox1stPDate.value()
        future_num_day2 = self.sbox2ndPDate.value()
        future_num_day3 = self.sbox3rdPDate.value()
        future_num_day4 = self.sbox4thPDate.value()
        self.future_num_days = [future_num_day1, future_num_day2, future_num_day3, future_num_day4]
        
        pred_ticker_text = str(self.leditEnterTickers.text())
        self.pred_tickers = pred_ticker_text.split(',')
        self.results_df = pd.DataFrame()
        
        for self.pred_ticker in self.pred_tickers:
            self.pred_ticker = self.pred_ticker.strip().upper()
            self.predictor = PricePredictor(self.start_date, self.end_date, self.last_train_date, 
                                        self.future_dates, self.future_num_days, self.pred_ticker)
            self.temp_df = self.predictor.make_predictions()
            self.results_df = self.results_df.append(self.temp_df)
        
        self.results_window = PredictionWidget(self.results_df)
        self.results_window.show()
        
    def display_plots(self):
        '''Reads ticks symbols from GUI's plotting line edit, retrieves data from Yahoo, plots data in PlotWidget'''
        plot_ticker_text = str(self.leditPlotSymb.text())
        plot_tickers = plot_ticker_text.split(',')
        self.start_date = self.deditStartDate.date().toPyDate() 
        self.end_date = self.deditEndDate.date().toPyDate()
        
        for self.plot_ticker in plot_tickers:
            self.plot_ticker = self.plot_ticker.strip().upper()
            self.yahoo_df = web.DataReader(self.plot_ticker, 'yahoo', self.start_date, self.end_date)
            self.plot_window = PlotWidget(self.yahoo_df, self.plot_ticker)
Пример #20
0
from yahoo_finance import Share

from Parser.models import EtfInfo, EtfData, StockInfo, StockDetail



etfResult = StockInfo.objects.values('ticker', 'name')

#for etfIdx in range(0, len(etfResult)) :
tickerStr = etfResult[0]['ticker']

share = Share(tickerStr)

dateStr = share.get_trade_datetime()[0:11].replace('-','')
ma_200Str = convert(share.get_200day_moving_avg())
ma_50Str = convert(share.get_50day_moving_avg())
book_valueStr = convert(share.get_book_value())
volume_avgStr = convert(share.get_avg_daily_volume())
ebitdaStr = convert(share.get_ebitda())
dividend_yieldStr = convert(share.get_dividend_yield())
market_capStr = convert(share.get_market_cap())
year_highStr = convert(share.get_year_high())
year_lowStr = convert(share.get_year_low())

print tickerStr, dateStr, ma_200Str, ma_50Str, book_valueStr, volume_avgStr, ebitdaStr, dividend_yieldStr, market_capStr, year_highStr, year_lowStr


# print share.get_change()
# print share.get_days_high()
# print share.get_days_low()
# print share.get_dividend_share()
Пример #21
0
class Company:
    def __init__(self, c, n):
        self.code = c               # ticker
        self.name = n               # friendly name
        self.prices = []            # gather data
        self.owned_shares = 0       # quantity of owned shares
        self.bought_value = 0       # invested
        self.share = Share(self.code) # share object
        self.lastAccess = time.time()

    # Every access to self.share must be prefixed with this call
    def verify_share(self):
        global requests_made
        if time.time() - self.lastAccess > 2:
            self.lastAccess = time.time()
            self.share.refresh()
            add_request()
        return

    def log(self, msg):
        print('\t('+self.code+') '+msg)

    def plot(self):
        x = range(0,max_samples%graph_density)
        y = self.prices[::graph_density]
        trace = Scatter(x=x,y=y)
        data = Data([trace])
        plot_url = py.plot(data, filename=self.code)
        print plot_url
        return

    def how_many_shares_to_buy(self, share_price):
        # buy up to max price limit
        buy_count = int((max_investment_per_comp - self.bought_value) / share_price)
        total_cost = buy_count * share_price
        # do not take more than you can afford
        if total_cost >= current_money:
            original_buy_count = buy_count
            buy_count = int(current_money / share_price)
            self.log('WARNING: Cannot buy amount wanted (' + str(original_buy_count) + ') because not enough money, getting (' + str(buy_count) + ') instead!')
        self.log('Calculated buy amount: ' + str(buy_count) + ' @ ' + str(share_price) + '/share.  Total: ' + str(buy_count * share_price))
        return buy_count

    def is_enough_data_to_trade(self):
        return self.get_long_moving_avg() != 0

    def get_high(self):
        return max(self.prices)
    def get_low(self):
        return min(self.prices)

    def get_short_moving_avg(self):
        self.verify_share()
        try:
            shortavg = self.share.get_50day_moving_avg()
        except:
            return -1.0
        if shortavg is None:
            return None
        return float(shortavg)

    def get_long_moving_avg(self):
        self.verify_share()
        try:
            longavg = self.share.get_200day_moving_avg()
        except:
            return -1.0
        if longavg is None:
            return None
        return float(longavg)

    def fill_historical(self):
        self.verify_share()
        #probs doesn't work
        #map real time space
        day = str(int(datetime.now().second / 2))
        month = str(int(datetime.now().minute / 4))
        if len(month) == 1:
            month = '0' + month
        if len(day) == 1:
            day = '0' + day
        s_date = '2014-' + month + '-' + day
        
        #for testing, get historical
        histories = self.share.get_historical(s_date, s_date)
        return
    
    def gather(self):
        price = self.get_price()
        if price is not None:
            self.prices.append(price)
        return

    def get_price(self):
        self.verify_share()
        try:
           price_u = self.share.get_price()
           if price_u is None:
               self.log('Company gave no price')
               return None
           price = float(price_u)
        except:
            self.log('ERROR: Failed to retrieve price due to internal yahoo API error')
            return None
        return price
    
    # returns the number to buy
    def check_buy(self):
        global current_money
        #one-time buy
        if self.owned_shares != 0:
            return False
        avg50 = self.get_short_moving_avg()
        avg200 = self.get_long_moving_avg()
        if avg50 == -1.0 or avg200 == -1.0:
            self.log('Short or Long moving average cannot be obtained due to yahoo API error')
            return 0
        
        current_price = self.get_price()
        if current_price is None:
            return False;
        
        if avg50 > avg200:
            #trend change, buy
            buy_count = self.how_many_shares_to_buy(current_price)
            if buy_count != 0:
                if buy(self, buy_count, current_price) == True:
                    self.owned_shares += buy_count
                    self.bought_value += float(current_price * self.owned_shares)

                    # reduce our money and re-save the config
                    current_money -= current_price * buy_count;
                    SaveConfig()
                    
            return self.owned_shares
        return 0

    def check_sell(self):
        global money_gained_this_session

        current_price = self.get_price()
        if current_price is None:
            return False;
        
        #UNCOMMENT WHEN USING ACTUAL DATA
        if self.bought_value >= current_price * self.owned_shares:
            return False

        #UNCOMMENT WHEN USING ACTUAL DATA
        if self.owned_shares == 0:
            self.log("Would have sold this stock, but none were owned")
            return False
        
        avg50 = self.get_short_moving_avg()
        avg200 = self.get_long_moving_avg()
        if avg50 < avg200:
            #trend change, buy
            if sell(self, self.owned_shares,current_price) == True:
                money_gained = self.owned_shares * current_price - self.bought_value
                self.log('Pending execution order. Return: ' + str(money_gained))
                money_gained_this_session += money_gained
                print('--Money Gained This Session: ' + str(money_gained_this_session) + ' --')
                self.owned_shares = 0
                self.bought_value = 0
                return True
        return False
Пример #22
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) + \
            str(stock.get_price_earnings_ratio()).ljust(8)+\
            stock.get_50day_moving_avg().ljust(10) +\
            stock.get_200day_moving_avg().ljust(10)
        print(line)
    except Exception as e:
        print("Exception error:", str(e))
        traceback.print_exc()
    i += 1

#you get get a spy.txt and then filter everything by yourself
def main():
    count = 0  # Counter

    # Need this for Technical Analysis calculations
    curr = datetime.datetime.now()
    currYear = str(curr.year)
    currMonth = str(curr.month)
    currDay = str(curr.day)
    currDate = currYear + '-' + currMonth + '-' + currDay
    startDate = str(curr.year - 1) + '-' + currMonth + '-' + currDay

    contents = open('constituents.csv',
                    'r')  # Open constituents file for reading
    reader = csv.reader(contents)  # CSV reader object

    writeData = open('stockData.csv', 'w',
                     newline='')  # Open output data file in write mode
    writer = csv.writer(writeData)  # CSV writer object

    for row in reader:  # For each line in the constituents file
        try:
            ticker = Share(row[0])  # Share object with ticker symbol as input

            currPrice = ticker.get_price()  # Get currPrice (15 min delay)
            avgVol = ticker.get_avg_daily_volume()  # Get average volume
            cap = ticker.get_market_cap()  # Get market cap
            yearHigh = ticker.get_year_high()  # Get year high
            yearLow = ticker.get_year_low()  # Get year low
            ma50d = ticker.get_50day_moving_avg()  # 50 DMA
            ma200d = ticker.get_200day_moving_avg()  # 200 DMA

            dataList = numpy.array([])  # Create empty numpy array
            data = ticker.get_historical(
                startDate, currDate)  # Get historical data for 1 year
            data = data[::-1]  # Reverse data

            for item in data:
                dataList = numpy.append(dataList, float(
                    item['Close']))  # Add closing prices to list

            macd, macdsignal, macdhist = talib.MACD(
                dataList, fastperiod=12, slowperiod=26,
                signalperiod=9)  # Calculate MACD values
            rsi = talib.RSI(dataList, timeperiod=14)  # Calculate RSI value

            # Write data to stockData file
            writer.writerow([
                row[0], row[1], currPrice, avgVol, cap, yearLow, yearHigh,
                ma50d, ma200d, macd[-1], macdsignal[-1], macdhist[-1], rsi[-1]
            ])

        except:
            pass

        # Update screen with percent complete
        count = count + 1
        os.system('CLS')
        print((str(format(count / 504.0 * 100.0, '.2f')) + '%'))

    # Close CSV files
    writeData.close()
    contents.close()
Пример #24
0
def getNDaysAgo(N):
    date_N_days_ago = datetime.now() - timedelta(days=N)

    return str(date_N_days_ago.date())


fname = 'C:\dump\companylist.csv'
with open(fname) as f:
    content = csv.reader(f, delimiter=',')
    twentDay = getNDaysAgo(1)
    today = str(datetime.now().date())
    for line in content:
        if any(x not in line[0] for x in ['^', '$']):
            stock = Share(line[0])
            print line[0]
            print stock.get_name()
            print stock.get_50day_moving_avg()
            # print stock.get_200day_moving_avg()
            print stock.get_avg_daily_volume()
            pprint(stock.get_historical(twentDay, today))
        else:
            print line[0] + ' contains a special character******'

# yahoo = Share('WWW')
# print yahoo.get_name()
# print yahoo.get_open();
#
# print yahoo.get_50day_moving_avg();
#
# print yahoo.get_avg_daily_volume()
Пример #25
0
		avgvolume = stock.get_avg_daily_volume()
		print avgvolume

	if myargs.short is True:
		short = stock.get_short_ratio()
		print short

	if myargs.peratio is True:
		pe = stock.get_price_earnings_ratio()
		print pe

	if myargs.exchange is True:
		exchange = stock.get_stock_exchange()

	if myargs.ma50 is True:
		ma50 = stock.get_50day_moving_avg()
		print ma50

	if myargs.ma200 is True:
		ma200 = stock.get_200day_moving_avg()
		print ma200

	if myargs.marketcap is True:
		marketcap = stock.get_market_cap()
		print marketcap

	if myargs.getopen is True:
		getopen = stock.get_open()
		print getopen

	if myargs.getbook is True:
Пример #26
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)
def svm(name, day):
    '''
    Input: Name of the stock, How many days of after current day to get predicted price
    Output: Predicted Price for next n days
    '''
    data = gethistorical(name)
    data = data[::-1]
    open_price_list = []
    close_price_list = []
    predicted_price = []
    for i in xrange(len(data)):
        open_price_list.append(data[i][1])
        close_price_list.append(data[i][2])
    for iterations in range(day):
        close_price_dataset = []
        open_price_dataset = []
        previous_ten_day_close_price_dataset = []
        g = 0
        h = 50
        while h < len(close_price_list):
            previous_ten_day_close_price_dataset.append(close_price_list[g:h])
            open_price_dataset.append(open_price_list[h])
            close_price_dataset.append(close_price_list[h])
            g += 1
            h += 1
        moving_average_dataset = []
        for x in previous_ten_day_close_price_dataset:
            i = 0
            for y in x:
                i = i + y
            moving_average_dataset.append(i / 10)
        feature_dataset = []
        for j in range(len(close_price_dataset)):
            list = []
            list.append(moving_average_dataset[j])
            list.append(open_price_dataset[j])
            feature_dataset.append(list)
        feature_dataset = numpy.array(feature_dataset)
        close_price_dataset = numpy.array(close_price_dataset)
        clf = SVR(kernel='linear', degree=1)
        clf.fit(feature_dataset[-365:], close_price_dataset[-365:])
        target = []
        if iterations == 0:
            url_string = "http://www.google.com/finance/getprices?q={0}".format(
                name)
            stock_info = Share(name)
            list = []
            list.append(stock_info.get_open())
            list.append(stock_info.get_50day_moving_avg())
            target.append(list)

        else:
            list = []
            list.append(moving_average_dataset[-1])
            list.append(open_price_dataset[-1])
            target.append(list)

        predicted_close_price = clf.predict(target)[0]
        predicted_price.append(predicted_close_price)
        open_price_list.append(close_price_list[-1])
        close_price_list.append(predicted_close_price)

    return predicted_price[4]
Пример #28
0
 def refresh_yahoo_api_data(self):
     yahoo_data = Share(self.symbol)
     self.fifty_moving_avg = yahoo_data.get_50day_moving_avg()
     self.two_hundred_moving_avg = yahoo_data.get_200day_moving_avg()
     self.year_high = yahoo_data.get_year_high()
     self.year_low = yahoo_data.get_year_low()
Пример #29
0
def CallSVM(name, day):
    '''
	Input: Name of the stock, How many days of after current day to get predicted price
	Output: Predicted Price for next n days
	'''
    # data = getHistoricalData(name)
    data = []
    if name in ('amzn'):
        sql = "SELECT price FROM Amazon"
    elif name in ('aapl'):
        sql = "SELECT price FROM Apple"
    elif name in ('fb'):
        sql = "SELECT price FROM Facebook"
    elif name in ('goog'):
        sql = "SELECT price FROM Google"
    elif name in ('ea'):
        sql = "SELECT price FROM EAsports"
    elif name in ('msft'):
        sql = "SELECT price FROM Microsoft"
    elif name in ('wmt'):
        sql = "SELECT price FROM Walmart"
    elif name in ('yhoo'):
        sql = "SELECT price FROM Yahoo"
    elif name in ('sne'):
        sql = "SELECT price FROM Sony"
    elif name in ('ninoy'):
        sql = "SELECT price FROM Nikon"

    cursor2.execute(sql)
    results = cursor2.fetchall()
    for row in results:
        data.append(row[0])

    data = data[::-1]
    open_price_list = []
    close_price_list = []
    predicted_price = []
    for i in range(len(data)):
        open_price_list.append(data[i][1])
        close_price_list.append(data[i][2])
    for iterations in range(day):
        close_price_dataset = []
        open_price_dataset = []
        previous_ten_day_close_price_dataset = []
        g = 0
        h = 50
        while h < len(close_price_list):
            previous_ten_day_close_price_dataset.append(close_price_list[g:h])
            open_price_dataset.append(open_price_list[h])
            close_price_dataset.append(close_price_list[h])
            g += 1
            h += 1
        moving_average_dataset = []
        for x in previous_ten_day_close_price_dataset:
            i = 0
            for y in x:
                i = i + y
            moving_average_dataset.append(i / 10)
        feature_dataset = []
        for j in range(len(close_price_dataset)):
            list = []
            list.append(moving_average_dataset[j])
            list.append(open_price_dataset[j])
            feature_dataset.append(list)
        feature_dataset = numpy.array(feature_dataset)
        close_price_dataset = numpy.array(close_price_dataset)
        clf = SVR(kernel='linear', degree=1)
        clf.fit(feature_dataset[-365:], close_price_dataset[-365:])
        target = []
        if iterations == 0:
            url_string = "http://www.google.com/finance/getprices?q={0}".format(
                name)
            stock_info = Share(name)
            list = []
            list.append(stock_info.get_open())
            list.append(stock_info.get_50day_moving_avg())
            target.append(list)

        else:
            list = []
            list.append(moving_average_dataset[-1])
            list.append(open_price_dataset[-1])
            target.append(list)

        predicted_close_price = clf.predict(target)[0]
        predicted_price.append(predicted_close_price)
        open_price_list.append(close_price_list[-1])
        close_price_list.append(predicted_close_price)

    return predicted_price
Пример #30
0
from yahoo_finance import Share
tesla = Share('TSLA')
print tesla.get_price()
print tesla.get_market_cap()

print "get_book_value:", tesla.get_book_value()
print "get_ebitda:", tesla.get_ebitda()
print "get_dividend_share:", tesla.get_dividend_share()
print "get_dividend_yield:", tesla.get_dividend_yield()
print "get_earnings_share:", tesla.get_earnings_share()
print "get_days_high:", tesla.get_days_high()
print "get_days_low:", tesla.get_days_low()
print "get_year_high:", tesla.get_year_high()
print "get_year_low:", tesla.get_year_low()
print "get_50day_moving_avg:", tesla.get_50day_moving_avg()
print "get_200day_moving_avg:", tesla.get_200day_moving_avg()
print "get_price_earnings_ratio:", tesla.get_price_earnings_ratio()
print "get_price_earnings_growth_ratio:", tesla.get_price_earnings_growth_ratio(
)
print "get_price_sales:", tesla.get_price_sales()
print "get_price_book:", tesla.get_price_book()
print "get_short_ratio:", tesla.get_short_ratio()
print "get_trade_datetime:", tesla.get_trade_datetime()
# "a:", print tesla.get_historical(start_date, end_date)
# "a:", print tesla.get_info()
print "get_name:", tesla.get_name()
print "refresh:", tesla.refresh()
print "get_percent_change_from_year_high:", tesla.get_percent_change_from_year_high(
)
print "get_percent_change_from_year_low:", tesla.get_percent_change_from_year_low(
Пример #31
0
        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) + \
            str(stock.get_price_earnings_ratio()).ljust(8)+\
            stock.get_50day_moving_avg().ljust(10) +\
            stock.get_200day_moving_avg().ljust(10) 
        print(line)    
    except Exception as e:
        print("Exception error:", str(e))
        traceback.print_exc()
    i+=1

#you get get a spy.txt and then filter everything by yourself
Пример #32
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")
Пример #33
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)
def svm(name, day):
    '''
    Input: Name of the stock, How many days of after current day to get predicted price
    Output: Predicted Price for next n days
    '''
    data = gethistorical(name)
    data = data[::-1]
    open_price_list = []
    close_price_list = []
    predicted_price=[]
    for i in xrange(len(data)):
        open_price_list.append(data[i][1])
        close_price_list.append(data[i][2])
    for iterations in range(day):
        close_price_dataset=[]
        open_price_dataset=[]
        previous_ten_day_close_price_dataset=[]
        g=0
        h=50
        while h<len(close_price_list):
            previous_ten_day_close_price_dataset.append(close_price_list[g:h])
            open_price_dataset.append(open_price_list[h])
            close_price_dataset.append(close_price_list[h])
            g += 1
            h += 1
        moving_average_dataset=[]
        for x in previous_ten_day_close_price_dataset:
            i=0
            for y in x:
                i=i+y
            moving_average_dataset.append(i/10)
        feature_dataset = []
        for j in range(len(close_price_dataset)):
            list = []
            list.append(moving_average_dataset[j])
            list.append(open_price_dataset[j])
            feature_dataset.append(list)
        feature_dataset = numpy.array(feature_dataset)        
        close_price_dataset = numpy.array(close_price_dataset)
        clf = SVR(kernel='linear',degree=1)
        clf.fit(feature_dataset[-365:],close_price_dataset[-365:])
        target = []
        if iterations==0:
            url_string = "http://www.google.com/finance/getprices?q={0}".format(name)
            stock_info = Share(name)
            list = []
            list.append(stock_info.get_open())
            list.append(stock_info.get_50day_moving_avg())
            target.append(list)
            
        else:
            list = []
            list.append(moving_average_dataset[-1])
            list.append(open_price_dataset[-1])
            target.append(list)

        predicted_close_price = clf.predict(target)[0]
        predicted_price.append(predicted_close_price)
        open_price_list.append(close_price_list[-1])
        close_price_list.append(predicted_close_price)
    
    return predicted_price
Пример #35
0
        'pk': index + 1,
        'fields': {},
    }

    fund = Share(ETF)

    fields = {
        'name': fund.get_name(),
        'symbol': ETF,
        'last_trade': fund.get_price(),
        'dividend_yield': fund.get_dividend_yield(),
        'absolute_change': fund.get_change(),
        'percentage_change': fund.get_percent_change(),
        'year high': fund.get_year_high(),
        'year low': fund.get_year_low(),
        '50 day moving average': fund.get_50day_moving_avg(),
        '200 day moving average': fund.get_200day_moving_avg(),
        'average_daily_volume': fund.get_avg_daily_volume()
    }

    etf_dict['fields'] = fields
    etf_data.append(etf_dict)
json_data = json.dumps(etf_data)

# print(json_data)

output_dict = [y for y in etf_data if y['fields']['dividend_yield'] > 1]

output_dict = [
    x for x in output_dict if x['fields']['average_daily_volume'] > 100000
]
Пример #36
0
def write_technical_files(stock_code, start_time, end_time):
  # """ Experiment on quandl """
  # print('quandl data')
  # mydata = quandl.get("FRED/GDP")
  # print(mydata)
  # print('hello')

  # data = quandl.get("WIKI/FB.11", start_date="2014-01-01", end_date="2014-12-31", collapse="monthly", transform="diff")
  # print(data)

  stock = Share(stock_code)

  print('stock.get_info()')
  print(stock.get_info())

  print('get_price()')
  print(stock.get_price())

  print('get_change()')
  print(stock.get_change())

  print('get_stock_exchange()')
  print(stock.get_stock_exchange())

  print('get_market_cap()')
  print(stock.get_market_cap())

  print('get_book_value()')
  print(stock.get_book_value())

  print('get_ebitda()')
  print(stock.get_ebitda())

  print('get_dividend_share()')  
  print(stock.get_dividend_share())

  print('get_dividend_yield()')
  print(stock.get_dividend_yield())

  print('get_earnings_share()')
  print(stock.get_earnings_share())

  print('get_50day_moving_avg()')
  print(stock.get_50day_moving_avg())

  print('get_200day_moving_avg()')
  print(stock.get_200day_moving_avg())

  print('get_price_earnings_ratio()')
  print(stock.get_price_earnings_ratio())

  print('get_price_earnings_growth_ratio()')
  print(stock.get_price_earnings_growth_ratio())

  print('get_price_sales()')
  print(stock.get_price_sales())

  print('get_price_book()')
  print(stock.get_price_book())

  print('get_short_ratio()')
  print(stock.get_short_ratio())

  print('historical_data')
  print(stock.get_historical(start_time, end_time))

  historical_data = stock.get_historical(start_time, end_time)

  info_text = "Symbol\t" + "Stock Exchange\t" + "Price\t" + "Market Cap\t" + "Book Value\t" + "EBITDA\t" + "50d Moving Avg\t" + "100d Moving Avg\n"
  info_text += str(stock.get_info()['symbol']) + "\t" + str(stock.get_stock_exchange()) + "\t" + str(stock.get_price()) + "\t" + str(stock.get_market_cap()) + "\t" + str(stock.get_book_value()) + "\t";
  info_text += str(stock.get_ebitda()) + "\t" + str(stock.get_50day_moving_avg()) + "\t" + str(stock.get_200day_moving_avg()) + "\n";

  info_directory = '/data/info.tsv'

  write_to_file(info_directory, info_text)

  high_low_text = "date\t" + "High\t" + "Low\n"
  open_close_text = "date\t" + "Open\t" + "Close\n"
  volume_text = "date\t" + "Volume\n"

  for index, value in enumerate(historical_data):
    date = str(historical_data[len(historical_data) - 1 - index]['Date'])
    date = date.replace('-','')

    stock_high = str(historical_data[len(historical_data) - 1 - index]['High'])
    stock_low = str(historical_data[len(historical_data) - 1 - index]['Low'])

    stock_open = str(historical_data[len(historical_data) - 1 - index]['Open'])
    stock_close = str(historical_data[len(historical_data) - 1 - index]['Close'])

    stock_volume = str(int(historical_data[len(historical_data) - 1 - index]['Volume']) / 1000)

    high_low_text += date + "\t" + stock_high + "\t" + stock_low + "\n"
    open_close_text += date + "\t" + stock_open + "\t" + stock_close + "\n"
    volume_text += date + "\t" + stock_volume + "\n"

  high_low_directory = '/data/highlow.tsv'
  open_close_directory = '/data/openclose.tsv'
  volume_directory = '/data/volume.tsv'

  write_to_file(high_low_directory, high_low_text)
  write_to_file(open_close_directory, open_close_text)
  write_to_file(volume_directory, volume_text)

  ratio_text = "name\t" + "value\n"

  if stock.get_change() != None:
    name = "Change"
    value = str(stock.get_change())
    ratio_text += name + "\t" + value + "\n"

  if stock.get_dividend_share() != None:
    name = "Dividend Share"
    value = str(stock.get_dividend_share())
    ratio_text += name + "\t" + value + "\n"

  if stock.get_dividend_yield() != None:
    name = "Divident Yield"
    value = str(stock.get_dividend_yield())
    ratio_text += name + "\t" + value + "\n"

  if stock.get_earnings_share() != None:
    name = "Earning Share"
    value = str(stock.get_earnings_share())
    ratio_text += name + "\t" + value + "\n"

  if stock.get_price_earnings_ratio() != None:
    name = "Price Earning"
    value = str(stock.get_price_earnings_ratio())
    ratio_text += name + "\t" + value + "\n"

  if stock.get_price_earnings_growth_ratio() != None:
    name = "Price Earning Growth"
    value = str(stock.get_price_earnings_growth_ratio())
    ratio_text += name + "\t" + value + "\n"

  if stock.get_price_sales() != None:
    name = "Price Sales"
    value = str(stock.get_price_sales())
    ratio_text += name + "\t" + value + "\n"

  if stock.get_price_book() != None:
    name = "Price Book"
    value = str(stock.get_price_book())
    ratio_text += name + "\t" + value + "\n"

  if stock.get_short_ratio() != None:
    name = "Short"
    value = str(stock.get_short_ratio())
    ratio_text += name + "\t" + value + "\n"

  ratio_directory = '/data/ratio.tsv'

  write_to_file(ratio_directory, ratio_text)
    def on_message(self, message):
        print_logger.debug("Received message: %s" % (message))

        self.write_message("Test 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]

            # The file I have stored didn't end up being a good validation
            # option as it does not contain a complete list of all
            # securities.  I have to acquire the data from yahoo
            # finance anyway, so just use that.  The Share function
            # call will throw a NameError exception if the ticker doesn't exist
            # isValid = current_stock_list.is_valid_stock(ticker)

            isValid = True
            try:
                test = Share(str(ticker))

                if test.get_price() is None:
                    isValid = False
            except NameError:
                isValid = False

            if isValid:
                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 = ""
            try:
                company_info="../task_1/google_search_program/cleaned_data/" + company_ticker + "/company_info"
                company_name = " "

                f = open(company_info, "r")
                line = f.readlines()
                company_name = line[0].split(",")
                company_name = company_name[0]
                company_name = company_name.title()

                if '(' not in company_name:
                    company_name = company_name + " (%s)" % company_ticker
            except Exception:
                company_name = get_company_title_proxied(company_ticker)


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

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

            if len(message) != 2:
                print_logger.error("Malformed input query")
                self.write_message("QueryResult:Error")

            data = current_solr_object.issue_query(str(message[1]))

            data = current_solr_object.recover_links(data)

            final_string = "QueryResult"

            for link in data:
                final_string = final_string + ":" + str(link)

            self.write_message(final_string)

        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]

            # Read in the company description
            description = ""
            try:
                f = open("../task_1/google_search_program/cleaned_data/%s/company_description" % str(ticker), "r")
                description = f.read()
            except Exception:
                # If the file does not exist, get the data manually
                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]

            # Get the bollinger band history along with the 5 day moving average
            close, lower_band, five_day_ma = calculate_bands(ticker)

            last_5_days_5_day_ma = []
            last_5_days_bb = []
            last_5_days_close = []
            for i in range(0, 5):
                last_5_days_5_day_ma.append(five_day_ma[i])
                last_5_days_bb.append(lower_band[i])
                last_5_days_close.append(close[i])

            condition_1 = False
            condition_2 = False

            # Condition 1: Has the stock price at close been below the lower bollinger band
            # at market close within the last 5 days
            for i in range(0, 5):
                if last_5_days_close[i] < last_5_days_bb[i]:
                    condition_1 = True

            # Condition 2: Has the current stock price been above the 5 day moving average sometime in the last 3 days
            for i in range(0, 3):
                if last_5_days_close[i] > last_5_days_5_day_ma[i]:
                    condition_2 = True

            if condition_1 is True and condition_2 is True:
                self.write_message("BB:GoodCandidate")
            else:
                self.write_message("BB:BadCandidate")
        elif "GetSentiment" in message:
            message = message.split(":")

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

            ticker = message[1]

            # Lists of sentiment based words
            good_words = ["buy", "bull", "bullish", "positive", "gain", "gains", "up"]
            bad_words = ["sell", "bear", "bearish", "negative", "loss", "losses", "down"]

            DATA_DIRECTORY = "../task_1/google_search_program/cleaned_data/%s" % ticker.upper()


            positive_file_stats = []
            negative_file_stats = []
            positive_files = 0
            negative_files = 0

            neutral_files = 0

            trump_count = 0

            files_examined = 0

            for root, dirs, files in os.walk(DATA_DIRECTORY):
                path = root.split(os.sep)
                print((len(path) - 1) * '---', os.path.basename(root))

                for file in files:

                    if "article" in file:
                        f = open('/'.join(path) + '/' + file)

                        title = f.readline()

                        article_text = " ".join(f.readlines())

                        if article_text.count("trump") > 0:
                            trump_count = trump_count + 1

                        positive_word_count = 0
                        negative_word_count = 0

                        files_examined = files_examined + 1

                        for word in good_words:
                            if word in article_text:
                                positive_word_count = positive_word_count + article_text.count(word)
                                print "Word: %s, %s" % (word, article_text.count(word))


                        for word in bad_words:
                            if word in article_text:
                                negative_word_count = negative_word_count + article_text.count(word)

                        if positive_word_count > negative_word_count:
                            positive_ratio = float(positive_word_count) / float(negative_word_count + positive_word_count)

                            if positive_ratio > 0.7:
                                positive_files = positive_files + 1

                                positive_file_stats.append((positive_word_count, negative_word_count))
                            else:
                                neutral_files = neutral_files + 1

                        elif positive_word_count == negative_word_count:
                            neutral_files = neutral_files + 1

                        else:
                            negative_ratio = float(negative_word_count) / float(negative_word_count + positive_word_count)

                            if negative_ratio > 0.7:
                                negative_files = negative_files + 1

                                negative_file_stats.append((positive_word_count, negative_word_count))
                            else:
                                neutral_files = neutral_files + 1

            print_logger.debug("Sentiment:" + str(positive_files) + ":" + str(negative_files) +\
                ":" + str(neutral_files) + ":" + str(trump_count) + ":" + str(files_examined))

            self.write_message("Sentiment:" + str(positive_files) + ":" + str(negative_files) +\
                ":" + str(neutral_files) + ":" + str(trump_count) + ":" + str(files_examined))