def eight_k(): eight_dic = { 'Item 1.03': 'Bankruptcy or Receivership', 'Item 1.04': 'Mine Safety - Reporting of Shutdowns and Patterns of Violations', 'Item 2.04': 'Triggering Events That Accelerate or Increase a Direct Financial Obligation or an Obligation under an Off-Balance Sheet Arrangement', 'Item 2.05': 'Costs Associated with Exit or Disposal Activities', 'Item 2.06': 'Material Impairments', 'Item 3.01': 'Notice of Delisting or Failure to Satisfy a Continued Listing Rule or Standard; Transfer of Listing', 'Item 4.02': 'Non-Reliance on Previously Issued Financial Statements or a Related Audit Report or Completed Interim Review', 'Item 5.04': 'Temporary Suspension of Trading Under Registrant"s Employee Benefit Plans', 'Item 6.04': 'Failure to Make a Required Distribution',} a = feedparser.parse('http://www.sec.gov/cgi-bin/browse-edgar?action=getcurrent&CIK=&type=8-k&company=&dateb=&owner=include&start=0&count=100&output=atom') time.sleep(2) today = datetime.datetime.today() for entry in range(0,99): try: company_name = a.entries[entry].title.lower() company_summary = a.entries[entry].summary for key in eight_dic: if key in company_summary: last25 = slice(-25, None) if company_name[last25] not in stocks_sent: day = a.entries[entry].updated day = day.split('T') t = day[0] if t in str(today): try: cik = company_name[company_name.find("(")+1:company_name.find(")")] stocks_sent.append(company_name[last25]) headers = {'Ocp-Apim-Subscription-Key': 'GETYOUROWNSUBSCRIPTIONKEY',} params = urllib.parse.urlencode({}) conn = http.client.HTTPSConnection('services.last10k.com') conn.request("GET", "/v1/company/"+cik+"/ticker?%s" % params, "{body}", headers) responsed = conn.getresponse() with responsed as response: html_content = response.read() ticker = html_content ticker = str(ticker) ticker = ticker.replace("b","") ticker = ticker.replace('"','') ticker = ticker.replace("'","") ticker = ticker.replace(" ","") ticker = ticker.upper() symbol = ticker conn.close() desc = eight_dic.get(key) ticker = Stock(ticker) current_price = ticker.get_price() message = company_name+'\n'+symbol+'\n$'+str(current_price)+'\n\n'+key+'\n'+desc confirm(text=message, title='Short Option', buttons=['OK']) print(key,'\n',desc,'\n~~~~~~~~~~~~~~~~~~~~') except: print('research fail: ',company_name) pass except: print('da fuk? Re 8k') pass
def getStock(name): # get data from API - use the Python requests library # process input to pull out the right values needed # calculate the sharpe ratio # return the sharpe ratio stock = Stock(name) return str(stock.get_price())
class IEXSecurity: def __init__(self, ticker): self.ticker = ticker self.security = Stock(ticker) def get_price(self): return self.security.get_price()
def data(tickers, sector): slist = [] print(tickers) stocks_object = Stock(tickers) stocks = stocks_object.get_price() now = datetime.now() last_year = datetime.now() - timedelta(days=365) date = datetime.today().strftime('%Y-%m-%d') for company in stocks: # Create one-year graph trend for company df = web.DataReader(company, 'robinhood', datetime(last_year.year, last_year.month, last_year.day), datetime(now.year, now.month, now.day)).reset_index() data = [go.Scatter(x=df.begins_at, y=df.close_price)] layout = go.Layout(title=company, xaxis={'title': 'Date'}, yaxis={'title':'Close Price'}) figure = go.Figure(data=data, layout=layout) link = py.plot(figure, filename=company) # Get closing price of company price = stocks[company] # Link to company graph company_graph = "[{}]({})".format(company, link) # Output company info slist.append([date, company_graph, price]) output(slist)
def index(): form = investmentForm() if request.method == 'POST' and form.validate(): #Get form field data symb = form.stockSymbol.data stock = Stock(symb) openPrice = stock.get_open() nowPrice = stock.get_price() companyInfo = stock.get_company() companyName = companyInfo['companyName'] symbol = companyInfo['symbol'] calculate = openPrice - nowPrice calc = "{:.2f}".format(calculate) ct = datetimeConverstion() percentage = ((openPrice - nowPrice) / openPrice) * 100 percent = "{:.2f}".format(percentage) new_date = ct.strftime('%A %Y-%m-%d %I:%M %p') return render_template('price.html', symbol=symbol, companyName=companyName, nowPrice=nowPrice, new_date=new_date, calc=calc, percent=percent) return render_template('home.html', form=form)
def update_header(submit, input_value): b = Stock(input_value) name = pd.DataFrame([b.get_company()]) name = name['companyName'].values[0] f = str(b.get_price()) title = name + ' $' + f return title
def price(ticker): try: ticker = Stock(ticker.ticker) price = ticker.get_price() except: return "---" else: return price
def fetch_market_data(tickers): prices = {} for i in range(0, len(tickers), 99): # print('{}/{}'.format(i, len(tickers))) stock = Stock(tickers[i:i + 99]) batch_prices = {ticker: (datetime.now(), value) for ticker, value in stock.get_price().items()} prices.update(batch_prices) batch_prices = {ticker: (datetime.now(), value) for ticker, value in Stock(tickers[-(len(tickers) % 99):]).get_price().items()} prices.update(batch_prices) return prices
def main(argv): print("name\tprice\topen\tvariation") for n in argv: try: s = Stock(n) price = s.get_price() open = s.get_open() variation = 100 * (price - open) / open print("{}\t{}\t{}\t{:.3f} %".format(n, price, open, variation)) except: sys.stderr.write("error fetching data for '{}'\n".format(n))
def chat(msg): global dictionary,pending,pending_action,state,my_friend print(msg) usermessage=txt_recog(msg) if usermessage=='quit': my_friend.send(get_chatbotanswer('See you.')) sys.exit() intent=interprete(interpreter,usermessage)['intent']['name'] entities=extract_entities(nlp,usermessage) Org=Check_Org(entities) intent_=(check_intents(intent)) dictionary,pending,pending_action,state=bot_reply(intent_,state,pending,Org,pending_action,dictionary) if state==END: my_friend.send(get_chatbotanswer('See you.')) sys.exit() action=pending_actions() if pending is not 0: my_friend.send(get_chatbotanswer(action[pending_action])) if state is not 0 and state is not 3 and state is not 5: my_friend.send(get_chatbotanswer(state_change_action(state))) if (dictionary['function'] is not None) and (dictionary['company']is not None): CPN=Stock(get_ticker_symbol(dictionary['company'])) if dictionary['function']=='b': if error_check1(CPN)==1: p_CPN=CPN.get_price() state=FOUND my_friend.send(get_chatbotanswer('Ok,I have found it! The price of {0} is {1}$'.format(dictionary['company'],p_CPN) )) else: my_friend.send(get_chatbotanswer('Information of company not found')) state=NOTFOUND if dictionary['function']=='c': if error_check2(CPN)==1: mv_CPN=CPN.get_volume() my_friend.send(get_chatbotanswer('Ok,I have found it!')) state=FOUND my_friend.send(get_chatbotanswer('The volume of {0} is {1}'.format(dictionary['company'],mv_CPN) )) else: my_friend.send(get_chatbotanswer('Information of company not found')) state=NOTFOUND if dictionary['function']=='d': if error_check3(CPN)==1: mc_CPN=CPN.get_market_cap() my_friend.send(get_chatbotanswer('Ok,I have found it!')) state=FOUND my_friend.send(get_chatbotanswer('The market value of {0} is {1}$'.format(dictionary['company'],mc_CPN))) else: my_friend.send(get_chatbotanswer('Information not found')) state=NOTFOUND if state == FOUND or state==NOTFOUND : my_friend.send(get_chatbotanswer('Do you have other questions? Say "quit" to quit')) state=INIT
def get_list_price(self, code_list): # check if there is only one code in list if len(code_list) == 1: return self.get_price(code_list[0]) # use list to directly query user_stocks = IEXStock(code_list) try: return user_stocks.get_price() except: return ("No saved stock in record")
def get_prices_in_range(): with open('NDQTickers.csv') as csvfile: reader = csv.reader(csvfile) for row in reader: #print(row[0]) if len(row[0]) > 4: continue else: ticker = Stock(row[0]) price = ticker.get_price() if 10 < price < 250: tickersInRange.append(row[0]) #print(row[0] + " " + str(ticker.get_price())) return tickersInRange
def run(self, dispatcher, tracker, domain): company_x = tracker.get_slot('company') symbols = get_available_symbols() for i in range(len(symbols)): if company_x.lower() in symbols[i]["name"].lower(): company = symbols[i]["symbol"] companyobj = Stock(company) price = companyobj.get_price() response = """{} shares is {} currently.""".format(company, price) dispatcher.utter_message(response) return [SlotSet('company', company)]
def get_ma(ticker): stock = Stock(ticker) start = now - timedelta(days=25) try: keyStats = stock.get_key_stats() if (stock.get_price() < 5): return -1,-1,-1 df_hist = get_historical_data(ticker, start=start, end=now, output_format='pandas') dma50 = keyStats['day50MovingAvg'] dma10 = df_hist.tail(10)['close'].mean() dma20 = df_hist.tail(20)['close'].mean() except: return -1,-1,-1 return dma10, dma20, dma50
def get_price(sym): start = time.time() pattern = re.compile(r'^\$([0-9]+\.[0-9]+)', re.MULTILINE) try: symbol = Stock(sym) price = symbol.get_price() except: soup = pull_website(sym) text = soup.find('p', {'class':f'last_price'}) if not hasattr(text, 'text'): text = soup.find('div', {'class':f'last_price_mf'}) #print(text.text) price = re.search(pattern, text.text).group(1) end = time.time() #print(f'{sym} price generation took {end-start} seconds') return float(price)
def get_ma(ticker): stock = Stock(ticker) start = now - timedelta(days=25) try: keyStats = stock.get_key_stats() if (stock.get_price() < 5): return -1, -1, -1 df_hist = get_historical_data(ticker, start=start, end=now, output_format='pandas') dma50 = keyStats['day50MovingAvg'] dma10 = df_hist.tail(10)['close'].mean() dma20 = df_hist.tail(20)['close'].mean() except: return -1, -1, -1 return dma10, dma20, dma50
def index(): if request.method == 'POST': #this block is only entered when the form is submitted stock = request.form['symbol'] symbol = Stock(stock) name = symbol.get_company_name() + " (" + str(stock) + ")\n\n" curr_time = now price = str(symbol.get_price()) + " " + str( symbol.get_quote().get('change')) + " (" + str( symbol.get_quote().get('changePercent')) + ")" return '''<title>Python Finance Info</title> <form method="POST"> <h3>Python Finance Info</h3><br/> <i>Input:</i><br/><br/> Enter a symbol <input type="text" name="symbol"> <input type="submit" value="Submit"><br/><br/> </form> <i>Output: </i><br/><br/> {} <br/> {} <br/> {} </h5>'''.format( name, curr_time, price) return '''<title>Python Finance Info</title>
class TestBatch(object): def setup_class(self): self.cbatch = Stock(["aapl", "tsla"]) def test_invalid_symbol_or_symbols(self): with pytest.raises(IEXSymbolError): Stock(["TSLA", "AAAPLPL", "fwoeiwf"]) def test_get_all_format(self): data = self.cbatch.get_all() assert isinstance(data, dict) def test_get_chart_format(self): data = self.cbatch.get_chart() assert isinstance(data, dict) def test_get_book_format(self): data = self.cbatch.get_book() assert isinstance(data, dict) def test_get_open_close_format(self): data = self.cbatch.get_open_close() assert isinstance(data, dict) def test_get_previous_format(self): data = self.cbatch.get_previous() assert isinstance(data, dict) def test_get_company_format(self): data = self.cbatch.get_company() assert isinstance(data, dict) def test_get_key_stats_format(self): data = self.cbatch.get_key_stats() assert isinstance(data, dict) def test_get_relevant_format(self): data = self.cbatch.get_relevant() assert isinstance(data, dict) def test_get_news_format(self): data = self.cbatch.get_news() assert isinstance(data, dict) def test_get_financials_format(self): data = self.cbatch.get_financials() assert isinstance(data, dict) def test_get_earnings_format(self): data = self.cbatch.get_earnings() assert isinstance(data, dict) def test_get_logo_format(self): data = self.cbatch.get_logo() assert isinstance(data, dict) def test_get_price_format(self): data = self.cbatch.get_price() assert isinstance(data, dict) def test_get_delayed_quote_format(self): data = self.cbatch.get_delayed_quote() assert isinstance(data, dict) def test_get_effective_spread_format(self): data = self.cbatch.get_effective_spread() assert isinstance(data, dict) def test_get_volume_by_venue_format(self): data = self.cbatch.get_volume_by_venue() assert isinstance(data, dict) def test_get_select_ep_bad_params(self): with pytest.raises(ValueError): self.cbatch.get_select_endpoints() with pytest.raises(IEXEndpointError): self.cbatch.get_select_endpoints("BADENDPOINT") def test_ohlc(self): data = self.cbatch.get_ohlc() assert isinstance(data, dict) def test_time_series(self): data = self.cbatch.get_time_series() data2 = self.cbatch.get_chart() assert data == data2 def test_nondefault_params_1(self): data = Stock(["AAPL", "TSLA"], _range='5y') data2 = Stock(["AAPL", "TSLA"]) assert len(data.get_chart()["AAPL"]) > len(data2.get_chart()["AAPL"]) assert len(data.get_chart()["TSLA"]) > len(data2.get_chart()["TSLA"]) def test_nondefault_params_2(self): data = Stock(["AAPL", "TSLA"], last=37) assert len(data.get_news()["AAPL"]) == 37 assert len(data.get_news()["TSLA"]) == 37
def analyse_data(self, filename, coin, formatted_cryptocurrency_tweets, j_info): tweetsInHour = [] print("Number of unique tweets in an hour for " + coin + " is " + str(len(formatted_cryptocurrency_tweets))) file_exists = os.path.isfile(filename) if sentiment_config.TYPE == "CRYPTO": change = j_info['ticker']['change'] volume = j_info['ticker']['volume'] self.price = j_info['ticker']['price'] timestamp = j_info['timestamp'] else: stock = Stock(sentiment_config.EXCHANGE) change = stock.get_price() - self.price volume = stock.get_volume() self.price = stock.get_price() timestamp = datetime.datetime.now().strftime("%H:%M:%S") try: # average compound average_compound = float( sum(d['sentiment']['compound'] for d in formatted_cryptocurrency_tweets)) / len( formatted_cryptocurrency_tweets) cryptoFeature = { 'TimeStamp': [timestamp], 'Sentiment': [average_compound], 'Volume': [volume], 'Change': [change], 'Price': [self.price], 'NoOfTweets': [len(formatted_cryptocurrency_tweets)] } formatted_cryptocurrency_tweets = [] pd.DataFrame.from_dict(data=cryptoFeature, orient='columns').to_csv( filename, mode='a', header=not file_exists) # Make Predictions linear_predict_change = predict.generate_linear_prediction_model( cryptoFeature, filename) multi_linear_predict_change = predict.generate_multi_linear_prediction_model( cryptoFeature, filename) tree_predict_change = predict.generate_tree_prediction_model( cryptoFeature, filename) forest_predict_change = predict.generate_forest_prediction_model( cryptoFeature, filename) if linear_predict_change is not None and multi_linear_predict_change is not None\ and tree_predict_change is not None and forest_predict_change is not None: #get average prediction average_prediction = (float(linear_predict_change) + float(multi_linear_predict_change) + float(tree_predict_change) + float(forest_predict_change)) / 4 self.notify_user(str(average_prediction), str(cryptoFeature['Sentiment'][0])) #Plotting self.cryptocurrency_current_price.append(self.price) self.cryptocurrency_plot_time.append( datetime.datetime.now().strftime("%H:%M:%S")) print("Linear " + linear_predict_change) print("Multi Linear" + multi_linear_predict_change) print("Forest" + forest_predict_change) self.plot(linear_predict_change, multi_linear_predict_change, tree_predict_change, forest_predict_change) else: print("Still building set") except Exception as e: print("No tweets in the last hour", str(e))
def setUp(self): stock = Stock(["GOOG", "TSLA"]) self.company = stock.get_price()
# https://pypi.org/project/iexfinance/ # Stock from iexfinance import Stock tsla = Stock('TSLA') print('TSLA open: %f' % tsla.get_open()) print('TSLA price: %f' % tsla.get_price()) # Historical Data from iexfinance import get_historical_data from datetime import datetime import pandas as pd start = datetime(2014, 1, 1) end = datetime(2018, 10, 1) aapl_hist_df = get_historical_data("AAPL", start=start, end=end, output_format='pandas') days_from_start = [] for x in aapl_hist_df.axes[0]: dt = datetime.strptime(x, "%Y-%m-%d") if start is None: start = dt diff = dt - start days_from_start.append(diff.days) aapl_hist_closing_df = pd.DataFrame({'price': aapl_hist_df['close'], 'days_from_start': days_from_start}) # Chart it import matplotlib.pyplot as plt
end = datetime.today() df = get_historical_data('MMM', start=start, end=end, output_format='pandas') df['date'] = df.index #df.drop(['date'],axis=1) df.reset_index(level=0, inplace=True) scipy.io.savemat('test.mat', {'struct': df.to_dict('list')}) #IES Market Data a = get_market_tops('TSLA', output_format='pandas') get_market_last() get_market_deep() get_market_book() # IEX stats get_stats_intraday() get_stats_recent()[0] get_stats_records() get_stats_daily(last=3) get_stats_monthly(start=datetime(2017, 2, 9), end=datetime(2017, 5, 24))[0] b = get_stats_intraday('TSLA') tsla = Stock(['TSLA', 'AAPL'], output_format='pandas') tsla.get_open() tsla.get_price() df = get_historical_data("AAPL", start=start, end=end, output_format='pandas') df.head() df.tail() df.plot() plt.show()
def get_price(sym): symbol = Stock(sym) price = symbol.get_price() return price
from iexfinance import Stock from datetime import datetime stockname = "GE" stock = Stock(stockname) lastprice = 0 while (True): curprice = stock.get_price() if (curprice != lastprice): lastprice = curprice print(str(datetime.now().time()) + " | " + str(curprice))
def quote(name): stock = Stock(name) return stock.get_price()
def format_result_string(*args): return ' | '.join(args) default_ticker = 'KO' if len(sys.argv) == 1: print(f"No ticker passed in as an arguement, default to {default_ticker}") ticker = default_ticker else: ticker = sys.argv[1] stock = Stock(ticker, output_format='pandas') stock_name = stock.get_company_name()['companyName'].to_string() stock_price = stock.get_price()['price'][ticker] stock_eps = stock.get_key_stats()[ticker]['latestEPS'] flat_growth_estimate = 5 aaa_corporate_bond_yield = 3.56 stock_intrinsic_value = (stock_eps * (8.5 + (2 * flat_growth_estimate)) * 4.4) / aaa_corporate_bond_yield norm_stock_intrinsic_value = stock_intrinsic_value / stock_price print( format_result_string(stock_name, ticker.upper(), format_num_to_currency(stock_price), float_to_percentage_string(flat_growth_estimate), float_to_percentage_string(aaa_corporate_bond_yield), format_num_to_currency(stock_eps), format_num_to_currency(stock_intrinsic_value), '{:.2f}'.format(norm_stock_intrinsic_value)))
class TestShareDefault(object): def setup_class(self): self.cshare = Stock("aapl") self.cshare2 = Stock("aapl", output_format='pandas') self.cshare3 = Stock("svxy") self.cshare4 = Stock("aapl", json_parse_int=Decimal, json_parse_float=Decimal) self.cshare5 = Stock("gig^") def test_invalid_symbol(self): data = Stock("BAD SYMBOL") with pytest.raises(IEXSymbolError): data.get_price() def test_get_all_format(self): data = self.cshare.get_all() assert isinstance(data, dict) def test_get_all(self): data = self.cshare.get_all() assert len(data) == 20 def test_get_endpoints(self): data = self.cshare.get_endpoints(["price"]) assert list(data) == ["price"] def test_get_endpoints_bad_endpoint(self): with pytest.raises(IEXEndpointError): self.cshare.get_endpoints(["BAD ENDPOINT", "quote"]) with pytest.raises(IEXEndpointError): self.cshare.get_endpoints("BAD ENDPOINT") def test_get_book_format(self): data = self.cshare.get_book() assert isinstance(data, dict) data2 = self.cshare2.get_book() assert isinstance(data2, pd.DataFrame) def test_get_chart_format(self): data = self.cshare.get_chart() assert isinstance(data, list) data2 = self.cshare2.get_chart() assert isinstance(data2, list) def test_get_chart_params(self): data = self.cshare.get_chart() # Test chart ranges data2 = self.cshare.get_chart(range_='1y') assert 15 < len(data) < 35 assert 240 < len(data2) < 260 # Test chartSimplify data4 = self.cshare.get_chart(chartSimplify=True)[0] assert "simplifyFactor" in list(data4) data5 = self.cshare.get_chart(range_='1y', chartInterval=5) assert 45 < len(data5) < 55 @pytest.mark.xfail(reason="This test only runs correctly between 00:00 and" "09:30 EST") def test_get_chart_reset(self): # Test chartReset data3 = self.cshare.get_chart(range_='1d', chartReset=True) assert data3 == [] def test_get_company_format(self): data = self.cshare.get_company() assert isinstance(data, dict) data2 = self.cshare2.get_company() assert isinstance(data2, pd.DataFrame) def test_get_delayed_quote_format(self): data = self.cshare.get_delayed_quote() assert isinstance(data, dict) data2 = self.cshare2.get_delayed_quote() assert isinstance(data2, pd.DataFrame) def test_get_dividends_format(self): data = self.cshare.get_dividends() assert isinstance(data, list) data2 = self.cshare2.get_dividends() assert isinstance(data2, list) def test_get_dividends_params(self): data = self.cshare.get_dividends() data2 = self.cshare.get_dividends(range_='2y') data3 = self.cshare.get_dividends(range_='5y') assert len(data) < len(data2) < len(data3) def test_get_earnings_format(self): data = self.cshare.get_earnings() assert isinstance(data, list) data2 = self.cshare2.get_earnings() assert isinstance(data2, pd.DataFrame) # Ensure empty list is returned for symbol with no earnings data3 = self.cshare5.get_earnings() assert isinstance(data3, list) def test_get_effective_spread_format(self): data = self.cshare.get_effective_spread() assert isinstance(data, list) data2 = self.cshare2.get_effective_spread() assert isinstance(data2, pd.DataFrame) def test_get_financials_format(self): data = self.cshare.get_financials() assert isinstance(data, list) data2 = self.cshare2.get_financials() assert isinstance(data2, pd.DataFrame) # Ensure empty list is returned even when ticker has no financials data3 = self.cshare5.get_financials() assert isinstance(data3, list) def test_get_key_stats_format(self): data = self.cshare.get_key_stats() assert isinstance(data, dict) data2 = self.cshare2.get_key_stats() assert isinstance(data2, pd.DataFrame) def test_get_largest_trades(self): data = self.cshare.get_largest_trades() assert isinstance(data, list) data2 = self.cshare2.get_largest_trades() assert isinstance(data2, pd.DataFrame) def test_get_logo_format(self): data = self.cshare.get_logo() assert isinstance(data, dict) data2 = self.cshare2.get_logo() assert isinstance(data2, pd.DataFrame) def test_get_news_format(self): data = self.cshare.get_news() assert isinstance(data, list) @pytest.mark.xfail(reason="Provider error. Awaiting patch.") def test_get_news_params(self): data = self.cshare.get_news(last=15) assert len(data) == 15 def test_ohlc(self): data = self.cshare.get_ohlc() assert isinstance(data, dict) data2 = self.cshare2.get_ohlc() assert isinstance(data2, pd.DataFrame) def test_get_open_close_format(self): data = self.cshare.get_open_close() assert isinstance(data, dict) data2 = self.cshare2.get_open_close() assert isinstance(data2, pd.DataFrame) def test_get_peers_format(self): data = self.cshare.get_peers() assert isinstance(data, list) data2 = self.cshare2.get_peers() assert isinstance(data2, list) def test_get_previous_format(self): data = self.cshare.get_previous() assert isinstance(data, dict) data2 = self.cshare2.get_previous() assert isinstance(data2, pd.DataFrame) def test_get_price_format(self): data = self.cshare.get_price() assert isinstance(data, float) data2 = self.cshare2.get_price() assert isinstance(data2, pd.DataFrame) data4 = self.cshare4.get_price() assert isinstance(data4, Decimal) def test_get_quote_format(self): data = self.cshare.get_quote() assert isinstance(data, dict) data2 = self.cshare2.get_quote() assert isinstance(data2, pd.DataFrame) def test_get_quote_params(self): data = self.cshare.get_quote() data2 = self.cshare.get_quote(displayPercent=True) assert (abs(data2["ytdChange"]) > abs(data["ytdChange"])) def test_get_relevant_format(self): data = self.cshare.get_relevant() assert isinstance(data, dict) data2 = self.cshare2.get_relevant() assert isinstance(data2, pd.DataFrame) def test_get_splits_format(self): data = self.cshare3.get_splits() assert isinstance(data, list) data2 = self.cshare3.get_splits(range_="1y") assert isinstance(data2, list) def test_get_splits_params(self): data = self.cshare3.get_splits(range_="2y") data2 = self.cshare3.get_splits(range_="5y") assert len(data2) > len(data) def test_get_time_series(self): data = self.cshare.get_time_series() data2 = self.cshare.get_chart() assert data == data2 def test_get_volume_by_venue_format(self): data = self.cshare.get_volume_by_venue() assert isinstance(data, list) data2 = self.cshare2.get_volume_by_venue() assert isinstance(data2, pd.DataFrame) def test_filter(self): data = self.cshare.get_quote(filter_='ytdChange') assert isinstance(data, dict) assert isinstance(data["ytdChange"], float) data4 = self.cshare4.get_quote(filter_='ytdChange') assert isinstance(data4, dict) assert isinstance(data4["ytdChange"], Decimal)
def test_invalid_symbol(self): data = Stock("BAD SYMBOL") with pytest.raises(IEXSymbolError): data.get_price()
def test_invalid_symbol_or_symbols(self): with pytest.raises(IEXSymbolError): a = Stock(["TSLA", "BAD SYMBOL", "BAD SYMBOL"]) a.get_price()
class TestBatchDefault(object): def setup_class(self): self.cbatch = Stock(["aapl", "tsla"]) self.cbatch2 = Stock(["aapl", "tsla"], output_format='pandas') self.cbatch3 = Stock(["uvxy", "svxy"]) def test_invalid_symbol_or_symbols(self): with pytest.raises(IEXSymbolError): a = Stock(["TSLA", "BAD SYMBOL", "BAD SYMBOL"]) a.get_price() def test_get_endpoints(self): data = self.cbatch.get_endpoints(["price"])["AAPL"] assert list(data) == ["price"] def test_get_endpoints_bad_endpoint(self): with pytest.raises(IEXEndpointError): self.cbatch.get_endpoints(["BAD ENDPOINT", "quote"]) with pytest.raises(IEXEndpointError): self.cbatch.get_endpoints("BAD ENDPOINT") def test_get_all(self): data = self.cbatch.get_all() assert len(data) == 2 assert len(data["AAPL"]) == 20 def test_get_all_format(self): data = self.cbatch.get_all() assert isinstance(data, dict) data2 = self.cbatch2.get_all() assert isinstance(data2["AAPL"], dict) def test_get_book_format(self): data = self.cbatch.get_book() assert isinstance(data, dict) data2 = self.cbatch2.get_book() assert isinstance(data2, pd.DataFrame) def test_get_chart_format(self): data = self.cbatch.get_chart() assert isinstance(data, dict) data2 = self.cbatch2.get_chart() assert isinstance(data2["AAPL"], list) def test_get_chart_params(self): data = self.cbatch.get_chart()["AAPL"] # Test chart range_s data2 = self.cbatch.get_chart(range_='1y')["AAPL"] assert 15 < len(data) < 35 assert 240 < len(data2) < 260 # Test chartSimplify data4 = self.cbatch.get_chart(chartSimplify=True)["AAPL"][0] assert "simplifyFactor" in list(data4) data5 = self.cbatch.get_chart(range_='1y', chartInterval=5)["AAPL"] assert 45 < len(data5) < 55 @pytest.mark.xfail(reason="This test only works overnight") def test_get_chart_reset(self): # Test chartReset data = self.cbatch.get_chart(range_='1d', chartReset=True) assert data == [] def test_get_company_format(self): data = self.cbatch.get_company() assert isinstance(data, dict) data2 = self.cbatch2.get_company() assert isinstance(data2, pd.DataFrame) def test_get_delayed_quote_format(self): data = self.cbatch.get_delayed_quote() assert isinstance(data, dict) data2 = self.cbatch2.get_delayed_quote() assert isinstance(data2, pd.DataFrame) def test_get_dividends_format(self): data = self.cbatch.get_dividends() assert isinstance(data, dict) data2 = self.cbatch2.get_dividends() assert isinstance(data2, dict) def test_get_dividends_params(self): data = self.cbatch.get_dividends()["AAPL"] data2 = self.cbatch.get_dividends(range_='2y')["AAPL"] data3 = self.cbatch.get_dividends(range_='5y')["AAPL"] assert len(data) < len(data2) < len(data3) def test_get_earnings_format(self): data = self.cbatch.get_earnings() assert isinstance(data, dict) data2 = self.cbatch2.get_earnings() assert isinstance(data2, pd.DataFrame) def test_get_effective_spread_format(self): data = self.cbatch.get_effective_spread() assert isinstance(data, dict) data2 = self.cbatch2.get_effective_spread() assert isinstance(data2, pd.DataFrame) def test_get_financials_format(self): data = self.cbatch.get_financials() assert isinstance(data, dict) data2 = self.cbatch2.get_financials() assert isinstance(data2, pd.DataFrame) def test_get_key_stats_format(self): data = self.cbatch.get_key_stats() assert isinstance(data, dict) data2 = self.cbatch2.get_key_stats() assert isinstance(data2, pd.DataFrame) def test_get_logo_format(self): data = self.cbatch.get_logo() assert isinstance(data, dict) data2 = self.cbatch2.get_logo() assert isinstance(data2, pd.DataFrame) def test_get_news_format(self): data = self.cbatch.get_news() assert isinstance(data, dict) def test_ohlc(self): data = self.cbatch.get_ohlc() assert isinstance(data, dict) def test_get_open_close_format(self): data = self.cbatch.get_open_close() assert isinstance(data, dict) data2 = self.cbatch2.get_open_close() assert isinstance(data2, pd.DataFrame) def test_get_peers_format(self): data = self.cbatch.get_peers() assert isinstance(data, dict) data2 = self.cbatch2.get_peers() assert isinstance(data2, dict) def test_get_previous_format(self): data = self.cbatch.get_previous() assert isinstance(data, dict) data2 = self.cbatch2.get_previous() assert isinstance(data2, pd.DataFrame) def test_get_price_format(self): data = self.cbatch.get_price() assert isinstance(data, dict) data2 = self.cbatch2.get_price() assert isinstance(data2, pd.DataFrame) def test_get_quote_format(self): data = self.cbatch.get_quote() assert isinstance(data, dict) data2 = self.cbatch2.get_quote() assert isinstance(data2, pd.DataFrame) data3 = self.cbatch.get_quote(displayPercent=True) assert (abs(data3["AAPL"]["ytdChange"]) > abs( data["AAPL"]["ytdChange"])) def test_get_relevant_format(self): data = self.cbatch.get_relevant() assert isinstance(data, dict) data2 = self.cbatch2.get_relevant() assert isinstance(data2, pd.DataFrame) def test_get_splits(self): data = self.cbatch.get_splits() assert isinstance(data, dict) data2 = self.cbatch2.get_splits() assert isinstance(data2, pd.DataFrame) def test_get_splits_params(self): data = self.cbatch3.get_splits(range_="2y")["SVXY"] data2 = self.cbatch3.get_splits(range_="5y")["SVXY"] assert len(data2) > len(data) def test_time_series(self): data = self.cbatch.get_time_series() data2 = self.cbatch.get_chart() assert data == data2 def test_get_volume_by_venue_format(self): data = self.cbatch.get_volume_by_venue() assert isinstance(data, dict) data2 = self.cbatch2.get_volume_by_venue() assert isinstance(data2, pd.DataFrame) def test_get_select_ep_bad_params(self): with pytest.raises(ValueError): self.cbatch.get_endpoints() with pytest.raises(IEXEndpointError): self.cbatch.get_endpoints("BADENDPOINT")
def run(): tsla = Stock('VOO') price_open = tsla.get_open() price_now = tsla.get_price() print(price_open) print(price_now)
def scrape_xml(link,company_name): TotalValue = 0 transactionCodeList = [] DorIList = [] TitleList = [] today = datetime.datetime.today() today = today.strftime('%m/%d/%Y %I:%M %p') headers = { "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.103 Safari/537.36", "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "accept-charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3", "accept-encoding": "gzip, deflate, sdch", "accept-language": "en-US,en;q=0.8", } explain = {'P' : 'Open market or private purchase of non-derivative or derivative security', 'S' : 'Open market or private sale of non-derivative or derivative security', 'V' : 'Transaction voluntarily reported earlier than required', 'A' : 'Grant, award or other acquisition', 'D' : 'Disposition to the issuer of issuer equity securities', 'F' : 'Payment of exercise price or tax liability by delivering or withholding securities incident to the receipt of a security issued', 'I' : 'Discretionary transaction resulting in acquisition or disposition of issuer securities', 'M' : 'Exercise or conversion of derivative security exempted Derivative Securities Codes', 'C' : 'Conversion of derivative security', 'E' : 'Expiration of short derivative position', 'H' : 'Expiration of long derivative position with value received', 'O' : 'Exercise of out-of-the-money derivative security', 'X' : 'Exercise of in-the-money or at-the-money derivative security', 'G' : 'Bona fide gift', 'L' : 'Small acquisition', 'W' : 'Acquisition or disposition by will or the laws of descent and distribution', 'Z' : 'Deposit into or withdrawal from voting trust', 'J' : 'Other', 'K' : 'Transaction in equity swap or instrument with similar characteristics', 'U' : 'Disposition pursuant to a tender of shares in a change of control transaction', } res = requests.get(link, headers=headers) soup = bs4.BeautifulSoup(res.text, 'html.parser') for a in soup.find_all('a'): if a.getText()[-4:] == '.xml': address = 'http://www.sec.gov' + a['href'] res = requests.get(address, headers=headers, timeout=None) tree = ET.fromstring(res.content) try: isOfficer = tree.find('reportingOwner/reportingOwnerRelationship/isOfficer').text if not isOfficer: isOfficer = 'I shot the Deputy' except: isOfficer = "0" pass transactionCode = tree.findall('nonDerivativeTable/nonDerivativeTransaction/transactionCoding/transactionCode') if not transactionCode: try: transactionCode = tree.findall('derivativeTable/derivativeTransaction/transactionCoding/transactionCode') except: transactionCode = "0" pass tradingSymbol = tree.find('issuer/issuerTradingSymbol') ticker = tradingSymbol.text.lower() symbol = str(ticker.upper()) print(company_name.title() + ' (' + symbol + ') at ' + str(today)) transactionShares = tree.findall('nonDerivativeTable/nonDerivativeTransaction/transactionAmounts/transactionShares/value') if transactionShares == None: try: transactionShares = tree.findall('derivativeTable/derivativeTransaction/transactionAmounts/transactionShares/value') except: transactionShares = [] pass transactionPricePerShare = tree.findall('nonDerivativeTable/nonDerivativeTransaction/transactionAmounts/transactionPricePerShare/value') if transactionShares == None: try: transactionShares = tree.findall('derivativeTable/derivativeTransaction/transactionAmounts/transactionPricePerShare/value') except: transactionShares = [] pass DorI = tree.findall('nonDerivativeTable/nonDerivativeTransaction/ownershipNature/directOrIndirectOwnership/value') if not DorI: try: DorI = tree.findall('derivativeTable/derivativeTransaction/ownershipNature/directOrIndirectOwnership/value') except: DorI = [] pass for price, shares, direct, code in zip(transactionPricePerShare, transactionShares, DorI, transactionCode): if explain[code.text]: #direct.text == 'D' and print('Shares: ',shares.text) TotalValue = TotalValue + float(shares.text)*float(price.text) print('Total value: ',TotalValue) shares = shares.text else: pass for code in transactionCode: transactionCodeList.append(code.text) for item in DorI: DorIList.append(item.text) if '2' in isOfficer: print ('Director purchase') elif '1' in isOfficer: print ('Officer purchase') elif '0' in isOfficer: print ('Neither Officer or Director') elif isOfficer != '1' or '2' or '0': print('Officer overboard --- or maybe more!', isOfficer) if 'D' in DorIList: print('Direct Purchase') elif 'I' in DorIList: print('Indirect Purchase') else: print('D or I value fubar') print('Transaction codes: ' + str(transactionCodeList)) for key in explain: if key in transactionCodeList: print(explain.get(key)) print ('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') if 'P' in transactionCodeList: #and ticker not in portfolio: #isOfficer == str(1) and and TotalValue > 10000 and 'D' in DorIList with open('portfolio.txt', 'a') as f: f.write(ticker + '\n') ticker = Stock(ticker) current_price = str(ticker.get_price()) with open('bought_price.txt', 'a') as f: f.write(current_price + '\n') message = 'Buy Opportunity\n' + company_name.capitalize() + '\nTicker symbol: ' + symbol + '\n\nCurrent price: $'+ current_price + '\n\nOfficer: ' + isOfficer + '\n Total Value: '+str(TotalValue) print(address) print(message) if confirm(text='Want to email with your friends?', title='Insider Buy!', buttons=['YES', 'NO']) == 'YES': email (symbol, address, current_price, company_name, message) print('~~~~~~~~~~~~~~~~\nemail!!!!\n~~~~~~~~~~~~~~~~~~~~~~~')
class TestShare(object): def setup_class(self): self.cshare = Stock("aapl") def test_get_all_format(self): data = self.cshare.get_all() assert isinstance(data, dict,) def test_get_chart_format(self): data = self.cshare.get_chart() assert isinstance(data, list) def test_get_book_format(self): data = self.cshare.get_book() assert isinstance(data, dict) def test_get_open_close_format(self): data = self.cshare.get_open_close() assert isinstance(data, dict) def test_get_previous_format(self): data = self.cshare.get_previous() assert isinstance(data, dict) def test_get_company_format(self): data = self.cshare.get_company() assert isinstance(data, dict) def test_get_key_stats_format(self): data = self.cshare.get_key_stats() assert isinstance(data, dict) def test_get_relevant_format(self): data = self.cshare.get_relevant() assert isinstance(data, dict) def test_get_news_format(self): data = self.cshare.get_news() assert isinstance(data, list) def test_get_financials_format(self): data = self.cshare.get_financials() assert isinstance(data, dict) def test_get_earnings_format(self): data = self.cshare.get_earnings() assert isinstance(data, dict) def test_get_logo_format(self): data = self.cshare.get_logo() assert isinstance(data, dict) def test_get_price_format(self): data = self.cshare.get_price() assert isinstance(data, float) def test_get_delayed_quote_format(self): data = self.cshare.get_delayed_quote() assert isinstance(data, dict) def test_get_effective_spread_format(self): data = self.cshare.get_effective_spread() assert isinstance(data, list) def test_get_volume_by_venue_format(self): data = self.cshare.get_volume_by_venue() assert isinstance(data, list) def test_ohlc(self): data = self.cshare.get_ohlc() assert isinstance(data, dict) def test_time_series(self): data = self.cshare.get_time_series() data2 = self.cshare.get_chart() assert data == data2 def test_nondefault_params_1(self): aapl = Stock("AAPL", _range='5y') aapl2 = Stock("AAPL") assert len(aapl.get_chart()) > len(aapl2.get_chart()) def test_nondefault_params_2(self): aapl = Stock("AAPL", last=37) assert len(aapl.get_news()) == 37