예제 #1
0
def collect_stock_data(symbol):
    """ Collect stock data for stock with symbol symbol
	:param symbol: symbol of stock to collect data for
	:return: dictionary containing stock data
	"""
    stock_data = dict()
    stock = Share(symbol)
    # check if symbol was for a valid stock
    name = stock.get_name()
    if name == 'N/A':
        return None
    stock_data['symbol'] = symbol
    stock_data['name'] = name
    # get all data between today and start of 21st century
    start_date = time.strftime("2000-01-01")
    end_date = time.strftime("%Y-%m-%d")
    stock_data['historical_data'] = stock.get_historical(start_date, end_date)
    # get dividend information
    stock_data['dividend_per_share'] = stock.get_dividend_share()
    stock_data['dividend_yield'] = stock.get_dividend_yield()
    # get volume information
    stock_data['avg_daily_volume'] = stock.get_avg_daily_volume()
    # primary key is the stock's symbol
    stock_data['_id'] = symbol
    return stock_data
예제 #2
0
파일: tasks.py 프로젝트: JoshuaKw/Minvest
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())
예제 #3
0
 def update_ETF_value(self):
     fund = Share(self.symbol)
     self.last_trade = fund.get_price()
     self.absolute_change = fund.get_change()
     self.percentage_change = fund.get_percent_change()
     self.dividend_yield = fund.get_dividend_yield()
     self.last_updated = timezone.now()
     self.save()
예제 #4
0
def getStock(name_of_company):
    global company_name,company_symbol
    stock = []
    k=0
    stock.append([])
    stock.append("NA")
    stock.append("NA")
    stock.append("NA")
    stock.append("NA")
    stock.append("NA")
    stock.append("NA")
    stock.append("NA")
    j=0
    for i in company_symbol:
        if i == name_of_company:
            break
        j=j+1
    print "j is "+str(j)+"link is "
    stock[0]=company_name[j]
    yahoo = Share(name_of_company)
    stock[1] = yahoo.get_open()
    stock[2] = yahoo.get_price()
    stock[3] = yahoo.get_trade_datetime()
    stock[4] = company_symbol[j]
    stock[5] = yahoo.get_volume()
    stock[6] = yahoo.get_dividend_yield()
    stock[7] = google_links[j]
    print stock
    conn = mysql.connect()
    cur = conn.cursor()
    if 'username' in session:
        username = session['username']
    cur.execute("SELECT purse FROM user WHERE username = %s;", [username])
    print username
    for row in cur.fetchall():
        for lol in row:
            purse=lol
    companystock = [dict(
        name=stock[0],
        open=stock[1],
        lasttradeprice=stock[2],
        lasttradetime=stock[3],
        stocksymbol=stock[4],
        MarketCapital=stock[5],
        dividend=stock[6],
        link=stock[7]
    )]
    cur.execute("SELECT stock FROM user WHERE username = %s;", [username])
    print username
    for row in cur.fetchall():
        for lol in row:
            newarray = lol.split(',')
            currentstock = newarray[j]

    print purse
    return companystock,stock,purse,currentstock
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})
예제 #6
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
예제 #7
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
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()
예제 #10
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
예제 #11
0
def get_symbol_yahoo_stats_yql(symbols, exclude_name=False):
    """
    Get the symbols' basic statistics from Yahoo Finance.
    Input:
       symbols - a list of symbol strings, e.g. ['AAPL']
    Output: stats in Pandas DataFrame.
    This function is ported from pandas_datareader/yahoo/components.py
    """
    sym_list = str2list(symbols)
    if sym_list == None:
        return DataFrame()

    # Yahoo Finance tags, refer to http://www.financialwisdomforum.org/gummy-stuff/Yahoo-data.htm
    tags = ['Symbol']
    if not exclude_name:
        tags += ['Name']
    tags += ['Exchange', 'MarketCap', 'Volume', 'AverageDailyVolume', 'BookValue', 'P/E', 'PEG', 'Price/Sales',
            'Price/Book', 'EBITDA', 'EPS', 'EPSEstimateNextQuarter', 'EPSEstimateCurrentYear', 'EPSEstimateNextYear',
            'OneyrTargetPrice', 'PriceEPSEstimateCurrentYear', 'PriceEPSEstimateNextYear', 'ShortRatio',
            'Dividend/Share', 'DividendYield', 'DividendPayDate', 'ExDividendDate']
    lines = []
    for sym in sym_list:
        stock = Share(sym)
        line = [sym]
        if not exclude_name:
            line += [stock.get_name()]
        line += [stock.get_stock_exchange(), str2num(stock.get_market_cap(), m2b=True),
                str2num(stock.get_volume()), str2num(stock.get_avg_daily_volume()), str2num(stock.get_book_value()),
                str2num(stock.get_price_earnings_ratio()), str2num(stock.get_price_earnings_growth_ratio()),
                str2num(stock.get_price_sales()), str2num(stock.get_price_book()), str2num(stock.get_ebitda()),
                str2num(stock.get_earnings_share()), str2num(stock.get_EPS_estimate_next_quarter()),
                str2num(stock.get_EPS_estimate_current_year()), str2num(stock.get_EPS_estimate_next_year()),
                str2num(stock.get_one_yr_target_price()), str2num(stock.get_price_EPS_estimate_current_year()),
                str2num(stock.get_price_EPS_estimate_next_year()), str2num(stock.get_short_ratio()),
                str2num(stock.get_dividend_share()), str2num(stock.get_dividend_yield()), stock.get_dividend_pay_date(),
                stock.get_ex_dividend_date()]
        lines.append(line)

    stats = DataFrame(lines, columns=tags)
    stats = stats.drop_duplicates()
    stats = stats.set_index('Symbol')
    return stats
예제 #12
0
def getStat(stockTicker):
    StatDict = dict()
    ticker = Share(stockTicker)

    mktCap = ticker.get_market_cap()
    if (mktCap != None and mktCap != 0):
        StatDict["Market cap"] = mktCap
    ebitda = ticker.get_ebitda()
    if (ebitda != None and ebitda != 0):
        StatDict["EBITDA"] = ebitda
    peR = ticker.get_price_earnings_ratio()
    if (peR != None and peR != 0):
        StatDict["Price Earning Ratio"] = peR
    EPS = ticker.get_earnings_share()
    if (EPS != None and EPS != 0):
        StatDict["EPS"] = EPS
    divYield = ticker.get_dividend_yield()
    if (divYield != None and divYield != 0):
        StatDict["Dividend Yield"] = divYield
    return StatDict
예제 #13
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)
    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))
예제 #15
0
for index, ETF in enumerate(ETF_master_list):

    etf_dict = {
        'model': 'portfolio.ETF',
        '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)
예제 #16
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")
예제 #17
0
파일: yfcmd.py 프로젝트: nhsb1/config
		print marketcap

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

	if myargs.getbook is True:
		getbook = stock.get_book_value()
		print getbook

	if myargs.dividendshare is True:
		getdiv = stock.get_dividend_share()
		print getdiv

	if myargs.dividendyield is True:
		dividendyield = stock.get_dividend_yield()
		print dividendyield

	if myargs.eps is True:
		eps = stock.get_earnings_share()
		print eps

	if myargs.dayh is True:
		dayhigh = stock.get_days_high()
		print dayhigh

	if myargs.dayl is True:
		daylow = stock.get_days_low()
		print daylow

	if myargs.yearhigh is True:
예제 #18
0
def main():
    # 1. get the time
    day = Time.get_utc_day()
    hours_mins = Time.get_utc_hours_minutes()

    # 1. Get all the list of stocks
    stocks = base.managers.stock_manager.get_many()

    # 2. go through stock and update the desired values
    for stock in stocks:
        ticker = stock.get('ticker')

        try:
            # 2.1 Get the info from the yahoo API
            updated_stock = Share(ticker)
        except:
            print "-->Failed to update: %s with Yahoo API" % ticker
            continue

        price = updated_stock.get_price()
        open = updated_stock.get_open()
        days_high = updated_stock.get_days_high()
        days_low = updated_stock.get_days_low()
        year_high = updated_stock.get_year_high()
        year_low = updated_stock.get_year_low()
        volume = updated_stock.get_volume()
        market_cap = updated_stock.get_market_cap()
        pe_ratio = updated_stock.get_price_earnings_ratio()
        div_yield = updated_stock.get_dividend_yield()
        change = updated_stock.get_change()
        change_percent = updated_stock.data_set.get('ChangeinPercent')

        # 2.2 Get the stock body
        stock_body = stock.get('body')

        stock_price = {hours_mins: price}

        if stock_body:
            # 1. Get the stock info for the day:
            stock_info = stock_body.get(day)

            if stock_info:
                stock_price = stock_info.get('price')
                stock_price.update({hours_mins: price})
        else:
            stock_body = {}

        # 2.2.4 update the stock info dict
        stock_info = {'price': stock_price}
        stock_info.update({'open': open})
        stock_info.update({'days_high': days_high})
        stock_info.update({'days_low': days_low})
        stock_info.update({'year_high': year_high})
        stock_info.update({'year_low': year_low})
        stock_info.update({'volume': volume})
        stock_info.update({'market_cap': market_cap})
        stock_info.update({'pe_ratio': pe_ratio})
        stock_info.update({'div_yield': div_yield})
        stock_info.update({'change': change})
        stock_info.update({'change_percent': change_percent})

        # update the stock body
        stock_body.update({day: stock_info})

        stock.body = stock_body

        # 3. update the stock in the DB
        try:
            base.managers.stock_manager.update_one(stock)
        except:
            print "-->Failed to update: %s in DB" % ticker
            continue
예제 #19
0
# Determine functionality

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(
)
예제 #20
0
def stock_quote_get():
    print(request.args.get('symbol'))
    symbol = str(request.args.get('symbol'))

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

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

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

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

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

    close_history = []

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

    return render_template("stock/stock_detail.html",
                           stock_name=stock_name,
                           stock_symbol=stock_symbol,
                           stock_price=stock_price,
                           stock_change=stock_change,
                           stock_change_pct=stock_change_pct,
                           prev_close=prev_close,
                           open=open,
                           day_range=day_range,
                           year_range=year_range,
                           volume=volume,
                           avg_volume=avg_volume,
                           market_cap=market_cap,
                           pe_ratio=pe_ratio,
                           eps=eps,
                           dividend=dividend,
                           dividend_yld=dividend_yld,
                           dividend_ex_date=dividend_ex_date,
                           yr_target=yr_target,
                           close_history=close_history)
예제 #21
0

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()
# print share.get_info()
# print share.get_open()
# print share.get_prev_close()
# print share.get_price()
예제 #22
0
from yahoo_finance import Share
#yahoo = Share('YHOO')
#yahoo = Share('SPXC')
yahoo = Share('TFM')
#yahoo = Share('INDU')
#INDEXSP
#yahoo = Share('NDX')
print yahoo
print yahoo.get_open()
#'36.60'
print yahoo.get_price()
print yahoo.get_price_earnings_ratio()
print 'get_dividend_share: ',yahoo.get_dividend_share()
print 'get_dividend_yield: ',yahoo.get_dividend_yield()
print 'get_earnings_share: ',yahoo.get_earnings_share()
print 'get_price_earnings_ratio: ',yahoo.get_price_earnings_ratio()
print 'get_price_earnings_growth_ratio: ',yahoo.get_price_earnings_growth_ratio()
print 'get_year_high: ',yahoo.get_year_high()
print 'get_year_low: ',yahoo.get_year_low()
print 'get_days_high: ',yahoo.get_days_high()
print 'get_days_low: ',yahoo.get_days_low()
print 'get_ebitda: ',yahoo.get_ebitda()
print 'get_book_value: ',yahoo.get_book_value()
#'36.84'
#print yahoo.get_trade_datetime()
#'2014-02-05 20:50:00 UTC+0000'
#get_avg_daily_volume()
예제 #23
0
 def loadKeyStatistics (cls, companyID = 'A'):
     '''
     dataset 
     df= pd.DataFrame(columns=['marketCapital','bookValue','ebitda','dividentShare','DividentYield','earningShare',
                               'BookPrice','SalesPrice','earningsGrowth','earningsRatio', 'symbol', 'date'])
     '''
     yahoo = Share(companyID)
     yahoo.refresh()
    
     try:    
         a = re.search('[a-zA-Z]+', yahoo.get_market_cap())
         b = re.search('[a-zA-Z]+', yahoo.get_ebitda())
 
         if a.group(0) is not None:
             p = re.split('[a-zA-Z]+', yahoo.get_market_cap())
             if a.group(0) in 'B':
                 marketCap = float(p[0]) * 10 ** 9
             elif a.group(0) in 'M':
                 marketCap = float(p[0]) * 10 ** 6
             else: 
                 marketCap = -1
             print ('Market cap: ' + yahoo.get_market_cap())
         else:
             marketCap = yahoo.get_market_cap()
     
         if b.group(0) is not None:    
             p = re.split('[a-zA-Z]+', yahoo.get_ebitda())
             if b.group(0) in 'B':
                 ebitda = float(p[0]) * 10 ** 9
             elif b.group(0) in 'M':
                 ebitda = float(p[0]) * 10 ** 6
             else: 
                 ebitda = -1
             
             print ('Ebitda: ' +yahoo.get_ebitda())
         else:
             ebitda =  yahoo.get_ebitda()
 
     except (TypeError, AttributeError):
         print ('Missing :' + companyID)
         e = sys.exc_info()[0]
         print( "<p>Error: %s</p>" % e )
         ebitda = -1.0
         marketCap = -1.0
     
     try:
         company = LoadYahooFinance(symbol = companyID, marketCap = marketCap, bookValue = float(yahoo.get_book_value()), ebitda = ebitda, 
                                dividentShare = float(yahoo.get_dividend_share()), dividentYield = float(yahoo.get_dividend_yield()), earningShare = float(yahoo.get_earnings_share()),
                                bookPrice = float(yahoo.get_price_book()), salesPrice = float(yahoo.get_price_sales()), earningsGrowth = float(yahoo.get_price_earnings_growth_ratio()),
                                earningRatio = float(yahoo.get_price_earnings_ratio()))
         
         return company
     except TypeError:
         print ('Missing :' + companyID)
         e = sys.exc_info()[0]
         print( "<p>Error: %s</p>" % e )
예제 #24
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)
예제 #25
0
class StockAnalysis:

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

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

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

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

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

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

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

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

	def get200DaysLowPrice(self,symbol):
		pass
	def get200DaysHighPrice(self,symbol):
		pass
	
	def get50DaysLowPrice(self,symbol):
		pass
	def get50DaysHighPrice(self,symbol):
		pass
	def getPERation(self):
		pass
예제 #26
0
def result_page(request):
    rstlist = list()
    grow_sortlst = list()
    value_sortlst = list()
    quality_sortlst = list()

    grow_stcklist = [ 'PNW','RL','PPG','ACN', 'ATVI', 'AYI', 'AMD', 'LNT', 'ALXN', 'GOOGL']
    value_stcklist = ['AMG', 'AFL', 'APD', 'AKAM','PCG','PM','PSX', 'AAP', 'AES', 'AET']
    quality_stcklist = ['MMM', 'ABT', 'ABBV','PEP','PKI','PRGO','PFE', 'ALB', 'ECL', 'AGN']
    stckdict = dict()

    if request.method == 'POST':
        allotment = int(str(request.POST['allotment']))
        ori_allotment = allotment
        iv_type = 0
        for key in request.POST.keys():
            print "iv_type="+str(iv_type)
            print str(key)
            if key in ['ethical','growth','index','quality','value']:
                iv_type = iv_type + 1

        print("current selected types count = " + str(iv_type))
        if iv_type == 2:
            allotment = allotment/float(2)

        if 'ethical' in request.POST.keys():
            AAPL = Share('AAPL')
            aapl_f = float(str(AAPL.get_percent_change_from_year_low())[0:-1]) + \
                     float(str(AAPL.get_percent_change_from_50_day_moving_average())[0:-1]) - \
                     float(str(AAPL.get_percent_change_from_year_high())[0:-1])

            ADBE = Share('ADBE')
            adbe_f = float(str(ADBE.get_percent_change_from_year_low())[0:-1]) + \
                     float(str(ADBE.get_percent_change_from_50_day_moving_average())[0:-1]) - \
                     float(str(ADBE.get_percent_change_from_year_high())[0:-1])

            NSRGY = Share('NSRGY')
            nsrgy_f = float(str(NSRGY.get_percent_change_from_year_low())[0:-1]) + \
                      float(str(NSRGY.get_percent_change_from_50_day_moving_average())[0:-1]) - \
                      float(str(NSRGY.get_percent_change_from_year_high())[0:-1])
            stckdict['AAPL'] = AAPL
            stckdict['ADBE'] = ADBE
            stckdict['NSRGY'] = NSRGY
            total_f = (aapl_f + adbe_f + nsrgy_f)*iv_type
            aapl_pct = aapl_f/float(total_f)
            adbe_pct = adbe_f/float(total_f)
            nsrgy_pct = nsrgy_f/float(total_f)
            aaplD = {"sticker":"AAPL","name":AAPL.get_name(),"aloc_pct":str(aapl_pct),"aloc_amt":str(allotment*aapl_pct),"price":str(AAPL.get_price()),"exchange":str(AAPL.get_stock_exchange())}
            adbeD = {"sticker":"ADBE","name":ADBE.get_name(),"aloc_pct":str(adbe_pct),"aloc_amt":str(allotment*adbe_pct),"price":str(ADBE.get_price()),"exchange":str(ADBE.get_stock_exchange())}
            nsrgyD = {"sticker":"NSRGY","name":NSRGY.get_name(),"aloc_pct":str(nsrgy_pct),"aloc_amt":str(allotment*nsrgy_pct),"price":str(NSRGY.get_price()),"exchange":str(NSRGY.get_stock_exchange())}
            rstlist.append(aaplD)
            rstlist.append(adbeD)
            rstlist.append(nsrgyD)

        if 'growth' in request.POST.keys():
            for stock in grow_stcklist:
                while True:
                    try:
                        detail = Share(stock)
                    except:
                        time.sleep(0.1)
                        continue
                    break
                stckdict[stock]=detail
                heapq.heappush(grow_sortlst, (float(str(detail.get_percent_change_from_year_low())[0:-1]) +
                                              float(
                                                  str(detail.get_percent_change_from_200_day_moving_average())[0:-1]) +
                                              float(str(detail.get_percent_change_from_50_day_moving_average())[0:-1]) +
                                              float(str(detail.get_percent_change_from_year_high())[0:-1]), stock,
                                              detail))
                if len(grow_sortlst) > 3:
                    heapq.heappop(grow_sortlst)
            total_f = 0
            for item in grow_sortlst:
                total_f = total_f + item[0]
            for item in grow_sortlst:
                item_pct = item[0]/float(total_f*iv_type)
                item_amt = allotment*item_pct
                rstlist.append({"sticker":item[1],"name":item[2].get_name(),"aloc_pct":str(item_pct),"aloc_amt":str(item_amt),"price":str(item[2].get_price()),"exchange":str(item[2].get_stock_exchange())})

        if 'index' in request.POST.keys():

            VTI = Share('VTI')
            vti_f = float(str(VTI.get_percent_change_from_year_low())[0:-1]) + \
                     float(str(VTI.get_percent_change_from_200_day_moving_average())[0:-1]) - \
                     float(str(VTI.get_percent_change_from_year_high())[0:-1])

            IXUS = Share('IXUS')
            ixus_f = float(str(IXUS.get_percent_change_from_year_low())[0:-1]) + \
                     float(str(IXUS.get_percent_change_from_200_day_moving_average())[0:-1]) - \
                     float(str(IXUS.get_percent_change_from_year_high())[0:-1])

            ILTB = Share('ILTB')
            iltb_f = float(str(ILTB.get_percent_change_from_year_low())[0:-1]) + \
                      float(str(ILTB.get_percent_change_from_200_day_moving_average())[0:-1]) - \
                      float(str(ILTB.get_percent_change_from_year_high())[0:-1])
            stckdict['VTI'] = VTI
            stckdict['IXUS'] = IXUS
            stckdict['ILTB'] = ILTB
            total_f = (vti_f + ixus_f + iltb_f)*iv_type
            vti_pct = vti_f / float(total_f)
            ixus_pct = ixus_f / float(total_f)
            iltb_pct = iltb_f / float(total_f)
            vtiD = {"sticker": "VTI", "name": VTI.get_name(), "aloc_pct": str(vti_pct),
                     "aloc_amt": str(allotment * vti_pct), "price": str(VTI.get_price()),
                     "exchange": str(VTI.get_stock_exchange())}
            ixusD = {"sticker": "IXUS", "name": IXUS.get_name(), "aloc_pct": str(ixus_pct),
                     "aloc_amt": str(allotment * ixus_pct), "price": str(IXUS.get_price()),
                     "exchange": str(IXUS.get_stock_exchange())}
            iltbD = {"sticker": "ILTB", "name": ILTB.get_name(), "aloc_pct": str(iltb_pct),
                      "aloc_amt": str(allotment * iltb_pct), "price": str(ILTB.get_price()),
                      "exchange": str(ILTB.get_stock_exchange())}
            rstlist.append(vtiD)
            rstlist.append(ixusD)
            rstlist.append(iltbD)

        if 'quality' in request.POST.keys():
            for stock in quality_stcklist:
                while True:
                    try:
                        detail = Share(stock)
                    except:
                        time.sleep(0.1)
                        continue
                    break
                stckdict[stock] = detail
                heapq.heappush(quality_sortlst, (
                    float(detail.get_price_earnings_ratio() if detail.get_price_earnings_ratio() != None else 0) +
                    float(
                        detail.get_price_earnings_growth_ratio() if detail.get_price_earnings_growth_ratio() != None else 0) +
                    float(
                        detail.get_change_from_200_day_moving_average() if detail.get_change_from_200_day_moving_average() != None else 0) +
                    float(
                        detail.get_price_earnings_growth_ratio() if detail.get_price_earnings_growth_ratio() != None else 0),
                    stock, detail))
                if len(quality_sortlst) > 3:
                    heapq.heappop(quality_sortlst)
            total_f = 0
            for item in quality_sortlst:
                total_f = total_f + item[0]
            for item in quality_sortlst:
                item_pct = item[0] / float(total_f*iv_type)
                item_amt = allotment * item_pct
                rstlist.append({"sticker": item[1], "name": item[2].get_name(), "aloc_pct": str(item_pct),
                                "aloc_amt": str(item_amt), "price": str(item[2].get_price()),
                                "exchange": str(item[2].get_stock_exchange())})

        if 'value' in request.POST.keys():
            for stock in value_stcklist:
                while True:
                    try:
                        detail = Share(stock)
                    except:
                        time.sleep(0.1)
                        continue
                    break
                stckdict[stock] = detail
                heapq.heappush(value_sortlst,
                               (float(detail.get_dividend_yield() if detail.get_dividend_yield() != None else 0) +
                                float(
                                    detail.get_price_earnings_growth_ratio() if detail.get_price_earnings_growth_ratio() != None else 0) -
                                float(detail.get_price_book() if detail.get_price_book() != None else 0), stock,
                                detail))
                if len(value_sortlst) > 3:
                    heapq.heappop(value_sortlst)
            total_f = 0
            for item in value_sortlst:
                total_f = total_f + item[0]
            print "total_f=" + str(total_f)
            for item in value_sortlst:
                item_pct = item[0] / float(total_f*iv_type)
                item_amt = allotment * item_pct
                rstlist.append({"sticker": item[1], "name": item[2].get_name(), "aloc_pct": str(item_pct),
                                "aloc_amt": str(item_amt), "price": str(item[2].get_price()),
                                "exchange": str(item[2].get_stock_exchange())})
        days_cnt = 15
        str_date =  str((datetime.now() - timedelta(days=days_cnt)).date().isoformat())
        end_date = str(datetime.today().date().isoformat())
        day_pro = list()
        remaining = 0
        for item in rstlist:
            while True:
                try:
                    hist_info = stckdict[item["sticker"]].get_historical(str_date,end_date)
                except:
                    continue
                break
            for i in range(0,6):
                if len(day_pro)<=i:
                    day_pro.append({hist_info[i]["Date"]:float(hist_info[i]["Close"])*int(float(item["aloc_amt"])/float(hist_info[i]["Open"]))+float(item["aloc_amt"])%float(hist_info[i]["Open"])})
                else:
                    day_pro[i][hist_info[i]["Date"]] = float(day_pro[i][hist_info[i]["Date"]]) + float(hist_info[i]["Close"])*int(float(item["aloc_amt"])/float(hist_info[i]["Open"])) + float(item["aloc_amt"])%float(hist_info[i]["Open"])
        rstlist.append({"sticker":"portfolio","history":day_pro})
        print(json.dumps(rstlist))
        return render(request, 'portfolio/result.html', {'result': json.dumps(rstlist)})
    return render(request, 'portfolio/home.html')