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 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_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 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 handle(text, mic, profile): positions = open('/home/pi/.jasper/config.txt', 'r') total_change = 0 for position in positions.readlines(): if '#' in position: pass else: x = position.split(':') stock = Share(str(x[0])) change = float(stock.get_change().strip('+')) shares = float(x[1]) #print x[0] + ' ' + str(change) + ' ' + str(shares) + ' ' + str(change * shares) total_change += (change * shares) #print("$%.2f" % round(total_change, 2)) change = ("%.2f" % round(total_change, 2)) if change[0] == '-': updown = 'down' else: updown = 'up' change = change[1:len(change)] change = change.split('.') tens = str(change[0]) ones = str(change[1]) #print 'Your stocks are ' + updown + ' ' + tens + ' dollars and ' + ones + ' cents on the day.' sentence = 'Your stocks are ' + updown + ' ' + tens + ' dollars and ' + ones + ' cents on the day.' mic.say(sentence)
def getPrice(): input = json.dumps(request.json) data = input print(data) symbolT = request.json['symbol'] finalResult["errMsg"] = "None" try: company = get_symbol(symbolT.upper()) if company == "NetworkError" or company == "InvalidSymbol": finalResult["errMsg"] = company else: #output dt = datetime.datetime.now(tzlocal.get_localzone()) finalResult["time"] = dt.strftime("%a %b %d %H:%M:%S %Z %Y") finalResult["company"] = company + " (" + symbolT.upper() + ") " stock = Share(symbolT) finalResult["stockInfo"] = stock.get_price( ) + " " + stock.get_change() + " (" + stock.get_percent_change( ) + ") " except ValueError: finalResult["errMsg"] = "SystemError" jsonResult = json.dumps(finalResult) return jsonResult
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 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 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 set_ETF_data(): etf_data = [] for index, etf_symbol in enumerate(settings.ETF_MASTER_LIST): etf_dict = { 'model': 'portfolio.ETF', 'pk': index + 1, 'fields': {}, } fund = Share(etf_symbol) fields = { 'name': fund.get_name(), 'symbol': etf_symbol, 'last_trade': fund.get_price(), 'dividend_yield': fund.get_dividend_yield(), 'absolute_change': fund.get_change(), 'percentage_change': fund.get_percent_change(), 'year high': fund.get_year_high(), 'year low': fund.get_year_low(), '50 day moving average': fund.get_50day_moving_avg(), '200 day moving average': fund.get_200day_moving_avg(), 'average_daily_volume': fund.get_avg_daily_volume() } etf_dict['fields'] = fields etf_data.append(etf_dict) json_data = json.dumps(etf_data) # print(json_data) output_dict = [y for y in etf_data if y['fields']['dividend_yield'] > 1] output_dict = [ x for x in output_dict if x['fields']['average_daily_volume'] > 100000 ] output_dict = [ z for z in output_dict if z['fields']['200 day moving average'] < z['fields']['last_trade'] ] sorted_list = sorted(output_dict, key=lambda k: k['fields']['dividend_yield'], reverse=True) for etf in sorted_list[:5]: ETF.objects.create( portfolio=Portfolio.objects.get(pk=1), name=etf['fields']['name'], symbol=etf['fields']['symbol'], investment_style=1, last_trade=etf['fields']['last_trade'], dividend_yield=etf['fields']['dividend_yield'], absolute_change=etf['fields']['absolute_change'], percentage_change=etf['fields']['percentage_change'], currency='USD', last_updated=timezone.now())
def 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 update_ETF_value(self): fund = Share(self.symbol) self.last_trade = fund.get_price() self.absolute_change = fund.get_change() self.percentage_change = fund.get_percent_change() self.dividend_yield = fund.get_dividend_yield() self.last_updated = timezone.now() self.save()
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 stock(message): ticker = Share(message) ticker.refresh() quote = ticker.get_price() if quote is None: resp = str(message) + " is not a valid ticker symbol" else: change = ticker.get_change() resp = message + ": " + quote + " " + change __send_response(resp, icon_money) quote = ""
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_stock_prices(stocks): data = [] for s in stocks: stock_data = {} share = Share(s) percent_change = round(float(share.get_change()) / float(share.get_prev_close()) * 100, 2) stock_data['symbol'] = s stock_data['price'] = round(float(share.get_price()), 2) stock_data['change_percent'] = percent_change data.append(stock_data) return data
def getStockInfoNow(request): if request.method == 'GET': sid = request.GET['sid'] try: s = Share(sid+'.TW') p = float(s.get_price()) c = float(s.get_change()) v = float(s.get_volume())/1000 pc = float(s.get_prev_close()) except: return JsonResponse({"success": 'false', 'error': 'wrong sid'}) return JsonResponse({'price': p, 'change': c, 'volume': v, 'prev_close': pc}) else: return JsonResponse({"success": 'false', 'error': 'wrong method'})
def get_symbol_info(self, symbol): yahoo = Share(symbol) name = symbol 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())) 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 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 lookup2(symbol): try: share = Share(symbol) except: return None if share.get_name() is None: return None return { "name": share.get_name(), "symbol": symbol.upper(), "price": share.get_price(), "change": share.get_change(), "pc_change": share.get_percent_change(), "trade_time": share.get_trade_datetime() }
class TickerData: def __init__(self, ticker_symbol): self._name = ticker_symbol self._yahoo = None self._google = None self._csv_data = HistoricCsvFile(ticker_symbol) if self._csv_data.is_google_data(): self._google = googlefinance.getQuotes(ticker_symbol)[0] #print (json.dumps(self._google, indent=2)) else: self._yahoo = Share(ticker_symbol) def get_name(self): return self._name def get_long_name(self): return self._yahoo.get_name() if self._yahoo else self._name def get_last_price(self): return self._yahoo.get_price( ) if self._yahoo else self._google['LastTradePrice'] def get_last_trade_datetime(self): return self._yahoo.get_trade_datetime( ) if self._yahoo else self._google['LastTradeDateTime'] def get_price_change(self): return self._yahoo.get_change( ) if self._yahoo else self._google['ChangePercent'] def get_price_open(self): return self._yahoo.get_open( ) if self._yahoo else self._google['PreviousClosePrice'] def get_percent_change(self): return self._yahoo.get_percent_change( ) if self._yahoo else get_ratio_percent(self.get_last_price(), self.get_price_open()) def get_yahoo(self): return self._yahoo def get_csv_data(self): return self._csv_data
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 getStockInfoNow(request): if request.method == 'GET': sid = request.GET['sid'] try: s = Share(sid + '.TW') p = float(s.get_price()) c = float(s.get_change()) v = float(s.get_volume()) / 1000 pc = float(s.get_prev_close()) except: return JsonResponse({"success": 'false', 'error': 'wrong sid'}) return JsonResponse({ 'price': p, 'change': c, 'volume': v, 'prev_close': pc }) else: return JsonResponse({"success": 'false', 'error': 'wrong method'})
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 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 makeList(self): Stock_list = [] for stock in self.Exchange: try: yahoo = Share("%s" % stock) price_open = yahoo.get_open() if price_open is not None: if float(price_open) < 15: change = yahoo.get_change() try: stock = stock.split(" ")[0] except: pass info = ("%s: $%s, %s" % (stock, price_open, change)) print(info) Stock_list.append([stock, price_open]) except: pass Stock_list = sorted(Stock_list) ## Creates Text File sys.stdout = open('15Below%s.txt' % self.ExchangeName, 'w')
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()
cba = Share("CBA.ax") nab = Share("NAB.ax") anz = Share("ANZ.ax") wbc = Share("WBC.ax") # westpac # retail wow = Share("WOW.ax") jbh = Share("JBH.ax") # jb hifi wes = Share("WES.ax") # west farmer # misc asx = Share("ASX.ax") bhp = Share("BHP.ax") ccl = Share("CCL.ax") # coca cola dmp = Share("DMP.ax") # domino pizza price = [cba.get_price(), nab.get_price(), anz.get_price(), wbc.get_price(), wow.get_price(), jbh.get_price(), wes.get_price(), asx.get_price(), bhp.get_price(), ccl.get_price(), dmp.get_price()] volume = [cba.get_volume(), nab.get_volume(), anz.get_volume(), wbc.get_volume(), wow.get_volume(), jbh.get_volume(), wes.get_volume(), asx.get_volume(), bhp.get_volume(), ccl.get_volume(), dmp.get_volume()] change = [cba.get_change(), nab.get_change(), anz.get_change(), wbc.get_change(), wow.get_change(), jbh.get_change(), wes.get_change(), asx.get_change(), bhp.get_change(), ccl.get_change(), dmp.get_change()] print "ASX overall price:", asx.get_price() # write to data.json counter = 0 def appendData(name): with open('data.json', 'r+') as f: global counter json_data = json.load(f) json_data["price"][name].append(float(price[counter])) f.seek(0) f.write(json.dumps(json_data)) f.truncate() json_data["volume"][name].append(float(volume[counter])) f.seek(0) f.write(json.dumps(json_data)) f.truncate()
# Give me a list of symbols in the S&P500 that are down more than 10% in one day. # # Joey <*****@*****.**> # pip install yahoo-finance # pip install finsymbols from finsymbols import get_sp500_symbols from yahoo_finance import Share sp500 = get_sp500_symbols() for d in sp500: symbol = d['symbol'] #print "Checking: %s" % symbol stockblob = Share(symbol) close = stockblob.get_prev_close() close = float(close) change = stockblob.get_change() change = float(change) if change < 0: # Negative number (stock is down) change = abs(change) percent = (change / close) * 100 if percent > 10: # Down more than 10%, looks interesting. print "%s is down %s" % (symbol, percent)
subrealtimequote = realtime.scraper(myargs.ticker) output.append(subrealtimequote) if myargs.price is True: price = stock.get_price() print price if myargs.volume is True: volume = stock.get_volume() output.append(volume) selections.append('Volume: ') print output if myargs.change is True: change = stock.get_change() output.append(change) selections.append('Change: ') print change if myargs.avgvol is True: avgvolume = stock.get_avg_daily_volume() print avgvolume if myargs.short is True: short = stock.get_short_ratio() print short if myargs.peratio is True: pe = stock.get_price_earnings_ratio() print pe
#set to 0 if you don't want to see trade time in the drop-down menu times = 1 #set to 0 if you don't want to see a link to your Yahoo Finance portfolio portfolio = 1 try: for i in stocks: price = Share(i) name = i if len(i) > 4: name = i[:4] price2 = price.get_price() if len(price2) > 6: price2 = price2[:6] change = price.get_change() if change == None: change = "0.00" elif len(change) > 5: change = change[:5] print(name + ": " + price2 + " (", end="") if change[:1] == "+": print("\033[1;32m" + change + "\033[0m) | href='https://ca.finance.yahoo.com/quote/" + i + "' refresh=true") elif change[:1] == "-": print("\033[1;31m" + change + "\033[0m) | href='https://ca.finance.yahoo.com/quote/" + i + "' refresh=true") elif change[:1] == "0": print("0.00) | href='https://ca.finance.yahoo.com/quote/" + i +
def get_close_ticker(self): date = datetime.datetime.now() weekday = date.weekday() if (datetime.time(16,00,30) < date.time() < datetime.time(16,01,30)) and (weekday != 5 or weekday != 6) and (self.posted_close == None or self.posted_close < 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_prev_close(), stock_info.get_change())) self.posted_close = date.date() return ' - '.join(stock_prices)
def query_change(ticker): from yahoo_finance import Share company = Share(ticker) change = float(company.get_change()) return change
from yahoo_finance import Share inp = open('input.txt', 'r') out = open('output.txt', 'w') for line in inp: temp = Share(line) temp.refresh() out.write(line.rstrip("\n") + "," + temp.get_price() + "," + temp.get_change() + "\n") #FORMAT: Symbol, last closing price, last change temp = Share('FUSVX') print(temp.get_stock_exchange())
from yahoo_finance import Share positions = open('config.txt', 'r') total_change = 0 for position in positions.readlines(): if '#' in position: pass else: x = position.split(':') stock = Share(str(x[0])) change = float(stock.get_change().strip('+')) shares = float(x[1]) total_change += (change * shares) print("$%.2f" % round(total_change, 2))
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
def getStocksFromSource(indexes=data, sortBy=SORT_BY_TOP): ''' ''' stocks = [] index = ['AGTC'] # for stock in data["Ticker"][:100]: # for stock in index: for stock in data: try: print(stock) # print(type(stock)) yf_data = yqd.load_yahoo_quote(stock, '20170301', '20170830') # yf_data = yqd.load_yahoo_quote('ABEO', '20170712', '20170725') # print(yf_data) share = Share(stock) # history part history = [] for i, day in enumerate(yf_data[1:-1]): daily_data = day.split(',') history.append([ i, str(daily_data[0]), float(daily_data[1]), float(daily_data[2]), float(daily_data[3]), float(daily_data[4]), float(daily_data[6]) ]) # print(history) # comments part comments = [] new_StockTwits_comments = [] url = 'https://api.stocktwits.com/api/2/streams/symbol/{0}.json'.format( stock) print(url) try: r = requests.get(url).json() print(len(r['messages'])) for message in r['messages']: try: new_tweet = { 'id': message['id'], 'body': message['body'], 'created_at': message['created_at'], 'core_body': nltk_service.clean_tweet(message['body']), 'nltk_sentiment': nltk_service.get_tweet_sentiment(message['body']), # 'azure_sentiment': azure_sentiment_service.GetSentiment(message['body']) } try: new_tweet[ 'azure_sentiment'] = azure_sentiment_service.GetSentiment( message['body']) except Exception as e: new_tweet['azure_sentiment'] = 0.5 print(e) # print(new_tweet['azure_sentiment']) new_StockTwits_comments.append(new_tweet) except Exception as e: print(e) # pass except Exception as e: print('stock tweets part problem') print(e) # new_StockTwits_comments = [{'id': message['id'], 'body': message['body'], 'created_at': message['created_at']} for message in r['messages']] print(len(new_StockTwits_comments)) stock = { 'index': stock, 'open': share.get_open(), 'change': share.get_change(), 'percent_change': share.get_percent_change(), 'prev_close': share.get_prev_close(), 'price': share.get_price(), 'volume': share.get_volume(), 'history': history, 'new_StockTwits_comments': new_StockTwits_comments } # stock_json = json.dumps(stock) # print(type(stock_json)) print(len(history)) if len(history) != 0: # f.write(stock['index']+'/n') stocks.append(stock) except Exception as e: print(e) pass print(len(stocks)) return stocks # f.close() # get_price() # get_change() # get_percent_change() # get_volume() # get_prev_close() # get_open() # get_avg_daily_volume() # get_stock_exchange() # get_market_cap() # get_book_value() # get_ebitda() # get_dividend_share() # get_dividend_yield() # get_earnings_share() # get_days_high() # get_days_low() # get_year_high() # get_year_low() # get_50day_moving_avg() # get_200day_moving_avg() # get_price_earnings_ratio() # get_price_earnings_growth_ratio() # get_price_sales() # get_price_book() # get_short_ratio() # get_trade_datetime() # get_historical(start_date, end_date) # get_name() # refresh() # get_percent_change_from_year_high() # get_percent_change_from_year_low() # get_change_from_year_low() # get_change_from_year_high() # get_percent_change_from_200_day_moving_average() # get_change_from_200_day_moving_average() # get_percent_change_from_50_day_moving_average() # get_change_from_50_day_moving_average() # get_EPS_estimate_next_quarter() # get_EPS_estimate_next_year() # get_ex_dividend_date() # get_EPS_estimate_current_year() # get_price_EPS_estimate_next_year() # get_price_EPS_estimate_current_year() # get_one_yr_target_price() # get_change_percent_change() # get_dividend_pay_date() # get_currency() # get_last_trade_with_time() # get_days_range() # get_year_range()
russell3000['Price sales']=pd.Series(-1,index=russell3000.index) russell3000['Price book']=pd.Series(-1,index=russell3000.index) russell3000['Short ratio']=pd.Series(-1,index=russell3000.index) russell3000.set_index('Ticker',inplace=True) for s in russell3000.index.values: print "Retrieving data for", s try: shy=Share(s) except: continue try: russell3000.set_value(s,'Price',shy.get_price()) except: pass try: russell3000.set_value(s,'Change',shy.get_change()) 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:
def get_info(ticker): # rjson = get_json(ticker) info = {} try: stock = Share(ticker) # 0: Get name url = "http://d.yimg.com/autoc.finance.yahoo.com/autoc?query={}®ion=1&lang=en".format(ticker) print("Ticker: ", ticker) result = requests.get(url).json() for x in result['ResultSet']['Result']: if x['symbol'] == ticker: info['name'] = truncate(x['name']) if info['name'] == "" or info['name'] == None: raise ValueError('Did not obtain a real value!') # 1: Get price # info['price'] = float(rjson[0][u'l']) info['price'] = get_price(ticker) if info['price'] == 0 or info['price'] == None: raise ValueError('Did not obtain a real value!') # 2: Get datetime # info['datetime'] = rjson[0][u'lt'] info['datetime'] = getdatetime(ticker) if info['datetime'] == "" or info['datetime'] == None: raise ValueError('Did not obtain a real value!') # 3: Get gain # change = rjson[0][u'c'] # if change is None: # info['gain'] = 0 # c = change.split("+") # if (len(c) > 1): # info['gain'] = float(c[1]) # info['gain'] = float(change) change = stock.get_change() if change is None: info['gain'] = 0 else: info['gain'] = float(stock.get_change()) if info['gain'] == None: raise ValueError('Did not obtain a real value!') # 4: Get percent change # info['percentchange'] = float(rjson[0][u'cp']) try: percentChange = stock.get_percent_change() percentChange = percentChange.split("%")[0] if len(percentChange.split("+")) > 1: percentChange = percentChange.split("+")[1] elif len(percentChange.split("-")) > 1: percentChange = percentChange.split("-")[1] info['percentchange'] = float(percentChange) except: info['percentchange'] = stock.get_percent_change() if info['percentchange'] == None: raise ValueError('Did not obtain a real value!') except: if db.session.query(Stock).filter_by(ticker = ticker).count() > 0: found_stock = db.session.query(Stock).filter_by(ticker = ticker).first() info['name'] = found_stock.name info['price'] = found_stock.price info['datetime'] = found_stock.datetime info['gain'] = found_stock.change info['percentchange'] = found_stock.percentChange else: info['name'] = "N/A" info['price'] = 0.00 info['datetime'] = "N/A" info['gain'] = 0.00 info['percentchange'] = 0.00 return info
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)
def print_menu(menuid, errorid): global selected_Ticker namesTicker = ["Stocks", "Exchanges", "Catagory", "Number Selection"] if selected_Ticker is not None: print("Selected:\t"+selected_Ticker.name) print("Type:\t\t"+namesTicker[selected_Ticker.typeof]) if selected_Ticker.typeof == 0: stock = Share(selected_Ticker.name) stock.refresh() print(stock.get_info()) print(stock.get_price()) print(stock.get_change()) print(stock.get_volume()) print("\n\n") if menuid == 0: print("------Menu------") print(" (e) exit") print(" (l) list") print(" (s) stats") error(errorid) elif menuid == 1: print("------Stats Menu------") print(" (a) all") print(" (u) uniques") print(" (b) back") if selected_Ticker is not None: print(" (r) run data collector") print(" (c) clear") error(errorid) elif menuid == 2: print("------All Data Menu------") print(" (e) exchanges") print(" (c) catagories") print(" (n) catagory Number") print(" (b) back") error(errorid) elif menuid == 3: print("------Unique Menu------") print(" (s) stock") print(" (e) exchange") print(" (c) catagories") print(" (n) catagory Number") print(" (b) back") error(errorid) elif menuid == 4: print("------Stock Tickers Selection------") exchanges_display(0) error(errorid) elif menuid == 5: print("------Exchanges Selection------") exchanges_display(1) error(errorid) elif menuid == 6: print("------Catagory Selection------") exchanges_display(2) error(errorid) elif menuid == 7: print("------Number Catagory Selection------") exchanges_display(3) error(errorid)
def get_stockprice(self, sym): stock = Share(sym) if stock: return "%s (%s): $%s [%s]" % (stock.symbol.upper(), stock.data_set['Name'], stock.get_price(), stock.get_change())
db = MySQLdb.connect("localhost","root","godawgs","Stocks") c = db.cursor() date = datetime.datetime.now() for line in data: try: share = line.split("|")[0] yahoo = Share(share) stockname = line.split("|")[1].split(" - ")[0] ticker = share price = str(yahoo.get_price()) change = str(yahoo.get_change()) print price + " " + stockname if stockname not in namelist: c.execute('''INSERT INTO HistoricalData (stockticker, price, dayending) values (%s, %s, %s)''', (ticker, price, str(date))) c.execute('''UPDATE NYSE SET price=%s, updatetimestamp=%s,delta=%s WHERE stockticker=%s''', (price, str(date),change, ticker)) db.commit() namelist.append(stockname) except AttributeError: print "" except TypeError: print "" db.commit()
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")
return "None" #accept input while True: try: print("Input : ") symbolT = input("Please enter a symbol : ") company = get_symbol(symbolT.upper()) while company.lower() in ("none", "networkerror"): if company == "NetworkError": exit() symbolT = input("Invalid Symbol. Please enter a valid symbol : ") company = get_symbol(symbolT.upper()) #display output print("\nOutput : ") dt = datetime.datetime.now(tzlocal.get_localzone()) print(dt.strftime("%a %b %d %H:%M:%S %Z %Y")) print(company + " (" + symbolT.upper() + ") ") stock = Share(symbolT) print(stock.get_price() + " " + stock.get_change() + " (" + stock.get_percent_change() + ") ") print("---------------------------------------------") cont = input("Do you want to continue? (Y/N) : ") if cont == 'Y' or cont == "y": continue else: break except ValueError: print("\nWrong Input! Please try again.")