def displayFinance(self, yearStart, yearEnd): yahoo = Share(self.companyCode) #declare textReturn = "" textReturn += "Opening price: " + str(yahoo.get_open()) + '\n' textReturn += "Current price: " + str(yahoo.get_price()) + '\n' textReturn += "Dividend Share: " + str( yahoo.get_dividend_share()) + '\n' textReturn += "Year High: " + str(yahoo.get_year_high()) + '\n' textReturn += "Year Low: " + str(yahoo.get_year_low()) + '\n' self.jsonObj.append({ "openPrice": str(yahoo.get_open()), "currPrice": str(yahoo.get_price()), "dividendPrice": str(yahoo.get_dividend_share()), "yearHigh": str(yahoo.get_year_high()), "yearLow": str(yahoo.get_year_low()) }) #historical data returns a jSON object jsonHistorical = yahoo.get_historical( str(yearStart) + '-04-25', str(yearEnd) + '-04-29') textReturn += "Historical Data: " + '\n' #To limit the number of historical datapoints sent numHist = 0 maxHist = 10 for dict in jsonHistorical: numHist += 1 if numHist < maxHist: textReturn += "For year " + dict['Date'] + " High was: " + dict[ 'High'] + " Low was: " + dict['Low'] + '\n' #self.jsonObj[0][dict['Date'] + "High"] = dict['High'] #self.jsonObj[0][dict['Date'] + "Low"] = dict['Low'] self.jsonObj.append({ "Highd": dict['Date'], "Lowd": dict['Date'], "Highp": dict['High'], "Lowp": dict['Low'] }) if textReturn == "": self.jsonObj.append({"success": "false"}) else: self.jsonObj.append({"success": "true"}) return textReturn
def get_quote(symbol): share = Share(symbol) if not share.get_price(): return {} change_f = float(share.get_change()) change_str = '+%.02f' % change_f if change_f >= 0 else '%.02f' % change_f change_percent_f = change_f / float(share.get_open()) * 100 change_percent = '+%.02f' % change_percent_f if change_percent_f >= 0 else '%.02f' % change_percent_f return { 'price': share.get_price(), 'change': change_str, 'change_percent': change_percent, 'open_price': share.get_open(), 'market_cap': share.get_market_cap(), 'year_low': share.get_year_low(), 'year_high': share.get_year_high(), 'day_low': share.get_days_low(), 'day_high': share.get_days_high(), 'volume': share.get_volume(), 'pe_ratio': share.get_price_earnings_ratio() or '-' }
def find_quote(word): """Given an individual symbol, find and return the corresponding financial data word -- the symbol for which you're finding the data (ex. "GOOG") """ cleanword=re.sub('[@<>]', '', word) share = Share(cleanword) price = share.get_price() if price != None: # Extract data day_high = share.get_days_high() day_low = share.get_days_low() market_cap = share.get_market_cap() year_high = share.get_year_high() year_low = share.get_year_low() yoy = calculate_YoY(share) output_string = ('*Stock*: \'{}\' \n*Current Price*: ${} \n*Day Range*: ' '${} - ${} \n*52 Wk Range*: ${} - ${} \n*YoY Change*: {}\n*Market Cap*: ' '${}').format(word.upper(), str(price), str(day_low), str(day_high), str(year_low), str(year_high), str(yoy), str(market_cap)) else: output_string = "Can't find a stock with the symbol \'" + cleanword.upper() + "\'" return output_string
def find_quote(word): """Given an individual symbol, find and return the corresponding financial data word -- the symbol for which you're finding the data (ex. "GOOG") """ cleanword = re.sub('[@<>]', '', word) share = Share(cleanword) price = share.get_price() if price != None: # Extract data day_high = share.get_days_high() day_low = share.get_days_low() market_cap = share.get_market_cap() year_high = share.get_year_high() year_low = share.get_year_low() yoy = calculate_YoY(share) output_string = ( '*Stock*: \'{}\' \n*Current Price*: ${} \n*Day Range*: ' '${} - ${} \n*52 Wk Range*: ${} - ${} \n*YoY Change*: {}\n*Market Cap*: ' '${}').format(word.upper(), str(price), str(day_low), str(day_high), str(year_low), str(year_high), str(yoy), str(market_cap)) else: output_string = "Can't find a stock with the symbol \'" + cleanword.upper( ) + "\'" return output_string
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())
def get52HL(name,attempt): try: if attempt == 0: st = Share(name) return [st.get_year_low(), st.get_year_high()] else: return [None,None] except: return get52HL(name,attempt+1)
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})
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 displayFinance(self, yearStart, yearEnd): yahoo = Share(self.companyCode) #declare textReturn = "" textReturn += "Opening price: " + str(yahoo.get_open()) + '\n' textReturn += "Current price: " + str(yahoo.get_price()) + '\n' textReturn += "Dividend Share: " + str(yahoo.get_dividend_share()) + '\n' textReturn += "Year High: " + str(yahoo.get_year_high()) + '\n' textReturn += "Year Low: " + str(yahoo.get_year_low()) + '\n' self.jsonObj.append({ "openPrice" : str(yahoo.get_open()) , "currPrice" : str(yahoo.get_price()), "dividendPrice" : str(yahoo.get_dividend_share()), "yearHigh" : str(yahoo.get_year_high()), "yearLow" : str(yahoo.get_year_low()) }) #historical data returns a jSON object jsonHistorical = yahoo.get_historical(str(yearStart) + '-04-25', str(yearEnd) + '-04-29') textReturn += "Historical Data: " + '\n' #To limit the number of historical datapoints sent numHist = 0 maxHist = 10 for dict in jsonHistorical: numHist += 1 if numHist < maxHist: textReturn += "For year " + dict['Date'] + " High was: " + dict['High'] + " Low was: " + dict['Low'] + '\n' #self.jsonObj[0][dict['Date'] + "High"] = dict['High'] #self.jsonObj[0][dict['Date'] + "Low"] = dict['Low'] self.jsonObj.append({ "Highd" : dict['Date'] , "Lowd" : dict['Date'], "Highp" : dict['High'], "Lowp" : dict['Low'] }) if textReturn == "": self.jsonObj.append({ "success" : "false" }) else: self.jsonObj.append({ "success" : "true" }) return textReturn
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 fetch_stock_price(self, stock_unit_key): # Step 1: Make HTTP Call to fetch the Stock Details # Step 2: Once received, create it into its corresponding model # Step 2.1 : Between the models, exchange packet as a native dictionary, rather as a JSON object # Get the share price share_item = Share(stock_unit_key) if share_item.get_open() is None: return share_item_dict = share_item.data_set st_model = StockModel() st_model.stock_unit = stock_unit_key st_model.stock_title = share_item_dict['Name'] # Share Price + Unit of Currency st_model.stock_price = share_item.get_price( ) + " " + share_item_dict['Currency'] deviation_price = share_item.get_change() st_model.stock_deviation = deviation_price + " (" + share_item_dict[ 'ChangeinPercent'] + ") " # Ex: '-1.83 (-1.59%)' if deviation_price[0] == '-': st_model.stock_deviation_status = 'Decline' else: st_model.stock_deviation_status = 'Incline' st_model.stock_equity = share_item.get_stock_exchange() st_model.stock_last_update_time = 'At close: ' + share_item_dict[ 'LastTradeDateTimeUTC'] st_model.stock_52wkrange = share_item.get_year_low( ) + " - " + share_item.get_year_high() st_model.stock_open = share_item.get_open() st_model.stock_market_cap = share_item.get_market_cap() st_model.stock_prev_close = share_item.get_prev_close() st_model.stock_peratio_tte = share_item.get_price_earnings_ratio() st_model_to_publish = self.payload_to_publish_dict.get_stock_payload_to_publish( st_model) self.push_stock_to_delivery_queue(st_model_to_publish, stock_unit_key)
'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) 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
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
import csv import time Symbol = [] with open('Screen2_res.csv', newline='') as csv_file: reader = csv.reader(csv_file) for row in reader: Symbol.append(row[0]) i = 0 with open('Screen2_3_res.csv', 'w', newline='') as f: writer = csv.writer(f) writer.writerow(['Symbol', 'Price', '1Y_low', 'Standard deviation', 'Marcket cap']) while i < len(Symbol): print(i/len(Symbol)*100) # print(Share(i).get_market_cap()) # print (Pre_Process.str2float(Share(i).get_market_cap())) try: temp = Share(Symbol[i]) cur = float(temp.get_price()) low = float(temp.get_year_low()) if (cur-low)/low < 3/100: writer.writerow([Symbol[i], cur, low, (cur-low)/low*100, temp.get_market_cap()]) except ConnectionError: print('Sleep') time.sleep(10) except AttributeError or KeyError: pass i += 1
except: pass #try: # russell3000.set_value(s,'Divident yield',shy.get_dividend_yield()) #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:
#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() # print share.get_price_book() # print share.get_price_earnings_growth_ratio() # print share.get_price_earnings_ratio()
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()
# 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( )
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()
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))
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: yearhigh = stock.get_year_high() print yearhigh if myargs.yearlow is True: yearlow = stock.get_year_low() print yearlow if myargs.ebitda is True: ebitda = stock.get_ebitda() print ebitda if myargs.ps is True: ps = stock.get_price_sales() print ps if myargs.peg is True: peg = stock.get_price_earnings_growth_ratio() print peg if myargs.percentchange is True:
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()
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()
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)
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
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
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")
stockArray = [] csvfile = open('companylist.csv', 'r') fieldnames = ("Symbol","Name","LastSale", "MarketCap", "IPOyear", "Sector", "industry") reader = csv.DictReader(csvfile, fieldnames) reader.next() for row in reader: s = Stock(row["Symbol"], row["Name"], row["LastSale"], row["MarketCap"], row["IPOyear"], row["Sector"], row["industry"]) stockArray.append(s) for s in stockArray: try: quoteFromGoogle = getQuotes(s.symbol) shareFromYahoo = Share(s.symbol) todaysPrice = quoteFromGoogle[0]["LastTradePrice"] yearLow = shareFromYahoo.get_year_low() print("Today's price for " + s.symbol + " is " + todaysPrice) print("52 Year Low: " + yearLow) if float(todaysPrice) <= float(yearLow): print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") body = s.symbol + " (" + s.name + ") " +" is now at 52 weeks low!! \n Today's price is at $" + todaysPrice + "; 52 weeks low was $" + yearLow " message = client.messages.create(to="+14152793685", from_="+15109015113", body=body) print(body) print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") except: print("#####################################") print(s.symbol + " is not invalid") print("#####################################")
def checklist(symbol, ibd50_list, ibd_session): """ Looks up information on a given stock market symbol. The returned dictionary contains all information from Dr. Wish's Stock Checklist for HONR348M. """ stock = {} # Load price data from yahoo. share = Share(symbol) ks = yahoo_ks(symbol) # Basics basics = stock["basics"] = {} basics["date"] = datetime.now().strftime("%m/%d/%Y %I:%M:%S%z") basics["symbol"] = symbol basics["equity_name"] = share.get_name() basics["price"] = float(share.get_price()) basics["52w_low"] = float(share.get_year_low()) basics["52w_high"] = float(share.get_year_high()) basics["percent_from_52w_low"] = share.get_percent_change_from_year_low() basics["percent_from_52w_high"] = share.get_percent_change_from_year_high() # IBD (Stocks only) ibd = stock["ibd"] = ibd_stock_checkup(symbol, ibd_session) # ibd["industry"] ibd["industry_rank"] = float(ibd["industry_rank"]) # ibd["industry_top5"] # ibd["3y_eps_growth"] # ibd["3y_sales_growth"] # ibd["eps_change"] ibd["eps_rating"] = float(ibd["eps_rating"]) ibd["rs_rating"] = float(ibd["rs_rating"]) # ibd["acc_distr_rating"] ibd["ibd_rating"] = float(ibd["ibd_rating"]) ibd["in_ibd50"] = symbol in ibd50_list # ibd["fundamental_greens"] # ibd["technical_greens"] ibd["next_earning"] = datetime.strptime(ibd["next_earning"], '%m/%d/%Y') # Yahoo Finance (Stocks only) yahoo = stock["yahoo"] = {} yahoo["pe"] = float(share.get_price_earnings_ratio()) yahoo["peg"] = float(share.get_price_earnings_growth_ratio()) yahoo["ps"] = float(share.get_price_sales()) yahoo["market_cap"] = share.get_market_cap() yahoo["float"] = ks["Float"] yahoo["annual_roe"] = ks["Return on Equity"] yahoo["percent_inst"] = ks["% Held by Institutions"] yahoo["percent_float_short"] = ks["Short % of Float"] yahoo["short_ratio"] = float(share.get_short_ratio()) # Evidence of an uptrend/downtrend uptrend = stock["uptrend"] = {} downtrend = stock["downtrend"] = {} pdstockdata = data.DataReader(symbol, 'yahoo', '1900-01-01') sd = StockDataFrame.retype(pdstockdata) sd.BOLL_PERIOD = 15 close1 = sd['close'][-1] close2 = sd['close'][-2] low1 = sd['low'][-1] low2 = sd['low'][-2] high1 = sd['high'][-1] high2 = sd['high'][-2] avg_30d = sd['close_30_sma'][-1] avg_4w = sd['close_20_sma'][-1] avg_10w = sd['close_50_sma'][-1] avg_30w = sd['close_150_sma'][-1] high_52w = sd['high'].tail(250).max() lbb1 = sd['boll_lb'][-1] lbb2 = sd['boll_lb'][-2] ubb1 = sd['boll_ub'][-1] ubb2 = sd['boll_ub'][-2] # Find all GLTs (ATH not broken for at least another 90 days) last_ath = 0.0 ath = Series() for day, day_high in sd['high'].iteritems(): last_ath = max(last_ath, day_high) ath.set_value(day, last_ath) ath_days = sd[sd['high'] == ath]['high'] glt = Series() for i, (day, high) in enumerate(ath_days.iteritems()): next_day = ath_days.keys()[i + 1] if i < len(ath_days) - 1 else Timestamp( str(date.today())) if next_day - day >= Timedelta('90 days'): glt.set_value(day, high) uptrend["c>30d_avg"] = close1 > avg_30d uptrend["c>10w_avg"] = close1 > avg_10w uptrend["c>30w_avg"] = close1 > avg_30w uptrend["4w>10w>30w"] = avg_4w > avg_10w > avg_30w # uptrend["w_rwb"] = uptrend["last_glt_date"] = glt.keys()[-1].to_datetime().date( ) if len(glt) > 0 else None uptrend["last_glt_high"] = glt[-1] if len(glt) > 0 else None uptrend["above_last_glt"] = len(glt) > 0 and close1 > glt[-1] uptrend["macd_hist_rising"] = sd['macdh'][-1] > sd['macdh_4_sma'][-1] uptrend["stoch_fast>slow"] = sd['rsv_10_4_sma'][-1] > sd[ 'rsv_10_4_sma_4_sma'][-1] # uptrend["bb_up_expansion_l2"] # uptrend["rs>30d_avg"] = (Need Investors.com data) # uptrend["rs_rising"] = (Need Investors.com data) uptrend["52w_high_l2"] = high_52w == high1 or high_52w == high2 uptrend["ath_l2"] = ath[-1] == high1 or ath[-2] == high2 uptrend["1y_doubled"] = close1 >= 2 * sd['close'][-255:-245].mean() # uptrend["bounce_30d_l2"] = # uptrend["bounce_10w_l2"] = # uptrend["bounce_30w_l2"] = uptrend["stoch<50"] = sd['rsv_10_4_sma'][-1] < 50 uptrend["<bb_lower_l2"] = low1 < lbb1 or low2 < lbb2 uptrend[ "above_avg_volume"] = sd['volume'][-1] > 1.5 * sd['volume_50_sma'][-1] downtrend["c<30d_avg"] = close1 < avg_30d downtrend["c<10w_avg"] = close1 < avg_10w downtrend["c<30w_avg"] = close1 < avg_30w downtrend["4w<10w<30w"] = avg_4w < avg_10w < avg_30w # downtrend["w_bwr"] = downtrend["macd_hist_falling"] = sd['macdh'][-1] < sd['macdh_4_sma'][-1] downtrend["stoch_fast<slow"] = sd['rsv_10_4_sma'][-1] < sd[ 'rsv_10_4_sma_4_sma'][-1] # downtrend["bb_down_expansion_l2"] # downtrend["bounce_30d_l2"] = # downtrend["bounce_10w_l2"] = # downtrend["bounce_30w_l2"] = downtrend["stoch>50"] = sd['rsv_10_4_sma'][-1] > 50 downtrend[">bb_upper_l2"] = high1 > ubb1 or high2 > ubb2 return stock
import json from elasticsearch import Elasticsearch import time from datetime import datetime, tzinfo import pytz import numpy as np date_now = int(time.time()) date_passed_72_hours = int(time.time()) - 72*60*60 es = Elasticsearch() yahoo = Share('AMZN') # res = es.search(index='stocks',doc_type='Amazon', body={ "size": 0, "aggs": { "count_by_type": { "terms": { "field": '_type'}}}}) res = es.search(index='stocks',doc_type='Amazon', body={ "size": 0, "aggs": { "avg_grade": { "avg": { "field": 'scoring'}}}}) avg_score_all_data = res["aggregations"]["avg_grade"]["value"] stock_year_high = float(yahoo.get_year_high()) stock_year_low = float(yahoo.get_year_low()) # res = es.search(index='stocks',doc_type='Amazon', body={ "size": 0, "aggs": { "min_time": { "min": { "field": 'created_at'}}}}) # min_timestamp = res["aggregations"]["min_time"]["value"] # res = es.search(index='stocks',doc_type='Amazon', body={ "size": 0, "aggs": { "max_time": { "max": { "field": 'created_at'}}}}) # max_timestamp = res["aggregations"]["max_time"]["value"] dataset = np.genfromtxt("../data/quote_data.csv", dtype=None, delimiter=',') original_quote = dataset[0][1] for data in dataset: tmp_timestamp = data[0] # convert from edt to utcd pytz_eastern = pytz.timezone("America/New_York") edt_dt = datetime.fromtimestamp(tmp_timestamp).replace(tzinfo=pytz_eastern) tzinfo=pytz.UTC utc_dt = edt_dt.astimezone(tzinfo).strftime("%Y-%m-%d %H:%M:%S")