def create_sector_classification_file(**kwargs): file_name = directory_name + '\sector_classification.pkl' if os.path.isfile(file_name): return pd.read_pickle(file_name) if 'report_date' in kwargs.keys(): report_date = kwargs['report_date'] else: report_date = exp.doubledate_shift_bus_days() symbol_list = ssd.get_symbol_list_4date(settle_date=report_date) for i in range(len(symbol_list)): eqty = Equity(symbol_list[i]) try: sector_list.append(eqty.sector) industry_list.append(eqty.industry) except: sector_list.append(None) industry_list.append(None) sector_classification = pd.DataFrame.from_dict({'ticker': symbol_list, 'sector': sector_list, 'industry': industry_list}) sector_classification.to_pickle(file_name) return sector_classification
def get_vg_ticker_info(equity_file, days): with open(equity_file, 'r') as f: excluded_industry = ['Oil & Gas', 'REIT', 'Biotechnology'] for line in f: # Skip if line has 'ETF', 'FUND', 'TRUST', 'THERA', 'PHARMA' ticker = re.search(r'\((.*?)\)',line).group(1) if ticker: #rb_client = robinhood.Equity(ticker) yahoo_ticker = Equity(ticker) yahoo_equity_summary = yahoo_info.get_summary(ticker) profile = yahoo_ticker.profile price = float(yahoo_equity_summary['Open']) if profile is None or price >= 50: continue market_cap = yahoo_equity_summary.get('Market Cap', None) if market_cap: if yahoo_equity_summary['Market Cap'].endswith('M'): data = re.split(r'(\d+)', yahoo_equity_summary['Market Cap'])[1] if int(data) < 50: print "Skipping {} because of mkt cap below 50M".format(ticker) continue else: continue # Skip REIT industry = yahoo_ticker.industry if industry in excluded_industry: continue stocks.get_stock_info(ticker, days) click.pause(info="Press any key to continue...", err=False)
def __init__(self, ticker='AAPL'): self.ticker = ticker self.YF = yf(ticker) self.PF = Equity(ticker) self.date_str = dt.date.today().strftime('%Y-%m-%d') self.prices_dir = 'prices/prices_{}'.format(self.date_str) self.info_dir = 'info/info_{}'.format(self.date_str)
def store_company(): df = pd.read_csv('constituents.csv') aapl = Equity('AAPL') print(aapl.profile) for index, row in df.head(50).iterrows(): company_check = CompanyInfo.objects.filter( symbol=row['Symbol']).count() if company_check == 0: company = Equity(row['Symbol']) try: print(company.profile) newCompany = CompanyInfo(name=row['Name'], symbol=row['Symbol'], sector=company.profile['Sector'], website=company.profile['Website'], country=company.profile['Country']) newCompany.save() except: pass
def setUpClass(cls): cls.aapl = Equity('AAPL') cls.options = OptionChain(cls.aapl)
def setUpClass(cls): cls.aapl = Equity('AAPL') cls.date = datetime.date(2013, 1, 25)
def get_stock_info(ticker, name=None, days=None): """ Returns ticker info """ yahoo_ticker_obj = Equity(ticker) ticker_obj = etrade_api.Equity(etrade_acct_obj, ticker) if ticker_obj.quote_all is None: return None rb_client = robinhood.Equity(rh_acct_obj, ticker) if rb_client.equity_ticker is None: return None yahoo_summary_info = yahoo_info.get_summary(ticker) yahoo_equity_info = yahoo_info.get_stats(ticker) trade_date, end_date = get_end_date(days) trade_date = datetime.strptime(trade_date, '%Y-%m-%d').date() sma_10 = ticker_10_sma(ticker) #sma_10_p1 = multiprocessing.Process(target=ticker_10_sma, args=(ticker,)) #sma_10 = sma_10_p1.start() #sma_10_p1.join() sma_21 = ticker_21_sma(ticker) #sma_21_p1 = multiprocessing.Process(target=ticker_21_sma, args=(ticker,)) #sma_21 = sma_21_p1.start() #sma_21_p1.join() sma_50 = ticker_50_sma(ticker) #sma_50_p1 = multiprocessing.Process(target=ticker_50_sma, args=(ticker,)) #sma_50 = sma_50_p1.start() #sma_50_p1.join() sma_200 = ticker_200_sma(ticker) #sma_200_p1 = multiprocessing.Process(target=ticker_200_sma, args=(ticker,)) #sma_200 = sma_200_p1.start() #sma_200_p1.join() rsi = get_rsi(ticker) url = '{}/query?function=TIME_SERIES_DAILY&symbol={}&apikey={}'.\ format(host, ticker, AV_API_KEY) resp = session.get(url) try: resp.raise_for_status() except requests.HTTPError as e: raise StockHTTPError(e) data = resp.json() symbol_table = PrettyTable([ 'Name', 'Ticker', 'Sector', 'Industry', 'Date', 'Company Founded', 'CEO', 'IPO Date', 'Total Employee', 'Market Cap' ]) if name is not None: symbol_table.add_row([ name, data['Meta Data']['2. Symbol'], yahoo_ticker_obj.sector, yahoo_ticker_obj.industry, today, rb_client.company_founded, rb_client.company_ceo, rb_client.company_ipo_date, rb_client.company_employees_total, market_cap(rb_client.market_cap) ]) #click.echo("Name: {}".format(name)) else: symbol_table.add_row([ 'None', data['Meta Data']['2. Symbol'], yahoo_ticker_obj.sector, yahoo_ticker_obj.industry, today, rb_client.company_founded, rb_client.company_ceo, rb_client.company_ipo_date, rb_client.company_employees_total, market_cap(rb_client.market_cap) ]) #symbol_table.add_row(['None', data['Meta Data']['2. Symbol'], yahoo_ticker_obj.sector, yahoo_ticker_obj.industry, today]) #click.echo("Ticker: {}, Sector: {}, Industry:{}, Date: {}".\ # format(click.style(data['Meta Data']['2. Symbol'], fg='red'), # yahoo_ticker_obj.sector, yahoo_ticker_obj.industry, # today)) click.echo(symbol_table) click.echo("Company Summary: {}".format(rb_client.company_info)) price_data = data['Time Series (Daily)'] close_price_list = [] sorted_price_data = collections.OrderedDict( sorted(price_data.items(), reverse=True)) ticker_table = PrettyTable([ 'Date', 'Open Price', 'Close price', 'High ($)', 'Low ($)', 'Fluctuate ($)', 'Fluctuate (%)', 'Change ($)', 'Change (%)', 'Volume(k)' ]) for k, v in sorted_price_data.items(): if ':' in k: k = datetime.strptime(k, '%Y-%m-%d %H:%M:%S').date() else: k = datetime.strptime(k, '%Y-%m-%d').date() prev_date = get_prev_close_date(k) prev_date_str = datetime.strftime(prev_date, '%Y-%m-%d') prev_close_date = price_data.get(prev_date_str, None) if prev_close_date is None: prev_date = get_prev_close_date(k - timedelta(days=1)) prev_date = datetime.strftime(prev_date, '%Y-%m-%d') if k < end_date: click.echo(ticker_table) #company_info_table = PrettyTable(['Company Founded', 'CEO', 'IPO Date', 'Total Employee', 'Market Cap']) #company_info_table.add_row([rb_client.company_founded, rb_client.company_ceo, rb_client.company_ipo_date, # rb_client.company_employees_total, market_cap(rb_client.market_cap)]) #click.echo(company_info_table) #click.echo("Company Founded: {}\t\tCEO: {}\tIPO date: {}\t\t" # "Total Employee: {}".format(click.style(str(rb_client.company_founded), fg='red'), # rb_client.company_ceo, click.style(rb_client.company_ipo_date, fg='red'), # rb_client.company_employees_total)) snap_ratio_table = PrettyTable([ 'PE', 'EPS', 'Estimated EPS', 'Trailing PE', 'Forward PE', 'P/S (ttm)', 'P/B (mrq)', 'Current Ratio (mrq)', 'Gross Profit(ttm)', 'Profit Margin', 'Operating Margin(ttm)', 'ROE', 'ROA' ]) snap_ratio_table.add_row([ rb_client.company_pe_ratio, ticker_obj.eps, ticker_obj.estEarnings, yahoo_equity_info['Trailing P/E'], yahoo_equity_info['Forward P/E 1'], yahoo_equity_info['Price/Sales (ttm)'], yahoo_equity_info['Price/Book (mrq)'], yahoo_equity_info['Current Ratio (mrq)'], yahoo_equity_info['Gross Profit (ttm)'], yahoo_equity_info['Profit Margin'], yahoo_equity_info['Operating Margin (ttm)'], yahoo_equity_info['Return on Equity (ttm)'], yahoo_equity_info['Return on Assets (ttm)'] ]) click.echo(snap_ratio_table) #click.echo("Market Cap: {}\tPE: {}\t\tEPS: {}\t\t\t" # "Dividend Yield: {}\t\tDividend Per Share: {}\t" # "Estimated EPS: {}".\ # format(market_cap(rb_client.market_cap), # click.style(str(rb_client.company_pe_ratio), fg='red'), # ticker_obj.eps, # ticker_obj.dividend, # ticker_obj.annualDividend, # ticker_obj.estEarnings)) snap_financial_table = PrettyTable([ 'Revenue per Share', 'Qtr Revenue Growth (yoy)', 'Qtr Earnings Growth (yoy)', 'Total Debt/Equity (mrq)', 'Book Value/Share (mrq)', 'Total Cash/Share (mrq)' ]) snap_financial_table.add_row([ yahoo_equity_info['Revenue Per Share (ttm)'], yahoo_equity_info['Quarterly Revenue Growth (yoy)'], yahoo_equity_info['Quarterly Earnings Growth (yoy)'], yahoo_equity_info['Total Debt/Equity (mrq)'], yahoo_equity_info['Book Value Per Share (mrq)'], yahoo_equity_info['Total Cash Per Share (mrq)'] ]) click.echo(snap_financial_table) #click.echo("Trailing PE: {}\t\tForward PE: {}\tP/S (ttm): {}\t\t\t" # "P/B (mrq): {}\t\t\tBeta: {}\t\t\tProfit Margin: {}\n" # "Operating Margin(ttm): {}\tROE: {}\t\tROA: {}\t\t\tRevenue per Share: {}\t" # "Gross Profit(ttm): {}\tCurrent Ratio (mrq): {}\nQuarterly Revenue Growth (yoy): {}\t\t\t" # "Quarterly Earnings Growth (yoy): {}\t\t\t\tTotal Debt/Equity (mrq): {}\n" # "Book Value Per Share (mrq): {}\t\t\tTotal Cash Per Share (mrq): {}\t\t\t\t 1 yr target: {}". # format(yahoo_equity_info['Trailing P/E'], yahoo_equity_info['Forward P/E 1'], # yahoo_equity_info['Price/Sales (ttm)'], yahoo_equity_info['Price/Book (mrq)'], # yahoo_equity_info['Beta'], yahoo_equity_info['Profit Margin'], # yahoo_equity_info['Operating Margin (ttm)'], # yahoo_equity_info['Return on Equity (ttm)'], # yahoo_equity_info['Return on Assets (ttm)'], # yahoo_equity_info['Revenue Per Share (ttm)'], # yahoo_equity_info['Gross Profit (ttm)'], # yahoo_equity_info['Current Ratio (mrq)'], # yahoo_equity_info['Quarterly Revenue Growth (yoy)'], # yahoo_equity_info['Quarterly Earnings Growth (yoy)'], #yahoo_equity_info['Total Cash (mrq)'], # yahoo_equity_info['Total Debt/Equity (mrq)'], # yahoo_equity_info['Book Value Per Share (mrq)'], # yahoo_equity_info['Total Cash Per Share (mrq)'], # yahoo_summary_info['1y Target Est'])) # click.echo("Market Cap: {}, PE: {},".\ # format(market_cap(rb_client.market_cap), # click.style(str(rb_client.company_pe_ratio), fg='red'))) snap_low_high_table = PrettyTable([ '1 yr target', 'RSI', 'Beta', 'Dividend Yield', 'Dividend/Share', 'Highest', 'Lowest', '52 week high', '52 week low', 'SMA10', 'SMA21', 'SMA50', 'SMA200' ]) snap_low_high_table.add_row([ yahoo_summary_info['1y Target Est'], str(rsi), yahoo_equity_info['Beta'], ticker_obj.dividend, ticker_obj.annualDividend, str(max(close_price_list)), str(min(close_price_list)), str(rb_client.high_52_weeks), str(rb_client.low_52_weeks), sma_10, sma_21, sma_50, sma_200 ]) click.echo(snap_low_high_table) #click.echo("RSI: {}\tHighest: {}\tLowest: {}\t52 week high: {}\t" # "52 week low: {}\tSMA10: {}\tSMA21: {}\tSMA50: {}\t" # "SMA200: {}".format(click.style(str(rsi), fg='red'), # click.style(str(max(close_price_list)), fg='red'), # click.style(str(min(close_price_list)), fg='red'), # click.style(str(rb_client.high_52_weeks), fg='red'), # click.style(str(rb_client.low_52_weeks), fg='red'), # sma_10, sma_21, sma_50, sma_200)) return True fluctuate = get_volatility(float(v['2. high']), float(v['3. low'])) fluctuate_percent = get_volatility_percent(fluctuate, float(v['4. close'])) try: change = get_price_change(float(v['4. close']), float(price_data[prev_date]['4. close'])) except KeyError: continue change_percent = get_price_change_percent( change, float(price_data[prev_date]['4. close'])) vol = int(v['5. volume']) / 1000 close_price_list.append(float(v['4. close'])) ticker_table.add_row([ k, round(float(v['1. open']), 3), round(float(v['4. close']), 3), round(float(v['2. high']), 3), round(float(v['3. low']), 3), round(fluctuate, 3), round(fluctuate_percent, 2), round(change, 2), round(change_percent, 2), vol ])
def setUpClass(cls): pytest.skip('Skip option tests due to broken yahoo api') cls.aapl = Equity('AAPL') cls.options = OptionChain(cls.aapl)