def recentdata(companyname): try: companydata = Share(companyname) print "This morning, it opened for $" + companydata.get_open() + ", and right now is at $" + companydata.get_price() + "." if companydata.get_open() > companydata.get_price(): difference = float(companydata.get_open()) - float(companydata.get_price()) if len(str(difference)) < 3: print "Since this morning, the price has fallen by $" + str(difference) + "0" else: print "Since this morning, the price has fallen by $" + str(difference) elif companydata.get_open() < companydata.get_price(): difference = float(companydata.get_price()) - float(companydata.get_open()) if len(str(difference)) < 3: print "Since this morning, the price has risen by $" + str(difference) + "0" else: print "Since this morning, the price has risen by $" + str(difference) print "" selection = raw_input( "Would you like some info about what the stock has been like in the past few days? Yes/No: ") if str.lower(selection) == "no": end() elif str.lower(selection) == "yes": print "Okay, please wait a moment" except (RuntimeError, TypeError, NameError): print "Whoops, something went wrong there. Are you sure you entered a valid company abbreviation?" finally: longterm(companyname)
def SelectStock(self): wb = Workbook() ws = wb.active with open('export.csv',newline='') as f: reader = csv.reader(f) index = 2 title = ["代號","名稱","股價","本益比","EPS"] for x in range(0,5,1): ws.cell(row=1,column=x+1,value=title[x]) for row in reader: if row!=[]: try: if int(row[0]) < 10000: # print(row[2]) if "-" not in (row[2]) and float(row[2]) < 20: # print(row) Query = Share(row[0]+'.TW') #print(float(Query.get_earnings_share())) #print(float(Query.get_open())) #print("******************") if float(Query.get_open()) >= 20 and float(Query.get_open()) <= 90 and float(Query.get_earnings_share())>1.2: print(row) ws.cell(row=index , column=1 , value = row[0]) ws.cell(row=index , column=2 , value = row[1]) ws.cell(row=index , column=3 , value = Query.get_open()) ws.cell(row=index , column=4 , value = row[2]) ws.cell(row=index , column=5 , value = Query.get_earnings_share()) index = index + 1 except: pass wb.save("Final.xlsx")
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 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 refresh(): yahoo = Share('YHOO') yahoo.get_open() val = yahoo.get_price() yahoo.get_trade_datetime() #rndm = Random() #val = rndm.randint(0,4) x = np.linspace(0, 4 * np.pi, N) + val y = np.sin(x) + val source.data = dict(x=x, y=y)
def get_pead_quotes(date): '''date = datetime.date(2016,12,6)''' previous_businessDt = (date - BDay(1)).date() days90backDt = previous_businessDt - datetime.timedelta(days=90) asofDate = date.strftime("%Y%m%d") previousDt = previous_businessDt.strftime("%Y%m%d") interestingQuotes = marketData.getInterestingQuotes(asofDate, previousDt) pead_results = [] for interestingQuote in interestingQuotes: yahoo = Share(interestingQuote['symbol']) if yahoo.get_open() is None: continue quotes = yahoo.get_historical(str(days90backDt), str(previous_businessDt)) size = len(quotes) total = 0 for i in range(0, size - 1): total += abs( float(quotes[i]['Close']) - float(quotes[i + 1]['Open'])) avg = total / (size - 1) squared_deviations_total = 0 for i in range(0, size - 1): squared_deviations_total += math.pow( abs(float(quotes[i]["Close"]) - float(quotes[i + 1]["Open"])) - avg, 2) variance = squared_deviations_total / (size - 1) std_dv90days = math.sqrt(variance) previous_close = yahoo.get_prev_close() today_open = yahoo.get_open() todaysmoving = float(today_open) - float(previous_close) if (abs(todaysmoving) > std_dv90days): if (todaysmoving > 0): pead_results.append({ 'symbol': interestingQuote['symbol'], 'action': 'Long' }) #print(interestingQuote['symbol']+' Long '+str(todaysmoving)+' '+str(std_dv90days)) else: pead_results.append({ 'symbol': interestingQuote['symbol'], 'action': 'Short' }) #print(interestingQuote['symbol']+' Short '+str(todaysmoving)+' '+str(std_dv90days)) return pead_results
def strategy1(): print "strategy1" # the purpose of this strategy is to make sure the stock is progressing # upwords and has been gradually increasing. I don't want a stock that # isn't a somewhat straight line # potentials = set() potentials = [] f = open("todays-gainers.txt", "r") for line in f: name = line.replace('\n', '') # print name stock = Share(name) # print "open: "+stock.get_open() # print "high: "+stock.get_days_high() # print "low: "+stock.get_days_low() # print "curr: "+stock.get_price() if stock.get_open() is not None: oo = stock.get_open() hh = stock.get_days_high() cc = stock.get_price() if type(oo) is str and type(hh) is str and type(cc) is str: o = float(oo) h = float(hh) # l = float(stock.get_days_low()) c = float(cc) delta_open_cur = c - o delta_high_cur = abs(h - c) # delta_low_open = abs(l-o) if delta_open_cur != 0.0 and delta_high_cur != 0.0: difference_high = delta_high_cur / delta_open_cur * 100.0 else: difference_high = 0 # difference_low = delta_low_open/delta_open_cur*100.0 if difference_high < 35 and difference_high > -1: # print "LOOK AT THIS ONE" potentials.append(name) print name change = (1.0 - (o / c)) * 100.0 print change print "---------------" # print "DIFFERENCE: "+str(difference_high) # print "DIFFERENCE LOW: "+str(difference_low) # message = "Strategy 1:\n" # message += "These are potentials\n" # message += str(potentials) # sendMessage(message) # printPotentials(potentials) return potentials
def get_stock_info(symbols, moreInfo=False): """ Scrape stock info from Yahoo finance @Param 'moreInfo': False for getting price, True for getting more information @Return 'message': "symbol: Price-number, Open Price-number, Pre Close Price-number, High Price-number, Low price-number" """ message = '' for symbol in symbols: try: stock = Share(symbol) price = stock.get_price() except AttributeError: price = None if price == None: # Stock symbol not exists, replace with an alert message message += '#' + symbol + ': ' + 'The stock symbol does not exit' + '\n' elif moreInfo: message += '#%s: Price-%s, Open Price-%s, Pre Close Price-%s, High Price-%s, Low price-%s\n' \ % (symbol, price, stock.get_open(), stock.get_prev_close(), stock.get_days_high(), stock.get_days_low()) else: message += '#' + symbol + ': ' + price + '\n' alert_message = 'Please type #1 followed by stock symbols to get more information' if moreInfo == True else \ 'Please type #0 followed by stock symbols to get stock price' return message if message != '' else alert_message
def get_info_share(symbol): #print symbol #symbol = sys.argv[1] share1 = Share(symbol) try: share1.get_info() if not share1:# is None: print symbol," is not a valid share symbol. \nPlease re-run the program with correct share symbol" else: #print "here" print(datetime.datetime.now()) company = get_symbol(symbol) print company print share1.get_price() print share1.get_change() #print share1.get_short_ratio() open = share1.get_open() price = share1.get_price() percChange = float(Decimal(price) - Decimal(open))/float(Decimal(open)) print "%f" % percChange +"%" except Exception as e: print symbol," is not a valid share symbol. \nPlease re-run the program with correct share symbol" except AttributeError as ae: print "att error" except yahoo_finance.YQLQueryError as ye: print symbol," is not a valid share symbol in ye error. \nPlease re-run the program with correct share symbol"
def fundamentalStats(stock): try: stokOutput = Share(stock) openPrice = stokOutput.get_open() closePrice = stokOutput.get_prev_close() dailyDelta = stokOutput.get_change() earningsShare = stokOutput.get_earnings_share() fiddyDay = stokOutput.get_50day_moving_avg() priceBook = stokOutput.get_price_book() peeEee = stokOutput.get_price_earnings_ratio() pegRatio = stokOutput.get_price_earnings_growth_ratio() if (float(priceBook) < 1.5 and float(peeEee) < 50 and float(pegRatio) < 2 and float(peeEee) > 0): csvList = [stock, "open price:", openPrice, "previous close:", closePrice, "daily deltas:", dailyDelta, "earnings per share:", earningsShare, "50 day moving avg:", fiddyDay, "price/book:", priceBook, "price/earnings:", peeEee, "peg:", pegRatio, "\n"] print (stock, "will be imported to Excel.") stockPicks = open("picks.csv", "a", newline='') writeCSV = csv.writer(stockPicks, dialect='excel') for stock in csvList: writeCSV.writerow([stock]) else: print (stock, "does not meet criteria.") except: print(stock, "is missing a defined key statistic.")
def current_stock_results(self): symbol_f = self.symbol data = Share(symbol_f) share_value = (data.get_open()) return round( float((float(share_value) * float(self.shares)) - float(self.shares) * float(self.purchase_price)), 2)
def get_data(): filename = 'data/symbols.csv' data = [] with open(filename, 'r') as csvfile: reader = csv.reader(csvfile, delimiter=',') for row in reader: symbol = row[0] print ("Getting share for %s" % symbol) name = row[1] sector = row[2] share = Share(symbol) _open = share.get_open() if _open: data.append({ 'id' : symbol, 'symbol' : symbol, 'name' : name, 'sector' : sector, 'open' : _open }) return data
def updateInfos(): print("Updating Infos!") with open('static/sp100.json', 'rb') as f: ls = json.load(f) for i in ls: timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") print (i['name']) symbol = Share(i['name']) item = { 'name': i['name'], 'price': symbol.get_price(), 'time': timestamp, 'prev_close': symbol.get_prev_close(), 'open': symbol.get_open(), 'volume': symbol.get_volume(), 'pe': symbol.get_price_earnings_ratio(), 'eps': symbol.get_earnings_share(), 'price_sales': symbol.get_price_sales(), 'ebitda': symbol.get_ebitda(), 'hotness': ms.hotness_function(i['name']), 'BS': ms.bs_function(i['name'])} db.infos.update( {"name": i['name']}, { "$push": {"data": item} } ) print('Collection Infos Updated.') return Response('Collection Infos Updated.')
def current_stock_value(self): symbol_f = self.symbol data = Share(symbol_f) share_value = (data.get_open()) if share_value is not None: share_value = float(share_value) return (share_value) * float(self.shares)
def createInfos(): if db.infos.count() == 0: print("Creating Infos!!") with open('static/sp100.json', 'rb') as f: ls = json.load(f) for i in ls: timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") symbol = Share(i['name']) item = { 'name': i['name'], 'price': symbol.get_price(), 'time': timestamp, 'prev_close': symbol.get_prev_close(), 'open': symbol.get_open(), 'volume': symbol.get_volume(), 'pe': symbol.get_price_earnings_ratio(), 'eps': symbol.get_earnings_share(), 'price_sales': symbol.get_price_sales(), 'ebitda': symbol.get_ebitda(), 'hotness': ms.hotness_function(i['name']), 'BS': ms.bs_function(i['name'])} db.infos.insert_one({ "name": i['name'], "sector": i['sector'], "data": [item] }) print('Collection Infos Created.') return Response('Collection Infos Created.')
class ShareObj(object): def __init__(self, ID): self.id = ID self.share = Share(self.id) self.refresh def getPrice(self): return self.share.get_price() def getOpenPrice(self): return self.share.get_open() def getChange(self): if(self.share.get_percent_change() == None): return 0 else: percent = (self.share.get_percent_change()[:-1]) return float(percent) def getChangeFormatted(self): self.share.get_percent_change() def getID(self): return self.id def refresh(self): self.share.refresh() def getHistorical(self,date1, date2): return self.share.get_historical(date1,date2) def getCalculatedChange(self, open, close): return ((close - open)/open)*100
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 current_stock_value(self): symbol_f = self.symbol data = Share(symbol_f) share_value = (data.get_open()) if share_value: return float(share_value) * float(self.shares) else: return 0.0
def get_stock_price(symbol): """ Return [price, open, close, high, low, volume]""" stock = Share(symbol) return [ stock.get_price(), stock.get_open(), stock.get_prev_close(), stock.get_days_high, stock.get_days_low, stock.get_volume ]
def getAllData(ticker): stock = Share(ticker) data = { 'name': stock.get_name(), 'price': stock.get_price(), 'open': stock.get_open(), 'prev_close': stock.get_prev_close() } return data
def current_stock_value(self): symbol_f = self.symbol data = Share(symbol_f) share_value = (data.get_open()) if share_value is None: return float(self.shares) else: return '{0:.2f}'.format(float(share_value) * float(self.shares))
def getStock(name_of_company): global company_name,company_symbol stock = [] k=0 stock.append([]) stock.append("NA") stock.append("NA") stock.append("NA") stock.append("NA") stock.append("NA") stock.append("NA") stock.append("NA") j=0 for i in company_symbol: if i == name_of_company: break j=j+1 print "j is "+str(j)+"link is " stock[0]=company_name[j] yahoo = Share(name_of_company) stock[1] = yahoo.get_open() stock[2] = yahoo.get_price() stock[3] = yahoo.get_trade_datetime() stock[4] = company_symbol[j] stock[5] = yahoo.get_volume() stock[6] = yahoo.get_dividend_yield() stock[7] = google_links[j] print stock conn = mysql.connect() cur = conn.cursor() if 'username' in session: username = session['username'] cur.execute("SELECT purse FROM user WHERE username = %s;", [username]) print username for row in cur.fetchall(): for lol in row: purse=lol companystock = [dict( name=stock[0], open=stock[1], lasttradeprice=stock[2], lasttradetime=stock[3], stocksymbol=stock[4], MarketCapital=stock[5], dividend=stock[6], link=stock[7] )] cur.execute("SELECT stock FROM user WHERE username = %s;", [username]) print username for row in cur.fetchall(): for lol in row: newarray = lol.split(',') currentstock = newarray[j] print purse return companystock,stock,purse,currentstock
def 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 stock_search(symbol="YHOO"): stock = Share(symbol) open_price = stock.get_open() close_price = stock.get_prev_close() price = stock.get_price() high = stock.get_days_high() low = stock.get_days_low() volume = stock.get_volume() return stock, open_price, close_price, price, high, low, volume
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 price(name): dict={} q='qaA' q=q.lower() if(name.lower()=='apple'): name='AAPL' company=Share(name) dict['price']=company.get_price() dict['open']=company.get_open() return dict
def print_stats(ticker,is_trading_hours): stock = Share(ticker) stock.refresh() if(is_trading_hours == True): print("Current Price: $" + stock.get_price() + "\n--------------------------------------") else: print("Previous Close: $" + stock.get_prev_close()) print("Opening Price: $" + stock.get_open()) print("Current Price: $" + stock.get_price() + "\n--------------------------------------")
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 SearchPERatio(self): for x in range(8,1503,5): # for x in range(8,self.soup.select('.basic2').__len__(),5): if self.soup.select('.basic2')[x].text != '-': if float(self.soup.select('.basic2')[x].text) <=float(self.TargetPERatio) : QueryPrice = Share(self.soup.select('.basic2')[x-2].text+'.TW') #Query the API if QueryPrice.get_earnings_share()!=None and float(QueryPrice.get_earnings_share())>=self.TargetEPS: # Get EPS self.AllData.append(self.soup.select('.basic2')[x-2].text) # StockNumber self.AllData.append(QueryPrice.get_open()) # Get FinalPrice self.AllData.append(self.soup.select('.basic2')[x].text) # Get PERatio self.AllData.append(QueryPrice.get_earnings_share())
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 printPotentials(potentials): message = "" for p in potentials: stock = Share(p) price = float(stock.get_price()) o = float(stock.get_open()) change = (1.0 - (o / price)) * 100.0 message += "______ " + p + " ______\nprice=" + str( price) + "\nchange=" + str(change) + "\n" # print message sendMessage(message)
def get_stock_info(ticker): temp_share = Share(ticker) real_price = temp_share.get_price() adj_price = (float(temp_share.get_open()) + float(temp_share.get_close()) + float(temp_share.get_high()) + float(temp_share.get_low())) / 4 real_vol = temp_share.get_volume() avg_vol = temp_share.get_avg_daily_volume() avg_50_day = temp_share.get_50day_moving_avg() avg_200_day = temp_share.get_200day_moving_avg() return real_price, adj_price, real_vol, avg_vol, avg_50_day, avg_200_day
def get_stock_info(tickers): for ticker in tickers: try: stock = Share(ticker) print ticker + '\'s opening price today: ' + stock.get_open() print ticker + '\'s current price today: ' + stock.get_price() print '\n' except Exception as e: print 'Could not retrieve data for ' + ticker + '\n' return
def get_open_ticker(self): date = datetime.datetime.now() weekday = date.weekday() if (datetime.time(07,30,30) < date.time() < datetime.time(07,31,30)) and (weekday != 5 or weekday != 6) and (self.posted_open == None or self.posted_open < date.date()): stock_prices = [] all_stocks = self.get_all_stocks() if all_stocks: for stock in all_stocks: stock_info = Share(stock) stock_prices.append('%s: $%s [%s]' % (stock_info.symbol.upper(), stock_info.get_open(), stock_info.get_change())) self.posted_open = date.date() return ' - '.join(stock_prices)
def get_stock_info(tickers): for ticker in tickers: try: stock = Share(ticker) print ticker + '\'s opening price today: ' + stock.get_open() print ticker + '\'s current price today: ' + stock.get_price() ## print ticker + '\'s historical data: \n' ## print stock.get_historical('2016-10-01', '2016-10-31') print '\n' except Exception as e: print 'Could not retrieve data for ' + ticker + '\n' return
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 getCurrent(ticker): """ Return the most recent stock data through yahoo_finance. """ stock = Share(ticker) stock.refresh() #refresh the query open_ = stock.get_open() volume = stock.get_volume() high = stock.get_days_high() price = stock.get_price() time = stock.get_trade_datetime() low = stock.get_days_low() return (open_, high, volume, price, time, low)
def recentdata(companyname): try: companydata = Share(companyname) print("This morning, it opened for $" + companydata.get_open() + ", and right now is at $" + companydata.get_price() + ".") if companydata.get_open() > companydata.get_price(): difference = float(companydata.get_open()) - float( companydata.get_price()) if len(str(difference)) < 3: print("Since this morning, the price has fallen by $" + str(difference) + "0") else: print("Since this morning, the price has fallen by $" + str(difference)) elif companydata.get_open() < companydata.get_price(): difference = float(companydata.get_price()) - float( companydata.get_open()) if len(str(difference)) < 3: print("Since this morning, the price has risen by $" + str(difference) + "0") else: print("Since this morning, the price has risen by $" + str(difference)) print("") selection = input( "Would you like some info about what the stock has been like in the past few days? Yes/No: " ) if str.lower(selection) == "no": end() elif str.lower(selection) == "yes": print("Okay, please wait a moment") except (RuntimeError, TypeError, NameError): print( "Whoops, something went wrong there. Are you sure you entered a valid company abbreviation?" ) finally: longterm(companyname)
def rec(p): yahoo = Share(p) a = yahoo.get_prev_close() b = yahoo.get_year_high() c = yahoo.get_year_low() d = yahoo.get_open() e = yahoo.get_ebitda() f = yahoo.get_market_cap() g = yahoo.get_avg_daily_volume() h = yahoo.get_dividend_yield() i = yahoo.get_earnings_share() j = yahoo.get_days_low() k = yahoo.get_days_high() l = yahoo.get_50day_moving_avg() m = yahoo.get_200day_moving_avg() n = yahoo.get_price_earnings_ratio() o = yahoo.get_price_earnings_growth_ratio() print p print "Previous Close: ", a print "Year High", b print "Year Low", c print "Open:", d print "EBIDTA", e print "Market Cap", f print "Average Daily Volume", g print "Dividend Yield", h print "Earnings per share", i print "Days Range:", j, "-", k print "50 Days Moving Average", l print "200 Days Moving Average", m print "Price Earnings Ratio", n print "Price Earnings Growth Ratio", o import MySQLdb db = MySQLdb.connect(host="127.0.0.1", user="******", passwd="1111", db="stocks", local_infile=1) cur = db.cursor() cur.execute( """ INSERT INTO stockapp_info (symbol, prev_close, year_high, year_low, open_price , ebidta, market_cap, avg_daily_vol , dividend_yield, eps , days_low ,days_high, moving_avg_50, moving_avg_200, price_earnings_ratio, price_earnings_growth_ratio) VALUES (%s, %s, %s, %s, %s, %s, %s,%s,%s,%s,%s,%s,%s,%s,%s,%s) """, (p, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)) db.commit() cur.close()
def get_price_YAHOO(ticker): #for ticker in list_of_symbols: try: from yahoo_finance import Share yahoo = Share(ticker) yahoo.refresh() price_finance = yahoo.get_price() print("IN->", ticker) print("Open -> ", yahoo.get_open()) print("Current Price -> ", yahoo.get_price()) print("Ave Volume -> ", yahoo.get_avg_daily_volume()) print("Volume -> ", yahoo.get_volume()) print("Time -> ", yahoo.get_trade_datetime()) return float(price_finance) except: get_price_YAHOO(ticker)
def yahoo_aktuell(self): #symbol = '^NDX' # symbol = 'FB' wp = Share(self.wertpapier.ric) open = wp.get_open() high = wp.get_days_high() low = wp.get_days_low() close = wp.get_price() time = wp.get_trade_datetime() # MEZ: +1 Stunde # MESZ: +2 Stunden # Close KO: Uhrzeit: 2017-04-04 20:00:00 UTC+0000 => 22 Uhr # Close NDX: Uhrzeit: 2017-04-04 21:15:00 UTC+0000 => 23:15 Uhr print('Symbol:', self.wertpapier.ric, 'Kursdaten:', open, high, low, close) print('Uhrzeit:', time)
def get_price_change(stock_list=[]): for stock_line in stock_list: stock_change = Share(stock_line) last_price = stock_change.get_open() real_time_price = stock_change.get_price() if(real_time_price==None): continue if(last_price==None): continue last_price = float(last_price) real_time_price = float(real_time_price) ratio = real_time_price/last_price if(ratio>=1.05): ratio = ratio - 1 print (stock_line +"last: " + str(last_price) + " realtime: "+str(real_time_price)+ " price gain " + "%.2f"%(ratio*100) +"\n")
def get_today_stock_data(ticker): try: s = Share(ticker) data = { 'Open': float(s.get_open()), 'Close': float(s.get_prev_close()), 'High': float(s.get_days_high()), 'Low': float(s.get_days_low()), 'Volume': int(s.get_volume()), 'Date': datetime.date.today(), } return data except YQLQueryError: logger.error("Daily data not found for {}".format(ticker)) except Exception as e: logger.error("Unexpected error occurred: {}".format(e)) return {}
def post(): ## Update stock info try: stock_list = Stock.objects.all() for stock in stock_list: try: s = Share(stock.symbol) stock.price = s.get_price() stock.open_price = s.get_open() stock.pre_close_price = s.get_prev_close() stock.high_price = s.get_days_high() stock.low_price = s.get_days_low() stock.save() except Exception, e: pass except Exception, e: pass
def scraper4(ticker): """ Returns real time price and realted info (realtime[0], targettime, changetarget, targetpercent, openprice) scraped from URL for supplied ticker #Replaces scraper3; scraper3 broke after update to Yahoo Finance """ url = baseurl + ticker + endurl page = urllib2.urlopen(url) soup = BeautifulSoup(page.read(), "lxml") targettime = 'NA' #realtime = soup.find("span", {"class": "time_rtq_ticker"}).span.contents realtime = soup.find("div", {"id": "app"}) realtime = soup.find("span", {"class": "Fw(b) D(ib) Fz(36px) Mb(-4px)"}) # Fw(500) D(ib) Fz(36px) changetargetdown = soup.find("span", {"class": "Fw(500) D(ib) Pstart(10px) Fz(24px) C($dataRed)"}) #dataRed is down, dataGreen is up changetargetup = soup.find("span", {"class": "Fw(500) D(ib) Pstart(10px) Fz(24px) C($dataGreen)"}) #$datagreen is up #prevclose = soup.find("td", {"class": "Ta(end) Fw(b)"}).text stock = Share(ticker) marketopen = stock.get_open() #print marketopen #print realtime.text #prints the realtime price if changetargetdown is not None: #print changetargetdown.text changeindollars = changetargetdown.text.split("(")[0] #might be broken? changeinpercent = changetargetdown.text.split("(")[1].strip(")") #print changeindollars #print changeinpercent if changetargetup is not None: #print changetargetup.text changeindollars = changetargetup.text.split("(")[0] changeinpercent = changetargetup.text.split("(")[1].strip(")") #print changeinpercent #print changeindollars #print changeinpercent #subtime, change ,subpercent, openprice #print realtime.text, targettime, changeindollars, changeinpercent, marketopen return realtime.text, targettime, changeindollars, changeinpercent, marketopen
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 sp500info(): #gets the S&P 500 price, ticker, changes, etc. sp500ticker = '^GSPC' sp500desc = "S&P 500 Index: " sp500index = Share(sp500ticker) #sp500price = sp500index.get_price() sp500price = scraper(sp500ticker) #sp500change = sp500index.get_change() sp500open = sp500index.get_open() #print sp500index.get_50day_moving_avg() #print sp500index.get_200day_moving_avg() #print sp500ma50, sp500ma200 sp500price = str(sp500price).strip('[]') sp500price = sp500price.replace(",", "") #print(repr(sp500price)) #scrub the ticker for hidden values; troubleshooting sp500change = float(sp500price) - float(sp500open) sp500dayhigh = sp500index.get_days_high() sp500percentchange = getPercentChange(sp500index, sp500change, sp500open) return sp500percentchange, sp500dayhigh, sp500open, sp500change, sp500price, sp500index, sp500desc
def main(): PATH_OF_DATA = 'data' error_log_file = open('error.log', 'a') index_lists = [ f[:-4] for f in listdir(PATH_OF_DATA) if f[-4:] == '.csv' ] skipFlag = True if len(sys.argv) > 1 else False tillFlag = True if len(sys.argv) > 2 else False for stock_index in index_lists: if skipFlag: if stock_index != sys.argv[1]: continue else: skipFlag = False if tillFlag: if stock_index == sys.argv[2]: break filename = join(PATH_OF_DATA, stock_index+'.csv') if isfile(filename):# 如果已經有檔案,就讀出最後一行然後插入在後面 lastline = get_last_row(filename) print 'lastline = ', lastline try: st = Share(stock_index+'.tw') if not time_after(lastline[0], st.get_trade_datetime()[:10]): print 'time : ', st.get_trade_datetime()[:10] fo = open(filename, 'ab') cw = csv.writer(fo, delimiter=',') # 更新當天資料 cw.writerow([st.get_trade_datetime()[:10], st.get_open(), st.get_days_high(), st.get_days_low(), st.get_price(), st.get_volume(), '0.0']) print "更新一筆!" else: print "不需要更新" except: print stock_index, "update error!" error_log_file.write('%s, Update Error\n' % (stock_index))
def fetch_current_data(self, sym): ts = get_latest_trading_date(get_cur_time()) if ts in self.datasets_daily[sym].keys() or ts > self.endDate: return try: sdata = Share(sym) gquote = gQuotes(sym) except: # live with the fact that data from the most recent day is missing return self.datasets_daily[sym][ts] = t = {} t['Date'] = '3000-01-01' #debugging purposes, so we know this is current. This won't be saved to file t['High'] = float(sdata.get_days_high()) t['Low'] = float(sdata.get_days_low()) t['Open'] = float(sdata.get_open()) # t['Close'] = sdata.get_price() t['Close'] = float(gquote[0]['LastTradePrice']) # use google data for latest 'Close', which is more accurate t['Volume'] = float(sdata.get_volume()) for k in t.keys(): if t[k] == None: raise Exception('missing most recent daily', sym)
class YahooFinanceData: """Get data from Yahoo Finance.""" def __init__(self, symbol): """Initialize the data object.""" from yahoo_finance import Share self._symbol = symbol self.state = None self.price_change = None self.price_open = None self.prev_close = None self.stock = Share(self._symbol) def update(self): """Get the latest data and updates the states.""" self.stock.refresh() self.state = self.stock.get_price() self.price_change = self.stock.get_change() self.price_open = self.stock.get_open() self.prev_close = self.stock.get_prev_close()
def moreInfo(from_number): #query to find the stock the user last looked up conn = mysql.connect() cur = conn.cursor() q = '''SELECT * FROM last_lookup WHERE phone = %s''' cur.execute(q,[from_number]) rv = cur.fetchone() #get stock information quote = Share(str(rv[1])) prevClose = quote.get_prev_close() openPrice = quote.get_open() volume = quote.get_volume() #if we get all the information back respond back with more info if prevClose and openPrice and volume: retStr = "PrevClose: "+prevClose+" OpenPrice: "+openPrice+" Volume: "+ volume #else the user has not looked up a stock yet else: retStr = "ticker still not found" return retStr
def displayStockQuotes(symbols, seconds): """ Display each symbol's price, volume and percent change for seconds :param: symbols: List of stock symbols in Yahoo format. E.g. 'AMZN' or 'BRK-B' (NOTE: not 'BRK.B'). :param: seconds: Number of seconds to display each stock. # The following Adafruit_CharLCD library is found here: # https://github.com/adafruit/Adafruit_Python_CharLCD # See this tutorial for a hello world Python/Raspberry Pi/LCD tutorial: # https://learn.adafruit.com/drive-a-16x2-lcd-directly-with-a-raspberry-pi/python-code """ lcd = Adafruit_CharLCD() while True: for symbol in symbols: stock = Share(symbol) lcd.clear() lcd.message(symbol + ": $") lcd.message(stock.get_price() + "\n") volume = stock.get_volume() change = stock.get_change() lcd.message(change + "|") open = stock.get_open() if type(open) is str and type(change) is str: percentChange = float(change) / float(open) # format percent change in human-readable format: "1%" instead of ".01" lcd.message("{0:.00%}".format(percentChange)) else: lcd.message("?") if volume: lcd.message("|" + volume) else: lcd.message("|?") sleep(seconds) # Delay between each stock/symbol
def history(): # If a user goes to the display page and a session is not active if session.get('active') != True: sym = 'SPY' session['active'] = True session['sym'] = sym else: sym = session['sym'] # if a session is active leave the sym alone share = Share(sym) historical = share.get_historical('2016-03-13', '2016-04-15') canvas_list = [] for day in historical: canvas_list.append([int(day['Date'][:4]), int(day['Date'][5:7]) - 1, int(day['Date'][-2:]), float(day['Open']), float(day['High']), float(day['Low']), float(day['Close']) ]) info = share.get_info() open = share.get_open() high = share.get_days_high() low = share.get_days_low() price = share.get_price() canvas_list.append([int(info['end'][:4]), int(info['end'][5:7]) - 1, int(info['end'][-2:]), float(open), float(high), float(low), float(price) ]) return render_template('history.html', canvas_list=canvas_list, sym=sym)
class YahooFinanceData(object): """Get data from Yahoo Finance.""" def __init__(self, name, symbol): """Initialize the data object.""" from yahoo_finance import Share self._name = name self._symbol = symbol self.state = None self.price_change = None self.price_open = None self.prev_close = None self.stock = Share(symbol) @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Get the latest data and updates the states.""" self.stock.refresh() self.state = self.stock.get_price() self.price_change = self.stock.get_change() self.price_open = self.stock.get_open() self.prev_close = self.stock.get_prev_close()