def sell(): if 'username' in session: # Get symbol name s = request.args.get('symbol') # recreate users stock information if not models.new_stock: models.Users.reload_user() # symbol name is valid if s is not None and s != '': symbol = Share(s) if symbol.get_price() is None: return render_template('apology.html', message=['Something went wrong. Please try again.']) else: # Get user's stock info holding = models.Stockholding.objects.get(username=session['username'], symbol=s) amount_to_add = int(holding.shares) * float(symbol.get_price()) # add value of shares to user's cash models.Users.objects(username=session['username']).update(inc__cash=amount_to_add) # log transaction transaction = models.Transaction(username=session['username'], date=time.strftime("%d/%m/%Y"), \ type=models.Transaction.SELL, symbol=s, shares=holding.shares) transaction.save() holding.delete() # Remove stock flash('Stock sold successfully', 'text-success') models.Users.reload_user() print models.new_stock return redirect('portfolio') return render_template('sell.html', stocks=models.new_stock) return render_template('apology.html', message=['Log In to see this page'])
def get_item_info(self, item): name = "" if (item >= self.top): yahoo = Share(self.updated_list[item]) name = self.updated_list[item] else: yahoo = Share(self.list_indexes[item]) name = self.list_indexes[item] string = name + " " + str(yahoo.get_price()) + " " + str( yahoo.get_change()) symbol_info = [] symbol_info.append(name) symbol_info.append(str(yahoo.get_price())) symbol_info.append(str(yahoo.get_change())) symbol_info.append(str(yahoo.get_trade_datetime())) if "None" in symbol_info[2]: symbol_info[2] = symbol_info[2][:-4] for i in range(0, len(symbol_info)): if i == 3: font = pygame.font.Font(self.display_font, self.font_size_lower) else: font = pygame.font.Font(self.display_font, self.font_size) font.set_bold(self.bold) symbol_info[i] = (symbol_info[i], font.size(symbol_info[i])) return symbol_info
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 getTodaysPortfolio(portfolio): port_today = [] for stock in portfolio: ticker = stock.Ticker stock_yhoo = Share(ticker) port_today.append({ "id": stock.id, "Ticker": ticker, "CurrentPrice": stock_yhoo.get_price(), "pct_change": stock_yhoo.get_change(), "Quote_Each": stock.Quote_Each, "Number_of_Shares": stock.Number_of_Shares, "Value": stock.Value, "Today_Value": float(stock.Number_of_Shares) * float(stock_yhoo.get_price()), "Date_Time": stock.Date_Time, }) return port_today
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 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 buy(self, symbol, trader, share): stock = Share(symbol) price = stock.get_price() trade_time = time.strftime("%Y-%m-%d %H:%M:%S") print stock.get_price() self.traderDAO.insertValues(symbol, "B", trader, share, trade_time, price)
def move_target_realworldmapping(): REAL_WORLD_ENVIRONMENT = "stocks" # REAL_WORLD_ENVIRONMENT = "stocks" # pulls stocks/indices datastream from Yahoo Finance if (REAL_WORLD_ENVIRONMENT == "stocks"): #print("mapping to Yahoo Finance datastreams") from yahoo_finance import Share ftse = Share('^FTSE') ftse_price = float(ftse.get_price()) #print (ftse_price) ndx = Share('^NDX') ndx_price = float(ndx.get_price()) #print (ndx_price) n225 = Share('^N225') n225_price = float(n225.get_price()) #print (n225_price) #ftse.refresh() #ndx.refresh() #n225.refresh() params['DYNAMIC_ENVIRONMENT_TARGET'] = (ftse_price, ndx_price, n225_price) else: # don't move_target print( "Error, in the fitness function move_target_realworldmapping() the REAL_WORLD_ENVIRONMENT is not implmented!" )
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 getPrice(share): for x in range(0, 30): price = Share(share) print price.get_price() stocks_price.append(price.get_price) time.sleep(60) print 'Share information recieved'
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 get_stock_prices(stock_symbol_list): """Returns a string that includes a list of stocks and their prices""" stock_response_line_list = [] for stock_symbol in stock_symbol_list: stock = Share(stock_symbol) stock_response_line = stock_symbol + ": " + ( stock.get_price() if stock.get_price() is not None else "Not Found") stock_response_line_list.append(stock_response_line) return "\n".join(stock_response_line_list)
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 get_initial_company_info(self): """Gets the initial information for each company""" company_dict = tf.open_json() driver = webdriver.PhantomJS( service_args=['--ignore-ssl-errors=true', '--ssl-protocol=any']) url = "https://uk.finance.yahoo.com/" for company in company_dict: driver.get(url) # Gets symbol for company if company_dict[company]["Symbol"] == "unknown": time.sleep(3) # allows time for page to load try: elem = driver.find_element_by_name("p") elem.send_keys(company) elem.send_keys(Keys.RETURN) time.sleep(3) # allows time for the page to load symbol = driver.current_url.split("=")[-1] company_dict[company]["Symbol"] = symbol except Exception: pass # Gets initial share price if company_dict[company]["Initial-share-price"] == 1: try: yahoo = Share(company_dict[company]["Symbol"]) share = yahoo.get_price() company_dict[company]["Initial-share-price"] = float(share) except Exception: pass # current-share-price if company_dict[company]["Current-share-price"] == 1: try: yahoo = Share(company_dict[company]["Symbol"]) share = yahoo.get_price() company_dict[company]["Current-share-price"] = float(share) except Exception: pass # writes info back into the monitor json tf.write_to_json(company_dict)
def check_sell(self): #UNCOMMENT WHEN USING ACTUAL DATA if self.owned_shares == 0: return False share = Share(self.code) current_price_u = share.get_price() if current_price_u is None: self.log('Current Price is None for Stock') return 0 current_price = float(current_price_u) #UNCOMMENT WHEN USING ACTUAL DATA if self.bought_value < current_price: return False avg50 = self.get_short_moving_avg() avg200 = self.get_long_moving_avg() if avg50 < avg200: #trend change, buy sell(self, self.owned_shares,current_price) return True return False
def check_buy(self): #one-time buy if self.owned_shares != 0: return False share = Share(self.code) avg50 = self.get_short_moving_avg() avg200 = self.get_long_moving_avg() if avg50 == -1.0 or avg200 == -1.0: self.log('Short or Long moving average cannot be obtained due to yahoo API error') return 0 current_price_u = share.get_price() if current_price_u is None: self.log('Current Price is None for Stock') return 0 current_price = float(current_price_u) if avg50 > avg200: #trend change, buy buy_count = self.how_many_shares_to_buy(current_price) if buy_count != 0: if buy(self, buy_count, current_price) == True: self.owned_shares = buy_count self.bought_value = float(current_price * self.owned_shares) return self.owned_shares return 0
def __init__(self, symbol, priceBought, countBought, dateBought): self.symbol = symbol self.priceBought = priceBought self.countBought = countBought self.dateBought = dateBought yhoEntity = Share(self.symbol) self.currPrice = float(yhoEntity.get_price())
def addTransaction(self, trade, tradeCount, assetSymbol): asset = Asset.objects.get(symbol=assetSymbol) portfolioAssetMapping = PortfolioAssetMapping.objects.get(asset=asset) timestamp = "2016-01-06" initialCount = portfolioAssetMapping.currentCount finalCount = initialCount if trade == "buy": finalCount = initialCount + tradeCount if trade == "sell": finalCount = initialCount - tradeCount portfolioAssetMapping.currentCount = finalCount assetInfo = Share(assetSymbol) price = finalCount * float(assetInfo.get_price()) transaction = Transaction(mapping=portfolioAssetMapping, trade=trade, timestamp=timestamp, initialCount=initialCount, finalCount=finalCount, tradeCount=tradeCount, price=price) transaction.save() portfolioAssetMapping.save()
def get(self): self.response.headers['Content-Type'] = 'text/plain' gs = pygsheets.authorize(service_file=SERVICE_CREDS, no_cache=True) sh = gs.open(SHEET_FILE_NAME) ws = sh.worksheet_by_title(SHEET_WORK_NAME) try: shares = ['^AORD', 'FXJ.AX', 'TLS.AX', 'REA.AX', 'CBA.AX'] for symbol in shares: share = Share(symbol) s_price = share.get_price() s_name = share.get_name() symbol_cells = sh.find(symbol) if len(symbol_cells) == 0: ws.append_table(values=[s_name, symbol, s_price]) else: symbol_cell = symbol_cells[0] symbol_cell.neighbour('left').value = s_name symbol_cell.neighbour('right').value = s_price self.response.write('OK') except: logging.exception('Caught exception in fetch') self.response.write('EXCEPTION')
def get_updates(self): dict = {} r_list = [] for symbol in self.list: try: s = Share(symbol) tmp = s.get_trade_datetime().split() timestamp = tmp[0] + 'T' + tmp[1] + '.00' price = int(s.get_price().split(".")[self.PRICE]) #print("type for price:{}".format(type(price))) dict[symbol] = [price, timestamp] del s except: pass #print ("Could not find {} in yahoo finance".format(symbol)) for item in dict: r_list.append((item, datetime.strptime(dict[item][self.TIME], "%Y-%m-%dT%H:%M:%S.%f"), dict[item][self.PRICE])) # r_list.append((item, datetime.now(), dict[item])) for i in r_list: yield i return ["GOOG", datetime(2104, 2, 13), 37]
class stocktw(object): CaptialCashYear = 3 def __init__(self, stockNum): self.stockNum = str(stockNum) self.share = Share(self.stockNum + ".tw") self.share.refresh() def getPrice(self): price = 0 try: price = self.share.get_price() except: print("get price error:" + self.stockNum) return price def isIncrease(self, x, key=lambda x: x): return all([key(x[i]) <= key(x[i + 1]) for i in self.CaptialCashYear]) def isCaptialCashDecrease(self): url = str('http://easyfun.concords.com.tw/z/zc/zcb/zcb_%s.djhtm' % self.stockNum) soup = BeautifulSoup(requests.get(url).text, 'lxml') table = pd.read_html(str(soup.find_all('table')[0])) df = table[2] df = df.ix[1:, :2] df.columns = df.iloc[0] df = df[1:] ds = df["比重"].str[:-1].apply(pd.to_numeric) decreasing = lambda L: all(x <= y for x, y in zip(L, L[1:])) check = decreasing(ds[:self.CaptialCashYear]) return check
def get_initial_company_info(): """Gets the initial information for each company""" company_dict = utils.open_json(MONITOR) for company in company_dict: # Gets symbol for company if company_dict[company]["Symbol"] == "unknown": try: with urllib.request.urlopen( f'https://finance.yahoo.com/_finance_doubledown/' f'api/resource/searchassist;searchTerm={company}' ) as response: html = response.read().decode() d = json.loads(html) company_dict[company]["Symbol"] = d['items'][0][ 'symbol'] except urllib.error.HTTPError as error: utils.write_to_log(f'Error opening URL: {error}') # Gets initial share price if company_dict[company]["Initial-share-price"] == 1: yahoo = Share(company_dict[company]["Symbol"]) share = yahoo.get_price() company_dict[company]["Initial-share-price"] = float(share) company_dict[company]["Current-share-price"] = float(share) utils.write_to_json(MONITOR, company_dict)
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 combine(onedayago, twodaysago, threedaysago, fivedaysago, oneweekago, companyname): print "Analyzing data from the past few days..." dates = [onedayago, twodaysago, threedaysago, fivedaysago, oneweekago] for i in dates: i == i.format('YYYY-MM-DD') # Just gets the info and puts it into programmer friendly names def getclosing(date, company): # Thanks to stackoverflow user 'TessellatingHeckler' for helping me out with this next function! At the time dictionaries were a foreign concept to me. readings = company.get_historical(date, date) for reading in readings: close = reading['Close'] return close company = Share(companyname) closingonedayago = getclosing(str(dates[0]), company) closingtwodaysago = getclosing(str(dates[1]), company) closingthreedaysago = getclosing(str(dates[2]), company) closingfivedaysago = getclosing(str(dates[3]), company) closingoneweekago = getclosing(str(dates[4]), company) twohundredavg = company.get_200day_moving_avg() fiftyavg = company.get_50day_moving_avg() today = company.get_price() decision(today, closingonedayago, closingtwodaysago, closingthreedaysago, closingfivedaysago, closingoneweekago, twohundredavg, fiftyavg)
def main(): """ Reads in a CSV file specifying the portfolio of stocks and their respective ratios within the portfolio.""" stocks = {} with open(STOCK_RATIO_FILE) as csvfile: reader = csv.reader(csvfile, delimiter=',') for row in reader: ticker, fraction = row[0].strip(), float(row[1].strip()) stocks[ticker] = {} share = Share(ticker) scurr = share.get_currency() if scurr != CURRENCY: xchrate = float(Currency(scurr + CURRENCY).get_rate()) else: xchrate = 1.0 price = float(share.get_price()) * xchrate stocks[ticker]['price'] = price stocks[ticker]['in_currency'] = CURRENCY stocks[ticker]['target_ratio'] = fraction stocks[ticker]['name'] = share.get_name() stocks[ticker]['target_number'] = np.round(fraction * TOTAL_CASH / price) print(json.dumps(stocks, indent=2)) total_value = 0 for stock in stocks: s = stocks[stock] total_value += s['price'] * s['target_number'] print('Total Portfolio Value:') print(total_value)
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 populate_stocks(): ticker_list = [] for i in range(1, 6): ticker_list.extend( list(map(''.join, product(ascii_uppercase, repeat=i)))) for tick in ticker_list: print("Checking " + tick + ".") if Share(tick).get_name(): try: if Stock.objects.get(ticker=tick): print(tick + " already exists. Skipping database entry.") continue except: stock_info = Share(tick) stock = Stock( name=stock_info.get_name(), ticker=tick, price=stock_info.get_price(), price_target=stock_info.get_one_yr_target_price(), is_bullish=None, last_updated=timezone.now()) stock.save() print(tick + " " + Share(tick).get_name())
def main(): outfile = open('process.txt', 'w') ticker = [] infile = open('NASDAQ.txt', 'r') for line in infile: line.rstrip('\n') share = Share(line) price = share.get_price() if price != None: if float(share.get_price()) > 10: outfile.write(line) infile.close() outfile.close()
def combine(onedayago, twodaysago, threedaysago, fivedaysago, oneweekago, companyname): print "Analyzing data from the past few days..." dates = [onedayago, twodaysago, threedaysago, fivedaysago, oneweekago] for i in dates: i == i.format('YYYY-MM-DD') # Just gets the info and puts it into programmer friendly names def getclosing(date, company): # Thanks to stackoverflow user 'TessellatingHeckler' for helping me out with this next function! At the time dictionaries were a foreign concept to me. readings = company.get_historical(date, date) for reading in readings: close = reading['Close'] return close company = Share(companyname) closingonedayago = getclosing(str(dates[0]), company) closingtwodaysago = getclosing(str(dates[1]), company) closingthreedaysago = getclosing(str(dates[2]), company) closingfivedaysago = getclosing(str(dates[3]), company) closingoneweekago = getclosing(str(dates[4]), company) twohundredavg = company.get_200day_moving_avg() fiftyavg = company.get_50day_moving_avg() today = company.get_price() decision(today, closingonedayago, closingtwodaysago, closingthreedaysago, closingfivedaysago, closingoneweekago, twohundredavg, fiftyavg)
def getPrice(bodyList, from_number): retStr = "" #interate over bodyList for ticker in bodyList: quote = Share(str(ticker)) price = quote.get_price() #construct return string with price ticker if found #appended the comma and space in the front, will remove preceeding comma after loop if price: retStr += ", " + ticker + " Price: " + price else: retStr += ", ticker not found" #update last_lookup field so the "more info" feature works conn = mysql.connect() cur = conn.cursor() q = '''INSERT INTO last_lookup (phone, ticker) VALUES (%s, %s) ON DUPLICATE KEY UPDATE ticker = VALUES(ticker) ''' try: cur.execute(q, (from_number, ticker)) conn.commit() except: conn.rollback() #strip preceeding comma and space retStr = retStr[2:] return retStr
def get_stock_info(name, abbr): x = Share(abbr) x.refresh() price = x.get_price() change = x.get_percent_change() print(change[0] == '-') if change[0] == '-': color = '#B22222' else: color = '#006400' url = "https://news.google.com/news?q={0}&output=rss".format(name) feed = feedparser.parse(url) entries = [] i = 0 while i < len(feed.entries) and i < 7: title = feed.entries[i]['title'] index = title.index('-') author = title[index + 2:] title = title[:index - 1] link = feed.entries[i]['link'] entries.append({'title': title, 'author': author, 'link': link}) i += 1 return { 'price': price, 'change': change, 'color': color, 'entries': entries }
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 stocks(self, message, params=None, **kwargs): """Display current stock value for user provided symbol(s) (ex: .stock rax,yhoo,aapl) """ if not params: message.dispatch("No stock symbol provided, please provide " "at least one symbol. Example: .stock rax or " ".stock rax,yhoo,aapl") return text = "" try: symbols = params.upper().split(',') for s in symbols: share = Share(s) text = (text + "%s: %s (%s) | " % (s, share.get_price(), share.get_change())) text = text.rstrip(" ") text = text.rstrip("|") except Exception: text = ("Unable to fetch stocks data. " "Please ensure the symbols you've provided are valid") message.dispatch(text)
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 combine(onedayago, twodaysago, threedaysago, fivedaysago, oneweekago, companyname): print("Analyzing data from the past few days...") dates = [onedayago, twodaysago, threedaysago, fivedaysago, oneweekago] for i in dates: i == i.format('YYYY-MM-DD') # Just gets the info and puts it into programmer friendly names def getclosing(date, company): readings = company.get_historical(date, date) for reading in readings: close = reading['Close'] return close company = Share(companyname) closingonedayago = getclosing(str(dates[0]), company) closingtwodaysago = getclosing(str(dates[1]), company) closingthreedaysago = getclosing(str(dates[2]), company) closingfivedaysago = getclosing(str(dates[3]), company) closingoneweekago = getclosing(str(dates[4]), company) twohundredavg = company.get_200day_moving_avg() fiftyavg = company.get_50day_moving_avg() today = company.get_price() decision(today, closingonedayago, closingtwodaysago, closingthreedaysago, closingfivedaysago, closingoneweekago, twohundredavg, fiftyavg)
def get_ma(stock): prices_10 = [] prices_20 = [] stock = Share(stock) if (stock.get_price() < 5): return 0, 0, 0 dma_10 = now - timedelta(days=30) date10 = str(dma_10.year) + "-" + str(dma_10.month) + "-" + str(dma_10.day) time.sleep(0.5) try: data = stock.get_historical(date10, theDate) prices_50 = stock.get_50day_moving_avg() count = 0 for theData in data: if count < 10: count = count + 1 prices_10.append(float(theData['Adj_Close'])) else: continue count = 0 for theData in data: if count < 20: count = count + 1 prices_20.append(float(theData['Adj_Close'])) else: continue except: return 0, 0, 0 print prices_50 return prices_10, prices_20, prices_50
def get_risers_and_fallers(self, account): print(datetime.now(), 'checking risers and fallers') risers = [] fallers = [] if account.portfolio != {}: for key in account.portfolio.keys(): try: share = account.portfolio[key] bought_price = float(share.price) units = float(share.holding) total_bought_price = bought_price * units s = Share(key) price = float(s.get_price()) net_gain = round((price * units) - total_bought_price, 2) print("net", net_gain) percent_gain = round( ((price - bought_price) / bought_price) * 100, 2) print("percent", percent_gain) if percent_gain > 0: risers.append((key, percent_gain, net_gain)) else: fallers.append((key, percent_gain, net_gain)) except: continue return risers, fallers
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.')
def data_frame_companies_prices(list_companies,a,b): # Es una funcion que toma una lista de empresas (codificadas por yahoo.finance) y valor minimo y maximo # de la distribucion uniforme que sigue la diferencia entre el bid y el ask para las empresas. list_index=["ask5","ask4","ask3","ask2","ask1","bid1","bid2","bid3","bid4","bid5"] companies_prices=pd.DataFrame(index=list_index) for i in list_companies: company = Share(i) open_price=company.get_price() open_price=float(open_price) a=float(a) b=float(b) random1=(np.random.rand(1)+(a/b-a))/(1.0/b-a) first_ask_price=open_price+(round(random1,2))/2.0 ask_array=np.array([first_ask_price+0.04,first_ask_price+0.03,first_ask_price+0.02,first_ask_price+0.01,first_ask_price]) first_bid_price=open_price-(round(random1,2))/2.0 bid_array=np.array([first_bid_price+0.04,first_bid_price+0.03,first_bid_price+0.02,first_bid_price+0.01,first_bid_price]) ask_bid_array=np.concatenate((ask_array,bid_array)) companies_prices[i]=ask_bid_array return companies_prices
def get(self, request, symbol): try: stock = Stock.objects.get(ticker=symbol) self.update_stock(stock) except ObjectDoesNotExist: stock_info = Share(symbol) stock = Stock( name=stock_info.get_name(), ticker=symbol, price=stock_info.get_price(), price_target=stock_info.get_one_yr_target_price(), is_bullish=None, last_updated=timezone.now() ) stock.save() try: stock = Stock.objects.get(ticker=symbol) except ObjectDoesNotExist: stock = "Still can not pull stock." return render(request, self.template_name, { 'stock': stock, 'stock_tracked': self.stock_tracked(request, symbol) })
def getPrice(bodyList, from_number): retStr = "" #interate over bodyList for ticker in bodyList: quote = Share(str(ticker)) price = quote.get_price() #construct return string with price ticker if found #appended the comma and space in the front, will remove preceeding comma after loop if price: retStr += ", " + ticker + " Price: " + price else: retStr += ", ticker not found" #update last_lookup field so the "more info" feature works conn = mysql.connect() cur = conn.cursor() q = '''INSERT INTO last_lookup (phone, ticker) VALUES (%s, %s) ON DUPLICATE KEY UPDATE ticker = VALUES(ticker) ''' try: cur.execute(q,(from_number,ticker)) conn.commit() except: conn.rollback() #strip preceeding comma and space retStr = retStr[2:] return retStr
def create_files(): for i in range(0,TIME_IN_MIN*60/TIME_BETWEEN_ITERATIONS): reader=csv.DictReader(open('Yahoo_symbols.csv','rb')) for sym in reader: company=sym["COMPANY"] symbol=sym["SYMBOL"] while(1): try: share_name=Share(symbol) if share_name: break except: time.sleep(1) filename = "./Q4_files/"+company+".csv" try: file=open(filename,"a") except: file=open(filename,"w") file.write("Time,Price") timestamp = share_name.get_trade_datetime() price = share_name.get_price() writer = csv.DictWriter(file, fieldnames=["Time","Price"], delimiter=",", lineterminator="\n") writer.writerow({"Time":timestamp ,"Price":price}) time.sleep(TIME_BETWEEN_ITERATIONS) file.close()
def get_stock_price_and_volume(symbol, start_date, end_date, dates): share = Share(symbol) hist_data = share.get_historical(start_date, end_date) hist_data.reverse() volume = [] price = [] i = 0 for d in dates: if i < len(hist_data): if (hist_data[i]['Date'] == d): # Weekday price.append(hist_data[i]['Close']) volume.append(hist_data[i]['Volume']) i += 1 else: # Weekend price.append(0) volume.append(0) else: # Get the current price and volume instead from historical data price.append(share.get_price()) volume.append(share.get_volume()) if len(dates) != len(volume) and len(dates) != len(price): print 'Dates and volume and/or price lists are not of same lenght!' return [price, volume]
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 create_files(): for i in range(0, TIME_IN_MIN * 60 / TIME_BETWEEN_ITERATIONS): reader = csv.DictReader(open('Yahoo_symbols.csv', 'rb')) for sym in reader: company = sym["COMPANY"] symbol = sym["SYMBOL"] while (1): try: share_name = Share(symbol) if share_name: break except: time.sleep(1) filename = "./Q4_files/" + company + ".csv" try: file = open(filename, "a") except: file = open(filename, "w") file.write("Time,Price") timestamp = share_name.get_trade_datetime() price = share_name.get_price() writer = csv.DictWriter(file, fieldnames=["Time", "Price"], delimiter=",", lineterminator="\n") writer.writerow({"Time": timestamp, "Price": price}) time.sleep(TIME_BETWEEN_ITERATIONS) file.close()
def get_title(title, cache=True): return_dic = {} # if cache == True, try to open the cached file if cache: cached_filename = 'cache/finance_{0}.json'.format(title) if os.path.exists(cached_filename): with open(cached_filename) as f: items = json.loads(f.read()) return items # if cache == False, or the cached file does not exist, call the API try: t = Share(title) return_dic["symbol"] = title return_dic["price"] = t.get_price() return_dic["change"] = t.get_change() return_dic["name"] = t.data_set["Name"] except: return_dic["symbol"] = title return_dic["price"] = 0 return_dic["change"] = 0 return_dic["name"] = title # if cache == True but we are down here, it means that the cached file does not exist, so create it if cache: with open(cached_filename, 'w') as f: json.dump(return_dic, f) return return_dic
def report_current_from_yahoo(symbol): yahoo = Share(symbol) price_cur = yahoo.get_price() eps = yahoo.get_earnings_share() pe = yahoo.get_price_earnings_ratio() print 'yahoo: price=%s eps=%s, pe=%s'%(price_cur, eps, pe)
def gather(self): share = Share(self.code) price = share.get_price() if price is None: self.log('Company gave no price') return self.prices.append(float(price)) return
def action(self): self.yahoo_finance_connect = "RAN" code = 'GOOG' # stock symbol here s = Share(code) price = s.get_price() self.price = price
def check_price(self, ticker): try: company = Share(ticker) return float(company.get_price()) except: print 'Failed to check price' print sys.exc_info()[0]; return 0
def getStockInfo(symbol): yahoo_finance_client = Share(symbol) stock_info = {} stock_info["price"] = yahoo_finance_client.get_price() stock_info["change"] = yahoo_finance_client.get_change() return stock_info
def get_database(stock): """Return stock database""" now = date.today() mystock = Share(stock) now_price = mystock.get_price() #ราคาปัจจุบัน import_time = mystock.get_trade_datetime() #เวลาที่ดึงฐานข้อมูล stock_db = mystock.get_historical("2015-01-01", now.isoformat()) #ฐานข้อมูลหุ้นตั้งแต่วันที่ 1 มกราคม 2558 ถึงปัจจุบัน return now, stock, now_price, import_time, stock_db
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 is_valid_stock_symbol(stock_symbol): """Returns true if stock symbol is listed in Yahoo Finance false otherwise""" stock = Share(stock_symbol) if stock.get_price() is None: return False else: return True
def whattodo(figure): # convert list to string # do we need to account for each transaction as well global trader_overhead key=''.join(str(e) for e in figure) action=figdict[key][4] if "-" in action: action="sell" else: action="buy" elemental=figdict[key][2] # elemental="Earth" # action="sell" whichone=random.choice(company_dict[elemental]) print action,whichone,elemental if action=="buy": if portfolio[elemental].has_key(whichone): portfolio[elemental][whichone]+=1 else: portfolio.setdefault(elemental, {})[whichone] = 1 print "Buy", whichone bought=Share(whichone) print "Price", bought.get_price() # do buy action if we have da cash cash = req_admxi.get_cash(ALGO) if bought.get_price(): if cash>(float(bought.get_price())+trader_overhead): # 50 just in case exec_buy(whichone) trader_overhead+=1.0 elif action=="sell": #choose a random from elemental dict if portfolio[elemental].has_key(whichone): print portfolio # unless it is zero decrement it if portfolio[elemental][whichone]>0: portfolio[elemental][whichone]-=1 print "Sell", whichone sold=Share(whichone) print "Price", sold.get_price() exec_sell(whichone) trader_overhead+=1.0 else: print "No action taken" return (' '.join((action,whichone)))
def collect_stocks_data(stocks, ipo_to_present_name, ipo_one_year_name): f_all_data = create_file("all_data/{}".format(ipo_to_present_name)) f_yearly_data = create_file("year_only_data/{}".format(ipo_one_year_name)) for stock in stocks: try: symbol = stock.get_symbol() name = stock.get_name() share = Share(symbol) price = share.get_price() historical_data = share.get_historical(start_date, end_date) if len(historical_data) > 1: oldest_entry_available = historical_data[-1] oldest_entry_closing_price = oldest_entry_available['Adj_Close'] oldest_entry_date = datetime.strptime(oldest_entry_available['Date'], "%Y-%m-%d") # Only use companies that IPOed two weeks after the first of january in 2005. # This was done to account for some missing data. if (oldest_entry_date - min_ipo_date).total_seconds() > NUM_SECONDS_TWO_WEEKS: ipo_date = date_to_string(oldest_entry_date) current_price_rounded = "%.2f" % float(price) ipo_price_rounded = "%.2f" % float(oldest_entry_closing_price) data = str((symbol, ipo_date, ipo_price_rounded, current_price_rounded)) write_and_flush(f_all_data, data) if(len(historical_data) > NUM_WORK_DAYS_ONE_YEAR): year_after_ipo_entry = historical_data[-NUM_WORK_DAYS_ONE_YEAR] year_after_ipo_date = datetime.strptime(year_after_ipo_entry['Date'], "%Y-%m-%d") year_after_ipo_date = date_to_string(year_after_ipo_date) year_after_ipo_price = "%.2f" % float(year_after_ipo_entry['Adj_Close']) data = str((symbol, ipo_date, ipo_price_rounded, year_after_ipo_date, year_after_ipo_price)) write_and_flush(f_yearly_data, data) else: print "{} has no historical data".format(symbol) continue except NameError as e: print "NameError: ", e except IndexError as e: print "IndexError: ", e except KeyboardInterrupt: raise except: print "GeneralError:", sys.exc_info()[0] continue f_all_data.close() f_yearly_data.close()
class Stock: """ """ def __init__(self, n): self.name = n self.confidence_list = [] self.fifty_day_moving_average = None self.two_hundred_day_moving_average = None self.price_earnings_growth_ratio = None self.confidence_string = None self.current_price = None self.stock = Share(self.name) def calculate_confidence_percentage(self): self.confidence_list = [] self.confidence_list.append(sc.formula_00_is_stock_above_50_day_moving_average(self.get_current_price(), self.get_fifty_day_moving_average())) self.confidence_list.append(sc.formula_01_is_stock_above_200_day_moving_average(self.get_current_price(), self.get_two_hundred_day_moving_average())) self.confidence_list.append(sc.formula_02_pattern_guesser_confidence_for_tomorrow(self.name)) confidence_string = '' for c in self.confidence_list: confidence_string += str(c) + ", " self.confidence_string = 'Confidence List: ' + confidence_string + '\tAverage Confidence: ' + str(sum(self.confidence_list) / len(self.confidence_list)) def get_name(self): """TODO:... :return: """ return self.name def get_current_price(self): if self.current_price is None: self.current_price = self.stock.get_price() def get_confidence_string(self): if self.confidence_string is None: self.calculate_confidence_percentage() return self.confidence_string def get_fifty_day_moving_average(self): if self.fifty_day_moving_average is None: self.fifty_day_moving_average = self.stock.get_50day_moving_avg() return self.fifty_day_moving_average def get_two_hundred_day_moving_average(self): if self.two_hundred_day_moving_average is None: self.two_hundred_day_moving_average = self.stock.get_200day_moving_avg() return self.two_hundred_day_moving_average def get_price_earnings_growth_ratio(self): if self.price_earnings_growth_ratio is None: self.price_earnings_growth_ratio = self.stock.get_price_earnings_growth_ratio() return self.price_earnings_growth_ratio
def get_quotes(self): self.debug("getting quotes") try: quotes = {} for i in self.assets: yahoo = Share(i) quotes[i] = {"source": "yahoo", "last": float(yahoo.get_price())} return quotes except OSError: self.error("Network Error")