def market_cap(self): mid_cap, large_cap = 2000000000, 10000000000 for i in range(len(self.list_of_tick)): try: ticker = self.list_of_tick[i][0] info_stock = Share(ticker) illions_of_stock = info_stock.get_market_cap()[-1] mktcap_val = float(info_stock.get_market_cap()[:-1]) if isinstance(mktcap_val, float) == True: ttl_mktcap_val = self.mktcap_cnvrs(illions_of_stock, mktcap_val) if ttl_mktcap_val > large_cap: self.db_validate("Large-Market Cap", ticker, "MarketCap") elif ttl_mktcap_val > mid_cap: self.db_validate("Mid-Market Cap", ticker, "MarketCap") else: self.db_validate("Small-Market Cap", ticker, "MarketCap") except yahoo_errors: pass
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 )
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 metricsForSector(self, Sector, screenParam=['avgVolume'], screenParamRange=(float("-inf"), float("inf"))): outputData = [] for stock in self.bySector[Sector]: try: working = stock sData = Share(stock[0]) screenQ = (type(screenParam) == list) if 'avgVolume' in screenParam: avgVolume = sData.get_avg_daily_volume() if (screenParamRange[0] <= float(avgVolume) <= screenParamRange[1]) or screenQ: working.append(avgVolume) else: working = None if 'mrkCap' in screenParam: mrkCap = sData.get_market_cap() if mrkCap[-1] == 'B': amrkCap = float(mrkCap[:-1]) * 1000000000 if mrkCap[-1] == 'M': amrkCap = float(mrkCap[:-1]) * 1000000 if (screenParamRange[0] <= amrkCap <= screenParamRange[1]) or screenQ: working.append(amrkCap) else: working = None outputData.append(working) except: pass return outputData
def get_stock_info(stock_symbol): _stock_info = dict() stock = Share(stock_symbol) _stock_info['price'] = stock.get_price() _stock_info['market_cap'] = stock.get_market_cap() if _stock_info['market_cap'] is not None: _stock_info['market_cap'] = _stock_info['market_cap'].replace("B", "") _stock_info['price_earnings'] = stock.get_price_earnings_ratio() return _stock_info
def get_quote(symbol): share = Share(symbol) return { 'open': share.get_open(), 'price': share.get_price(), 'change': share.get_change(), 'market_cap': share.get_market_cap(), 'pe': share.get_price_earnings_ratio() or '-' }
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 andrews_algo(): """ Various metrics for a given ticker :param tickers: :return: """ global ticker_list for ticker in ticker_list: stock = Share(ticker) print(line_separator) print(stock.get_name()) print("Current Price: " + str(stock.get_price())) # Dollar volume == momentum dollar_volume = float(stock.get_price()) * float(stock.get_volume()) if dollar_volume > 20000000.0: print("High Trading Liquidity, dollar volume: " + num_to_short_text(dollar_volume)) else: print("Low Trading Liquidity, dollar volume: " + num_to_short_text(dollar_volume)) # PEG is apparently inaccurate need to implement checks/also check conditional logic peg = float(stock.get_price_earnings_growth_ratio()) if peg > 1.5: print("Undervalued, Large Growth Potential, PEG ratio: " + str(peg)) elif peg < 1: print("Overvalued, High Risk Potential, PEG ratio: " + str(peg)) else: print("Fairly Priced, Low Growth Potential, PEG ratio: " + str(peg)) # TODO: ROE (increasing ROE signals regular profit generation) # TODO: Beta value to determine volatility # TODO: Actual EPS vs next quarter estimated EPS (to predict imminent stock jump or crash) # TODO: Formula to calculate future theoretical earnings # Converting textual numbers to floats market_cap = short_text_to_float(stock.get_market_cap()) if market_cap > 200000000000.0: print("Mega Cap") elif market_cap > 10000000000.0: print("Large Cap") elif market_cap > 2000000000.0: print("Mid Cap") elif market_cap > 300000000.0: print("Small Cap") elif market_cap > 50000000.0: print("Micro Cap") else: print("Nano Cap") print("Market Capitalization: " + num_to_short_text(market_cap)) print(line_separator)
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
def render_comment(tickers): for ticker in sorted(tickers): stk = Share(ticker) now = datetime.now() print '''### %s\n =======\n * Price: %s * Market Cap: %s\n ######*as of %s via [Openfolio](http://www.openfolio.com)* ''' % (ticker.upper(), stk.get_price(), stk.get_market_cap(), now.strftime('%Y/%m/%d %H:%M:%S'))
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 get_one_stock(thread_id, tickers, good): for ticker in tickers: try: stock = Share(ticker['symbol']) a = stock.get_open() #print(thread_id, ":", ticker['symbol'], a, dir(stock)) cap = stock.get_market_cap() if 'B' in cap: print(ticker['symbol'], cap) good.append(ticker['symbol']) except Exception as e: pass
def get_one_stock(thread_id, tickers, good): for ticker in tickers: try: stock = Share(ticker['symbol']) a = stock.get_open() #print(thread_id, ":", ticker['symbol'], a, dir(stock)) cap = stock.get_market_cap() if 'B' in cap: print(ticker['symbol'], cap) good.append(ticker['symbol']) except Exception as e: pass
def test_filter_stocks(self): start, end = get_time_period() tickers = self.get_fifty_random_tickers() tested = 0 for ticker in tickers: if tested >= 10: break try: s = Share(ticker) data = s.get_historical(end, start) except: continue tested += 1 if len(data) < MIN_DATA_LEN or data[0]['Date'] == last_trading_day: continue if not data: self.assertTrue(filter_stocks(s, data)) elif data[0]['Close'] < 1: self.assertTrue(filter_stocks(s, data)) elif not s.get_market_cap(): self.assertTrue(filter_stocks(s, data)) elif _parse_market_cap_string(s.get_market_cap()) < float( getenv('MARKET_CAP_MIN', FILTER_DEFAULTS['MARKET_CAP_MIN'])): self.assertTrue(filter_stocks(s, data)) elif not s.get_price_earnings_ratio(): self.assertTrue(filter_stocks(s, data)) elif float(s.get_price_earnings_ratio()) >= float(getenv('PE_MAX', FILTER_DEFAULTS['PE_MAX'])) or \ float(s.get_price_earnings_ratio()) <= float(getenv('PE_MIN', FILTER_DEFAULTS['PE_MIN'])): self.assertTrue(filter_stocks(s, data)) elif not s.get_avg_daily_volume() or float( s.get_avg_daily_volume()) >= float( getenv('VOLUME_MIN', FILTER_DEFAULTS['VOLUME_MIN'])): self.assertTrue(filter_stocks(s, data)) elif (float(s.get_year_high()) * .99) <= float(data[0]['High']): self.assertTrue(filter_stocks(s, data)) else: self.assertFalse(filter_stocks(s, 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 quote(request): stockSymbol = request.GET['stock'] stock = Share(stockSymbol) form = StockQuoteForm() context = { "form": form, "stock": stockSymbol, "price": stock.get_price(), "change": stock.get_change(), "volume": stock.get_volume(), "cap": stock.get_market_cap() } template = "quote.html" return render(request, template, context)
def GetInfo(company): companyinfo = {} dictIS = IncomeStatement(company) dictBS = BalanceSheet(company) dictKR = KeyRatios(company) dictionaries = [dictIS, dictBS, dictKR] companyinfo['EXR'] = ExchangeRate(dictIS['currency']) # price and market capitalization share = Share(company) companyinfo['quote'] = share.get_price() companyinfo['MC'] = float(share.get_market_cap()[:-1]) companyinfo['name'] = share.get_name() for dictionary in dictionaries: # merge dictionaries companyinfo.update(dictionary)
def get_company_info(ticker): try: s = Share(ticker) data = { 'Market_cap': s.get_market_cap(), 'Average_volume': s.get_avg_daily_volume(), 'EPS': s.get_earnings_share(), 'Short_ratio': s.get_short_ratio(), 'PE': s.get_price_earnings_ratio(), 'PEG': s.get_price_earnings_growth_ratio(), } return DataFetcher._extract_company_info(data) except YQLQueryError: logger.error("Company info not found for {}".format(ticker)) except Exception as e: logger.error("Unexpected error occured: {}".format(e)) return {}
def get_company_info(ticker): try: s = Share(ticker) data = { 'Market_cap': s.get_market_cap(), 'Average_volume': s.get_avg_daily_volume(), 'EPS': s.get_earnings_share(), 'Short_ratio': s.get_short_ratio(), 'PE': s.get_price_earnings_ratio(), 'PEG': s.get_price_earnings_growth_ratio(), } return DataFetcher._extract_company_info(data) except YQLQueryError: logger.error("Company info not found for {}".format(ticker)) except Exception as e: logger.error("Unexpected error occured: {}".format(e)) return {}
def get_one_stock(thread_id, tickers, good, big, small): for ticker in tickers: try: stock = Share(ticker['symbol']) print(thread_id, ":", ticker['symbol']) cap = stock.get_market_cap() if 'B' in cap: position = cap.find('B') big.append(float(cap[:position]) *1000000000.0) print(ticker['symbol'], cap) good.append(ticker['symbol']) if 'M' in cap: position = cap.find('M') small.append(float(cap[:position]) *1000000.0) print(ticker['symbol'], cap) except Exception as e: pass
def generate_comment(tickers): """ Generate text for a comment given the ticker names """ strings = [] for ticker in sorted(tickers): stk = Share(ticker) now = datetime.now() strings.append(''' ### {} ======= * Price: {} * Market Cap: {} ######*as of {} via [Openfolio](http://www.openfolio.com)* '''.format(ticker.upper(), stk.get_price(), stk.get_market_cap(), now.strftime('%Y/%m/%d %H:%M:%S'))) return "\n".join(strings)
def get_share_price(stock_symbol): try: stock_symbol = stock_symbol.lower() stock = Share(stock_symbol) opening_price = stock.get_open() cur_price = stock.get_price() pe_ratio = stock.get_price_earnings_ratio() market_cap = stock.get_market_cap() result = [ stock_symbol, str(cur_price), str(opening_price), str(pe_ratio), str(market_cap) ] except: result = "1" return result
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)
def bot_action(c, symbol): stock = Share(symbol) # Link stock with yahoo_finance module print(stock) if stock.get_price() == None: main() #print(stock.get_price()) head = 'Up to date stock info for **${0}** ({1}):\n\n'.format(symbol.upper(), stock.get_name()) price = '**Price:** ${0:.2f}\n\n'.format(float(stock.get_price())) price_open = '**Open:** ${0:.2f}\n\n'.format(float(stock.get_open())) change = '**Change:** {0:.2f} ({1})\n\n'.format(float(stock.get_change()), stock.get_percent_change()) vol = '**Volume:** {0:,.2f}\n\n'.format(float(stock.get_volume())) market_cap = '**Mkt Cap:** {0}\n\n'.format(stock.get_market_cap()) average = '**Average (50 day):** {0:.2f}\n\n'.format(float(stock.get_50day_moving_avg())) exchange = '**Exchange:** {0}\n\n'.format(stock.get_stock_exchange()) divider = '-----------------------------------------------------------------------------------------\n\n' tail = "Don't abuse me, robots have feelings too! | [Source Code](https://github.com/Logicmn/Reddit-Stock-Bot) " \ "| [Report Bug](https://www.reddit.com/message/compose/?to=Pick-a-Stock) " \ "| [Suggest Feature](https://www.reddit.com/message/compose/?to=Pick-a-Stock)" c.reply(head + divider + price + price_open + change + vol + market_cap + average + exchange+ divider + tail)
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
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
def getStockInfo(): messageBody = request.values.get('Body') try: """Splitting the text input into action and ticker""" actionMessage = messageBody.split(" ")[0] stockTicker = messageBody.split(" ")[1].upper() """Using the Yahoo api to respond to user requests""" stock = Share(stockTicker) if actionMessage.upper() == "QUOTE": message = "Last Trading Price: " + stock.get_price() elif actionMessage.upper() == "VOLUME": message = "Last Trading VOLUME: " + stock.get_volume() elif actionMessage.upper() == "MCAP": message = "MarketCap: " + stock.get_market_cap() elif actionMessage.upper() == "EBITDA": message = "EBITDA: " + stock.get_ebitda() except: message = "Wrong input, please try again" resp = twilio.twiml.Response() resp.sms(message) return str(resp)
def solar_value(myString): print(myString) Ticker = input("What's the ticker symbol of solar company?") stock_ticker = Share(Ticker) print("Now lets figure out how valuable this company is") print("Market Capital is: ") market_cap = (stock_ticker.get_market_cap()) print(market_cap) market_cap_num = str(market_cap[:-1]) #print(market_cap_num) stock_price = stock_ticker.get_price() share_count = (float(market_cap_num) / float(stock_price)) print("~Share Count is: ") print(share_count) solar_output = input("How much gigiwatt does " + Ticker + " output per year?") solar_output_num = float(solar_output) print(solar_output_num) value = (float(market_cap_num) / float(solar_output_num)) print("The value of this solar company as an investment is: ") print("%.4f" % value) print("1.0 being strong buy and .01 being strong sell") print("-For Billion market capital companies, move decimal over 3 places")
def getStockInfo(): messageBody = request.values.get('Body') try: """Splitting the text input into action and ticker""" actionMessage = messageBody.split(" ")[0] stockTicker = messageBody.split(" ")[1].upper() """Using the Yahoo api to respond to user requests""" stock = Share(stockTicker) if actionMessage.upper() == "QUOTE": message = "Last Trading Price: "+ stock.get_price() elif actionMessage.upper() == "VOLUME": message = "Last Trading VOLUME: "+ stock.get_volume() elif actionMessage.upper() == "MCAP": message = "MarketCap: "+ stock.get_market_cap() elif actionMessage.upper() == "EBITDA": message = "EBITDA: "+ stock.get_ebitda() except: message = "Wrong input, please try again" resp = twilio.twiml.Response() resp.sms(message) return str(resp)
def main(): # this adds commas to all numbers greater than one thousand locale.setlocale(locale.LC_ALL, 'en_US') # if statement that checks for args. error/help message will appear if no args if (len(sys.argv) == 1): print "\nPlease supply one or more tickers. Example: python stephan_s_stock_quote.py GOOG\n" else: for counter in range(1, len(sys.argv)): # this is where we fetch our stocks from y = Share(sys.argv[counter]) # this is the output along with a message regarding the CSV file print "\nSymbol: " + str(sys.argv[counter]) print "Company Name: " + str(y.get_name()) print "Market Capitalization: $" + str(y.get_market_cap()) print "Earnings Per Share: $" + str( locale.format( "%d", float(y.get_earnings_share()), grouping=True)) print "P/E Ratio: " + str(y.get_price_earnings_ratio()) print "Average Volume: " + str( locale.format( "%d", float(y.get_avg_daily_volume()), grouping=True)) print "Today's Volume: " + str( locale.format("%d", float(y.get_volume()), grouping=True)) print "Today's Closing Price: $" + str(y.get_price()) print "Percent Change: " + str(y.get_percent_change()) + "\n" print "A CSV file of your selected stock tickers has been downloaded to your computer under the name 'stocks.csv'. " + "\n" print "The CSV file will be downloaded to the same folder that this program was stored in." + "\n"
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)
from Auto_Investment import PreProcess yahoo = Share('YGE') try : temp = Share('BW@') except ConnectionError: print('Sleep') time.sleep(10) except AttributeError: print('No value') pass # print (Pre_Process.str2float(Share('BW@').get_market_cap())) print(yahoo.get_open()) print (yahoo.get_year_high()) t = float("45.3") print (t) M = yahoo.get_market_cap() if M == None: print (yahoo.get_market_cap()) print (yahoo.get_info()) # ya = yahoo.get_historical('2000-04-25', '2014-04-29') # n = ya.__len__() # print(n) # fig = plt.figure() # # axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1) # # x = np.linspace(0, 5, 10) # y = x ** 2 # axes.plot(x, y, color="green", lw=2, ls='*', marker='+') #
class Symbol(object): def __init__(self, symbol, s_date=None, e_date=None): self.log=Logging() self.name=symbol self.created=datetime.datetime.utcnow() self.log.info("created {}".format(self.name)) try: self.share=Share(symbol) except: self.log.error("platform is offline or not connecting") if s_date and e_date: self.begin=s_date self.end=e_date try: self.share=Share(symbol) self.data=self.share.get_historical(self.begin, self.end) self.log.refresh("{} data collected".format(self.name)) except: self.log.error("platform is offline or not connecting") def refresh_data(self, s_date=None, e_date=None): if s_date and e_date: try: share=Share(self.name) self.begin=s_date self.end=e_date share.get_historical(s_date, e_date) self.log.refresh("{} data collected".format(self.name)) except: self.log.error("platform is offline or not connecting") def market_cap(self): try: self.market_cap = self.share.get_market_cap() self.log.info("{} market cap refreshed".format(self.name)) except: self.log.error("platform is offline or not connecting") def earnings_per_share(self): try: self.eps = self.share.get_earnings_share() self.log.info("{} eps refreshed".format(self.name)) except: self.log.error("platform is offline or not connecting") def moving_average_50(self): try: self.moving_average_50 = self.share.get_50day_moving_average() self.log.info("{} 50 day moving ave refreshed".format(self.name)) except: self.log.error("platform is offline or not connecting") #implement TODO def nday_moving_average(self, n): try: self.moving_average_n = None self.log.info("{} {} day moving ave refreshed".format(self.name, n)) except: self.log.error("platform is offline or not connecting") def price_earnings_ratio(self): try: self.price_to_earnings = self.share.get_price_earnings_ratio() self.log.info("{} price to earnings refreshed".format(self.name)) except: self.log.error("platform is offline or not connecting") def book_value(self): try: self.book = self.share.get_price_book() self.log.info("{} book value refreshed".format(self.name)) except: self.log.error("platform is offline or not connecting") def year_high(self): try: self.year_high = self.share.get_change_from_year_high() self.log.info("{} year high change refreshed".format(self.name)) except: self.log.error("platform is offline or not connecting") def year_low(self): try: self.year_low = self.share.get_change_from_year_low() self.log.info("{} year low change refreshed".format(self.name)) except: self.log.error("platform is offline or not connecting") def target_price(self): try: self.year_target = self.share.get_change_from_year_high() self.log.info("{} year target change refreshed".format(self.name)) except: self.log.error("platform is offline or not connecting") def year_range(self): try: self.year_range = self.share.get_change_from_year_high() self.log.info("{} year range change refreshed".format(self.name)) except: self.log.error("platform is offline or not connecting")
pe = stock.get_price_earnings_ratio() print pe if myargs.exchange is True: exchange = stock.get_stock_exchange() if myargs.ma50 is True: ma50 = stock.get_50day_moving_avg() print ma50 if myargs.ma200 is True: ma200 = stock.get_200day_moving_avg() print ma200 if myargs.marketcap is True: marketcap = stock.get_market_cap() print marketcap if myargs.getopen is True: getopen = stock.get_open() print getopen if myargs.getbook is True: getbook = stock.get_book_value() print getbook if myargs.dividendshare is True: getdiv = stock.get_dividend_share() print getdiv if myargs.dividendyield is True:
class Market: __PULL_INTERVAL_IN_MIN = 5 def __init__(self, s): self.share_string = s self.share = Share(s) self.current_price = self.share.get_price() self.price = self.current_price self.market_cap = self.share.get_market_cap() self.open_price = self.share.get_open() self.prev_close_price = self.share.get_prev_close() self.percent_change = self.share.get_percent_change() self.price_array = [] self.time_array = [] def pullPrices(self): file_string = "share_" + self.share_string + ".dat" dataFile = open(file_string, "w+") start_time = int(time.strftime("%-S")) last_time = start_time while (1 == 1): current_time = int(time.strftime("%-S")) if (current_time >= 60): current_time = 0 if (current_time - last_time < 0): last_time = -60 - (current_time - last_time) if (int(time.strftime("%-S")) - last_time >= self.__PULL_INTERVAL_IN_MIN): dataFile.write(time.strftime('%l:%M%p, %b %d, %Y') + "\t") dataFile.write(self.share.get_price()) dataFile.write("\n") dataFile.flush() last_time = int(time.strftime("%-S")) def __storeData(self, filename): dataFile = open(filename, "r") lineList = dataFile.readLines() for i in range(len(lineList)): index1 = lineList[i].index('\t') price = float(lineList[i][index1:]) price_array.append(price) dataFile.close() def getSlope(self, filename): __storeData(filename) length = len(self.price_array) current_slope = ( self.price_array[length] - self.price_array[length - 1]) / ( self.time_array[length] - self.time_array[length - 1]) return current_slope def getSecondDegreeSlope(self, filename): __storeData(filename) length = len(price_array) current_slope = ( self.price_array[length] - self.price_array[length - 1]) / ( self.time_array[length] - self.time_array[length - 1]) last_slope = ( self.price_array[length - 1] - self.price_array[length - 2]) / ( self.time_array[length - 1] - self.time_array[length - 2]) current_secondDegreeSlope = (current_slope - last_slope) / ( self.time_array[length] - self.time_array[length - 1]) return current_secondDegreeSlope
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 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
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
class Market: __PULL_INTERVAL_IN_MIN = 5 def __init__ (self, s): self.share_string = s self.share = Share(s) self.current_price = self.share.get_price() self.price = self.current_price self.market_cap = self.share.get_market_cap() self.open_price = self.share.get_open() self.prev_close_price = self.share.get_prev_close() self.percent_change = self.share.get_percent_change() self.price_array = [] self.time_array = [] def pullPrices(self): file_string = "share_" + self.share_string + ".dat" dataFile = open(file_string, "w+") start_time = int(time.strftime("%-S")) last_time = start_time while (1 == 1): current_time = int(time.strftime("%-S")) if (current_time >= 60): current_time = 0 if (current_time - last_time < 0): last_time = -60 - (current_time - last_time) if (int(time.strftime("%-S")) - last_time >= self.__PULL_INTERVAL_IN_MIN): dataFile.write (time.strftime('%l:%M%p, %b %d, %Y') + "\t") dataFile.write (self.share.get_price()) dataFile.write ("\n") dataFile.flush () last_time = int(time.strftime("%-S")) def __storeData(self, filename): dataFile = open(filename, "r") lineList = dataFile.readLines() for i in range(len(lineList)): index1 = lineList[i].index('\t') price = float(lineList[i][index1:]) price_array.append(price) dataFile.close() def getSlope(self, filename): __storeData(filename) length = len(self.price_array) current_slope = (self.price_array[length] - self.price_array[length-1])/(self.time_array[length] - self.time_array[length-1]) return current_slope def getSecondDegreeSlope(self, filename): __storeData(filename) length = len(price_array) current_slope = (self.price_array[length] - self.price_array[length-1])/(self.time_array[length] - self.time_array[length-1]) last_slope = (self.price_array[length-1] - self.price_array[length-2])/(self.time_array[length-1] - self.time_array[length-2]) current_secondDegreeSlope = (current_slope - last_slope)/(self.time_array[length] - self.time_array[length-1]) return current_secondDegreeSlope
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() # print share.get_price_book()
companyinfo['currency'] = re.findall( '.*\. (\S{3}) in millions except per share data', dataIS)[0] #get what currency the data is in if companyinfo['currency'] == 'USD': companyinfo['EXR'] = 1 else: dataEXR = urllib.urlopen(urlEXR).read() jsonEXR = json.loads(dataEXR) rates = jsonEXR.get('rates', None) companyinfo['EXR'] = rates.get(companyinfo['currency'], None) #get the exchange rate #price and market capitalization share = Share(company) companyinfo['quote'] = share.get_price() companyinfo['MC'] = float(share.get_market_cap()[:-1]) companyinfo['name'] = share.get_name() #write to DMF excel # if number==1:wb=openpyxl.load_workbook('blankDMF.xlsx') # else: wb=openpyxl.load_workbook(month+' '+year+'.xlsx') # ws=wb.get_sheet_by_name('sheet1') ws['B' + str(number * 3 + 1)] = companyinfo['name'] ws['C' + str(number * 3 + 1)] = company ws['F' + str(number * 3 + 1)] = companyinfo['EXR'] ws['G' + str(number * 3 + 1)] = companyinfo['quote'] ws['H' + str(number * 3 + 1)] = companyinfo['MC'] ws['I' + str(number * 3 + 1)] = companyinfo['eps1'] ws['I' + str(number * 3 + 2)] = companyinfo['eps2'] ws['I' + str(number * 3 + 3)] = companyinfo['eps3'] ws['J' + str(number * 3 + 1)] = companyinfo['revenue']
except: pass try: russell3000.set_value(s,'Volume',shy.get_volume()) except: pass try: russell3000.set_value(s,'Open',shy.get_open()) except: pass try: russell3000.set_value(s,'Average daily volume',shy.get_avg_daily_volume()) except: pass try: russell3000.set_value(s,'Market cap',shy.get_market_cap()) except: pass try: russell3000.set_value(s,'Book value',shy.get_book_value()) except: pass try: russell3000.set_value(s,'Ebitda',shy.get_ebitda()) except: pass try: russell3000.set_value(s,'Dividend share',shy.get_dividend_share()) except: pass #try:
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
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")
def YaOrg(gather=[ 'debtToEquity', 'Trailing P/E', 'Price/Sales', 'priceToBook', 'profitMargins', 'operatingMargins', 'returnOnAssets', 'returnOnEquity', 'revenuePerShare', 'Market Cap', 'enterpriseValue', 'forwardPE', 'pegRatio', 'enterpriseToRevenue', 'enterpriseToEbitda', 'totalRevenue', 'grossProfit', 'ebitda', 'netIncomeToCommon', 'trailingEps', 'earningsGrowth', 'revenueGrowth', 'totalCash', 'totalCashPerShare', 'totalDebt', 'currentRatio', 'bookValue', 'operatingCashflow', 'beta', 'heldPercentInsiders', 'heldPercentInstitutions', 'sharesShort', 'shortRatio', 'shortPercentOfFloat', 'sharesShortPriorMonth', 'currentPrice', 'sharesOutstanding' ]): df = pd.DataFrame(columns=[ 'Date', 'Unix', 'Ticker', 'Price', 'stock_p_change', 'SP500', 'sp500_p_change', 'Difference', 'DE Ratio', 'Trailing P/E', 'Price/Sales', 'Price/Book', 'Profit Margin', 'Operating Margin', 'Return on Assets', 'Return on Equity', 'Revenue Per Share', 'Market Cap', 'Enterprise Value', 'Forward P/E', 'PEG Ratio', 'Enterprise Value/Revenue', 'Enterprise Value/EBITDA', 'Revenue', 'Gross Profit', 'EBITDA', 'Net Income Avl to Common ', 'Diluted EPS', 'Earnings Growth', 'Revenue Growth', 'Total Cash', 'Total Cash Per Share', 'Total Debt', 'Current Ratio', 'Book Value Per Share', 'Cash Flow', 'Beta', 'Held by Insiders', 'Held by Institutions', 'Shares Short (as of', 'Short Ratio', 'Short % of Float', 'Shares Short (prior ', 'Status' ]) #time.sleep(2) file_list = os.listdir("YaParse") counter = 0 passfiles = 0 for each_file in file_list: ticker = each_file.split(".json")[0] full_file_path = "YaParse/" + each_file source = open(full_file_path, "r").read() data = Share(ticker.upper()) counter += 1 print("File No: " + str(counter)) try: value_list = [] for each_data in gather: try: #value = float(source.split(gather + ':</td><td class="yfnc_tabledata1">')[1].split('</td>')[0]) regex = re.escape( each_data) + r'.*?(\d{1,8}\.\d{1,8}M?B?K?|N/A)%?' value = re.search(regex, source) value = (value.group(1)) if "B" in value: value = float(value.replace("B", '')) * 1000000000 elif "M" in value: value = float(value.replace("M", '')) * 1000000 value_list.append(value) except Exception as e: if not (each_data == 'Trailing P/E' or each_data == 'Price/Sales' or each_data == 'Market Cap'): print("Exception1: " + str(e)) print("Data: " + str(each_data) + " File: " + str(each_file)) #time.sleep(5) value = "N/A" if each_data == 'Price/Sales': value = data.get_price_sales() if each_data == 'Market Cap': value = data.get_market_cap() if each_data == 'Trailing P/E': value = data.get_price_earnings_ratio() try: if "B" in value: value = float(value.replace("B", '')) * 1000000000 elif "M" in value: value = float(value.replace("M", '')) * 1000000 except Exception as e: value = "N/A" value_list.append(value) #print(value_list) #time.sleep(5) if value_list.count("N/A") > 0: print("Passing on this file: " + str(each_file) + " ::::Count of N/A: " + str(value_list.count("N/A"))) passfiles += 1 pass else: try: df = df.append( { 'Date': "N/A", 'Unix': "N/A", 'Ticker': ticker, 'Price': "N/A", 'stock_p_change': "N/A", 'SP500': "N/A", 'sp500_p_change': "N/A", 'Difference': "N/A", 'DE Ratio': value_list[0], 'Trailing P/E': value_list[1], 'Price/Sales': value_list[2], 'Price/Book': value_list[3], 'Profit Margin': value_list[4], 'Operating Margin': value_list[5], 'Return on Assets': value_list[6], 'Return on Equity': value_list[7], 'Revenue Per Share': value_list[8], 'Market Cap': value_list[9], 'Enterprise Value': value_list[10], 'Forward P/E': value_list[11], 'PEG Ratio': value_list[12], 'Enterprise Value/Revenue': value_list[13], 'Enterprise Value/EBITDA': value_list[14], 'Revenue': value_list[15], 'Gross Profit': value_list[16], 'EBITDA': value_list[17], 'Net Income Avl to Common ': value_list[18], 'Diluted EPS': value_list[19], 'Earnings Growth': value_list[20], 'Revenue Growth': value_list[21], 'Total Cash': value_list[22], 'Total Cash Per Share': value_list[23], 'Total Debt': value_list[24], 'Current Ratio': value_list[25], 'Book Value Per Share': value_list[26], 'Cash Flow': value_list[27], 'Beta': value_list[28], 'Held by Insiders': value_list[29], 'Held by Institutions': value_list[30], 'Shares Short (as of': value_list[31], 'Short Ratio': value_list[32], 'Short % of Float': value_list[33], 'Shares Short (prior ': value_list[34], 'Current Price': value_list[35], 'Shares Outstanding': value_list[36], 'Status': "N/A" }, ignore_index=True) except Exception as e: print("Problem in DF Append: " + str(e)) print("Data: " + str(each_data) + "File: " + str(each_file)) print( 'Error on line {}'.format( sys.exc_info()[-1].tb_lineno), type(e).__name__, e) time.sleep(5) #print("DataFrame: ", df) except Exception as e: print("Problem as a whole: " + str(e)) print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e) pass df.to_csv('YaParse_sample_NO_NA.csv') print("Done making csv") print("No. of files passed: " + str(passfiles))
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