def main(): ticker = str(raw_input("Stock Ticker: ")) company = Share(ticker) company.refresh() print company.get_name() print "Current Price: ", company.get_price()
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 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 search(request): stock = request.GET.get('put') flagvar = 0 try: symbol = Share(stock) stock_name = symbol.get_name() stock_data = symbol.get_historical('2016-01-01', date.today().strftime("%Y-%m-%d")) stock_df = pd.DataFrame(stock_data) abbr = stock_df['Symbol'][0] temp = pd.DataFrame({ 'Close_Price': [], 'Low': [], 'High': [], 'Date': [] }) temp['Date'] = stock_df['Date'] temp['High'] = stock_df['High'] temp['Low'] = stock_df['Low'] temp['Close_Price'] = stock_df['Adj_Close'] path = os.getcwd() filepath = path + os.sep + 'static' + os.sep + 'js' + os.sep + 'search' os.chdir(filepath) temp.to_csv(filepath + "/result.csv", index_label=False, index=False) os.chdir(path) flagvar = 1 except: flagvar = 0 abbr = '' stock_name = '' context = {'flag': flagvar, 'abbr': abbr, 'stock_name': stock_name} return render(request, 'search2.html', context)
def main(): """ Main example """ logging.info("--- SETTING UP IDENTIFIERS ---") asset_manager_id = random.randint(1, 2**31 - 1) calendar = Calendar() # This can fail if yesterday was a holiday - need to add a holiday calendar business_date = calendar.addbusdays(date.today(), -2) logging.info("Business Date: %s", business_date) business_date_str = business_date.isoformat() symbols = ['TWTR', 'AAPL', 'RBS.L', 'Z77.SI', '0008.HK'] logging.info("--- PULL MARKET DATA FROM YAHOO FINANCE ---") eod_prices = [] for symbol in symbols: share = Share(symbol=symbol) logging.info("Stock Name: %s", share.get_name()) close = (share.get_historical( start_date=business_date_str, end_date=business_date_str)[0].get('Close')) eod_price = EODPrice(asset_manager_id=asset_manager_id, asset_id=symbol, business_date=business_date, price=Decimal(close)) logging.info("EOD Price: %s", eod_price.price) eod_prices.append(eod_price) logging.info("--- PERSIST PRICES TO AMAAS ---") # Some of these attributes can be derived from the eod_prices - cleanup market_data_interface.persist_eod_prices(asset_manager_id=asset_manager_id, business_date=business_date, eod_prices=eod_prices, update_existing_prices=True)
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 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 collect_stock_data(symbol): """ Collect stock data for stock with symbol symbol :param symbol: symbol of stock to collect data for :return: dictionary containing stock data """ stock_data = dict() stock = Share(symbol) # check if symbol was for a valid stock name = stock.get_name() if name == 'N/A': return None stock_data['symbol'] = symbol stock_data['name'] = name # get all data between today and start of 21st century start_date = time.strftime("2000-01-01") end_date = time.strftime("%Y-%m-%d") stock_data['historical_data'] = stock.get_historical(start_date, end_date) # get dividend information stock_data['dividend_per_share'] = stock.get_dividend_share() stock_data['dividend_yield'] = stock.get_dividend_yield() # get volume information stock_data['avg_daily_volume'] = stock.get_avg_daily_volume() # primary key is the stock's symbol stock_data['_id'] = symbol return stock_data
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 historical(stocks): cnx = mysql.connector.connect(user='******', password='******', host='127.0.0.1', database='DBtest') cursor = cnx.cursor() databegining = raw_input( "Please type the begin date for the historical data" "in the format YYYY-MM-DD : ") datafinish = raw_input("Please type the last date for the historical data" "in the format YYYY-MM-DD : ") for i in stocks: print("Stock of " + i) stock = Share(i) # Provides the information on a Dictionary name = stock.get_name() history = stock.get_historical(databegining, datafinish) print("Getting the data for: " + i + " " + name) print("| Date | Opening | High | " " Low | Close | Volume |") for j in history: date = j['Date'] opening = j['Open'] high = j['High'] low = j['Low'] close = j['Close'] volume = j['Volume'] newrecord = (date + " | " + opening + " | " + high + " " "| " + low + " | " + close + " | " + volume) print(newrecord) # Don't forget to use the config file to avoid writing the password on the source add_realtime = ("INSERT INTO historical " "(tricker, date, open, high, low, close, volume) " "VALUES (%s, %s, %s, %s, %s, %s, %s)") data_realtime = (i, date, opening, high, low, close, volume) try: cursor.execute(add_realtime, data_realtime) cnx.commit() # Make sure data is committed to the database except mysql.connector.IntegrityError as err: #print(err) # Ussually a Duplicate value error pass print("Database sucessfuly udpated. ") cursor.close() cnx.close()
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() }
def getAllData(ticker): stock = Share(ticker) data = { 'name': stock.get_name(), 'price': stock.get_price(), 'open': stock.get_open(), 'prev_close': stock.get_prev_close() } return data
def 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_yahoo_csv(symbols, years_before): ''' INPUT: historical price for symbols in seleted period of time. OUTPUT: save as .csv file in each symbols. ''' days_before = years_before * 365 #trasfer years into days today = datetime.now().strftime('%Y-%m-%d') #make today as str date = datetime.now() - timedelta( days=days_before) #date is days before from today symbol = Share(symbols) sym = pd.DataFrame(symbol.get_historical(date.strftime('%Y-%m-%d'), today))[::-1] sym.columns = map(str.lower, sym.columns) sym.index = sym['date'] sym = sym.drop(['symbol', 'date'], axis=1) print("Inserted {} days {} data.".format(days_before, symbol.get_name())) sym.to_csv("{}.csv".format(symbol.get_name())) return sym
def portfolio_stocks(stocks): tickers = [] index = 0 for stock in stocks: names = [ 'Company Name', 'Ticker', 'Price', 'Market Cap', 'P/E Ratio', 'Earnings Yield', 'Div Yield', '50 Day MA', '200 Day MA', 'Price Target' ] ticker = Share(stock) comp_name = ticker.get_name() #company name tick = stock #ticker price = ticker.get_price() #price market_cap = ticker.get_market_cap() #market_cap pe = ticker.get_price_earnings_ratio() #gets pe as a string pe_two = float(pe) if pe else 0 #returns a float of the p/e if there is a result, otherwise returns 0 final_pe = pe_two if float(pe_two) > 0 else 0 #returns pe_two if > 0 else returns 0 EPS = ticker.get_EPS_estimate_current_year() # gets eps as a string final_eps = EPS if EPS else 0 #returns eps if there is a result, else returns 0 earn_yield = float(final_eps)/float(price) #returns float of earnings yield pos_ey = earn_yield if earn_yield > 0 else 0 #turns negitive numbers to 0 print(tick, 'earn yield', pos_ey) ey = round(pos_ey*100, 2) #returns in % format div = ticker.get_dividend_yield() #returns div in string final_div = 0 if div == None else float(div) #if no result returns 0 else returns float of div fifty = ticker.get_50day_moving_avg() #returns as string short_fifty = round(float(fifty), 2) #returns div with 2 decimal places two_hundred = ticker.get_200day_moving_avg() #returns as string short_two = round(float(two_hundred), 2) #returns float with 2 decimal places target = ticker.get_one_yr_target_price() #returns as string short_target = round(float(target), 2) values = [comp_name, tick, price, market_cap, final_pe, ey, final_div, short_fifty, short_two, short_target] final_values = list(zip(names, values)) index += 1 tickers.append(final_values) return tickers
def 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 CollectStockData(stock): today = datetime.date.today() five_years = today - datetime.timedelta(365 * 5 + 1) for i in range(3): try: share = Share(stock) if share.get_name() != None: longStock = share.get_historical(str(five_years), str(today))[::-1] longStock = pd.DataFrame(longStock) longStock = longStock.set_index( pd.DatetimeIndex(longStock['Date'])) del longStock['Date'] del longStock['Symbol'] longStock = longStock.apply(pd.to_numeric, errors='coerce') return longStock, share.get_name() except: print("Data not collected. Trying Again") return None, share.get_name()
def scraping_data(self): print('Scraping data...') yahoo = Share(self.ticker) yahoo.refresh() print(yahoo.get_name()) self.total_data = yahoo.get_historical('2017-07-11', '2017-07-12') for data in self.total_data: row = [data['Date'], data['Adj_Close']] self.writer.writerow(row) self.csv_file.close() print('\nAll done successfully!!!')
def get_current_stock_info(stock_short): stock_share = Share(stock_short) stock_current_info = {} stock_current_info['stock_short'] = stock_short stock_latest_price = stock_share.get_price() stock_current_info['stock_latest_price'] = stock_latest_price stock_trade_datetime = stock_share.get_trade_datetime() stock_current_info['stock_trade_datetime'] = stock_trade_datetime stock_exchange = stock_share.get_stock_exchange() stock_current_info['stock_exchange'] = stock_exchange stock_company_name = stock_share.get_name() stock_current_info['stock_company_name'] = stock_company_name return stock_current_info
def _get_stocks(self, name, value, units): value = Numeric.to_float(value) if value is None: return self.speak('I don\'t recognize that number.') if units not in ('day', 'days', 'week', 'weeks'): return self.speak('I don\'t recognize that unit.') end = datetime.now() start = datetime.now() if units == 'days' or units == 'day': start -= timedelta(days=value) elif units == 'weeks' or units == 'week': start -= timedelta(weeks=value) stock = Share(name) full_name = stock.get_name() if full_name is None: return self.speak('I cannot find stocks for that company.') else: self.speak('Fetching stock data for {}.'.format(full_name)) try: data = stock.get_historical(start.strftime('%Y-%m-%d'), end.strftime('%Y-%m-%d')) except (ValueError, YQLResponseMalformedError): return self.speak('Error while fetching data.') points = [point['Close'] for point in data] image = BytesIO() plt.plot(points) plt.axis('off') plt.savefig(image, bbox_inches='tight', format='svg') image.seek(0) tree = etree.parse(image) root = tree.getroot() for group in root.iter('{http://www.w3.org/2000/svg}g'): if group.attrib['id'] == 'patch_1': parent = root.findall('.//{http://www.w3.org/2000/svg}g[@id="patch_1"]...')[0] parent.remove(group) image = BytesIO() tree.write(image) image.seek(0) self._draw(image)
def calculate(stock,data=None): s = Share(stock) ticker = stock.lower() +".csv" try: f = pd.read_csv(ticker) except: url="https://www.google.com/finance/historical?output=csv&q="+ticker stock=ticker+".csv" urllib.request.urlretrieve(url,stock) f=pd.read_csv(stock) volumes = list(f['Volume']) average = sum(volumes)/len(volumes) if data==None or data==1: pertinent = [volumes.index(x) for x in volumes if x>= average] else: pertinent = [volumes.index(x) for x in volumes if x>= average][:data] prices = list(f['Close']) #ignore the low volume price prices_pert = [prices[i] for i in pertinent[::-1]] svr_lin = SVR(kernel= 'linear', C= 1e3) X=np.arange(1,len(prices_pert)+1,1.0) X=np.reshape(X,(len(X),1)) y=prices_pert y_lin = svr_lin.fit(X, y).predict(X) diff = [(y_lin[x]-y[x])/y_lin[x] for x in range(len(y))] #support coefficient bpd = max(diff) #resistance coefficient spd = min(diff) volatility = bpd-spd print("volatiliy: %.3f" %(volatility)) y_supp = [ i*(1-bpd) for i in y_lin ] y_res = [ i*(1+abs(spd)) for i in y_lin ] plt.title(s.get_name()) plt.plot(y_lin) plt.plot(y) plt.plot(y_supp,label="Support") plt.plot(y_res,label="resistance") plt.legend() plt.show() buying_point = diff.index(max(diff)) gain = y[-1]/y[buying_point] return len(pertinent)
def drawChart(self): #setup data stream label = self.symbol now = (time.strftime("%Y-%m-%d")) yahooObject = Share(self.symbol) dataStream = yahooObject.get_historical(str('2015-01-01'), str(now)) currPrice = yahooObject.get_price() fullName = yahooObject.get_name() #setup graphics x_interval = (self.width / len(dataStream)) #start a lof of data operations to normalize the data points chartData = normalizeData(dataStream, self.height) #declare canvas 1/2 of width w = Canvas(root, width=(self.width), height=self.height, bg="black", bd=2) startX = 0 startY = chartData[0] for value in chartData: endY = value endX = startX + x_interval if (startY > endY): color = "green" else: color = "red" w.create_line(startX, startY, endX, endY, fill=color, smooth="true", width=3) startX = endX startY = endY avg = float(sum(chartData)) / len(chartData) w.create_text(self.width / 3, avg, text=fullName + " " + currPrice, font="Helvetica", fill="white") w.grid(column=0)
def scraping_data(self): for key in self.tickers: yahoo = Share(key) print(key + ": saving data...") #print(yahoo.get_name(), yahoo.get_price(), yahoo.get_trade_datetime()) row = [ key, yahoo.get_name(), yahoo.get_trade_datetime(), yahoo.get_price() ] self.writer.writerow(row) self.csv_file.close() print('\nAll done successfully!!!')
def GetInfo(company): companyinfo = {} dictIS = IncomeStatement(company) dictBS = BalanceSheet(company) dictKR = KeyRatios(company) dictionaries = [dictIS, dictBS, dictKR] companyinfo['EXR'] = ExchangeRate(dictIS['currency']) # price and market capitalization share = Share(company) companyinfo['quote'] = share.get_price() companyinfo['MC'] = float(share.get_market_cap()[:-1]) companyinfo['name'] = share.get_name() for dictionary in dictionaries: # merge dictionaries companyinfo.update(dictionary)
def evalStocks(i): global f3 dates = [] values = [] count = 0 processed_text = i.upper() stock = Share(processed_text) sName = stock.get_name() for value in stock.get_historical('2006-06-12', '2017-03-15'): if count == 1: #print value['Date'] + " | " + value['Close'] + " \n" dates.insert(0, value['Date']) values.insert(0, float(value['Close'])) f3.write(str(value['Close']) + "\n") count = 0 count = count + 1 printStocks(dates, values, sName)
def stocks(dict_response): message = "" try: query_text = dict_response['_text'].lower() if query_text.find("stocks ") != -1: query_text = query_text[7:] y = Share(query_text) message += "Trading information for " + y.get_name( ) + " (" + query_text + ") :\n" message += "Opened: " + y.get_open() + "\n" message += "Current: " + y.get_price() + "\n" message += "Earnings share: " + y.get_earnings_share() + "\n" message += "Short ratio: " + y.get_short_ratio() + "\n" message += "Previous close: " + y.get_prev_close() + "\n" except: message = technical_issues() return message
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 bot_action(c, symbol): stock = Share(symbol) # Link stock with yahoo_finance module print(stock) if stock.get_price() == None: main() #print(stock.get_price()) head = 'Up to date stock info for **${0}** ({1}):\n\n'.format(symbol.upper(), stock.get_name()) price = '**Price:** ${0:.2f}\n\n'.format(float(stock.get_price())) price_open = '**Open:** ${0:.2f}\n\n'.format(float(stock.get_open())) change = '**Change:** {0:.2f} ({1})\n\n'.format(float(stock.get_change()), stock.get_percent_change()) vol = '**Volume:** {0:,.2f}\n\n'.format(float(stock.get_volume())) market_cap = '**Mkt Cap:** {0}\n\n'.format(stock.get_market_cap()) average = '**Average (50 day):** {0:.2f}\n\n'.format(float(stock.get_50day_moving_avg())) exchange = '**Exchange:** {0}\n\n'.format(stock.get_stock_exchange()) divider = '-----------------------------------------------------------------------------------------\n\n' tail = "Don't abuse me, robots have feelings too! | [Source Code](https://github.com/Logicmn/Reddit-Stock-Bot) " \ "| [Report Bug](https://www.reddit.com/message/compose/?to=Pick-a-Stock) " \ "| [Suggest Feature](https://www.reddit.com/message/compose/?to=Pick-a-Stock)" c.reply(head + divider + price + price_open + change + vol + market_cap + average + exchange+ divider + tail)
def get_symbol_yahoo_stats_yql(symbols, exclude_name=False): """ Get the symbols' basic statistics from Yahoo Finance. Input: symbols - a list of symbol strings, e.g. ['AAPL'] Output: stats in Pandas DataFrame. This function is ported from pandas_datareader/yahoo/components.py """ sym_list = str2list(symbols) if sym_list == None: return DataFrame() # Yahoo Finance tags, refer to http://www.financialwisdomforum.org/gummy-stuff/Yahoo-data.htm tags = ['Symbol'] if not exclude_name: tags += ['Name'] tags += ['Exchange', 'MarketCap', 'Volume', 'AverageDailyVolume', 'BookValue', 'P/E', 'PEG', 'Price/Sales', 'Price/Book', 'EBITDA', 'EPS', 'EPSEstimateNextQuarter', 'EPSEstimateCurrentYear', 'EPSEstimateNextYear', 'OneyrTargetPrice', 'PriceEPSEstimateCurrentYear', 'PriceEPSEstimateNextYear', 'ShortRatio', 'Dividend/Share', 'DividendYield', 'DividendPayDate', 'ExDividendDate'] lines = [] for sym in sym_list: stock = Share(sym) line = [sym] if not exclude_name: line += [stock.get_name()] line += [stock.get_stock_exchange(), str2num(stock.get_market_cap(), m2b=True), str2num(stock.get_volume()), str2num(stock.get_avg_daily_volume()), str2num(stock.get_book_value()), str2num(stock.get_price_earnings_ratio()), str2num(stock.get_price_earnings_growth_ratio()), str2num(stock.get_price_sales()), str2num(stock.get_price_book()), str2num(stock.get_ebitda()), str2num(stock.get_earnings_share()), str2num(stock.get_EPS_estimate_next_quarter()), str2num(stock.get_EPS_estimate_current_year()), str2num(stock.get_EPS_estimate_next_year()), str2num(stock.get_one_yr_target_price()), str2num(stock.get_price_EPS_estimate_current_year()), str2num(stock.get_price_EPS_estimate_next_year()), str2num(stock.get_short_ratio()), str2num(stock.get_dividend_share()), str2num(stock.get_dividend_yield()), stock.get_dividend_pay_date(), stock.get_ex_dividend_date()] lines.append(line) stats = DataFrame(lines, columns=tags) stats = stats.drop_duplicates() stats = stats.set_index('Symbol') return stats
def run_analysis(): """ Run analysis on the current global ticker list :return: """ global ticker_list if len(ticker_list) == 0: print("No stocks in current ticker list") return for ticker in ticker_list: stock = Share(ticker) print(line_separator) print("Name: " + str(stock.get_name())) print("Open: " + str(stock.get_open())) print("Price: " + str(stock.get_price())) # print("Time :" + str(stock.get_trade_datetime())) # print("Earnings Share :" + str(stock.get_earnings_share())) # print("EPS Estimate :" + str(stock.get_EPS_estimate_next_quarter())) print(line_separator)