def descarga_registros(self, request, queryset): for i in queryset: perfil = investpy.get_stock_company_profile(stock=i.symbol, country=i.pais) obj = Empresa.objects.get(symbol=i.symbol) FundamentalesEmpresa.objects.create( empresa_id=obj.id, num_acciones=int(perfil['num_acciones'].replace(',', '')), beneficios=0 if perfil['beneficios'] == 'N/A' else float( perfil['beneficios'].replace('B', '000000')), valor_bursatil=float(perfil['valor_bursatil'].replace('B', '')), proximos_resultados=perfil['proximos_resultados']) print(perfil)
def get_stock_info(ticker): info = investpy.get_stock_company_profile(stock=ticker, country='iceland') description = info["desc"] url = info["url"] price_now = get_stock_price(ticker) now = datetime.datetime.now() price_year_ago = investpy.get_stock_historical_data( stock=ticker, country='iceland', from_date=(now - datetime.timedelta(days=365)).strftime('%d/%m/%Y'), to_date=( now - datetime.timedelta(days=350)).strftime('%d/%m/%Y'))['Close'][-1] return price_now, price_year_ago, description, url
def only(): stock = request.form.get('stockName').upper() start = request.form.get('startDate') end = request.form.get('endDate') country = request.form.get('countryName') model = load_model('model.h5') start_date = datetime.strptime(start, "%Y-%m-%d").strftime("%d/%m/%Y") end_date = datetime.strptime(end, "%Y-%m-%d").strftime("%d/%m/%Y") df = investpy.get_stock_historical_data(stock=stock, country=country, from_date=start_date, to_date=end_date) df.drop('Currency', axis=1, inplace=True) data = df.filter(['Close']) dataset = data.values scaler = MinMaxScaler(feature_range=(0, 1)) scaled_data = scaler.fit_transform(dataset) df = investpy.get_stock_historical_data(stock=stock, country=country, from_date=start_date, to_date=end_date) df.drop('Currency', axis=1, inplace=True) pred_data = df.filter(['Close']) last_60_days = pred_data[-60:].values last_60_days_scaled = scaler.fit_transform(last_60_days) X_test = [] X_test.append(last_60_days_scaled) X_test = np.array(X_test) X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1)) pred_price = model.predict(X_test) pred_price = scaler.inverse_transform(pred_price) print(pred_price) com_profile = investpy.get_stock_company_profile(stock=stock, country=country, language='english') profile = com_profile['desc'] return render_template('only.html', stock=stock, start_date=start_date, end_date=end_date, profile=profile, pred_price=pred_price)
def find_technical_details(symbol): # Using the investpy module, we would get investing.com website url for the company # TODO: # Add functionality for Canadian and Stocks that are from other parts of the world company_profile = investpy.get_stock_company_profile( stock=symbol, country='United States') # print(company_profile) company_profile_url = company_profile['url'] technical_url = company_profile_url[:-15] + 'technical' response = requests.get(technical_url, headers={'User-Agent': 'Mozilla/5.0'}) soup = BeautifulSoup(response.text, 'lxml') # print(soup) data_table = soup.find_all('div', {'id': 'techinalContent'}) # print(data_table) cols = [td.text for td in data_table[0].select('td')] # print(cols) # We initializa a empty list parsed_list = [] # Parse data that we receive from web scraping into array for text in cols: parsed_text = text.strip() if '\t' or '\n' in text: parsed_text = text.replace('\n', '') parsed_text = parsed_text.replace('\t', '') parsed_list.append(parsed_text) print(parsed_list) # Now we initialize a dictionary that contains information in regards to the data we want, as well as how # many number of elements are contained in the array technical_indicators = { 'Classic': 7, 'RSI(14)': 2, 'MACD(12,26)': 2, 'MA10': 1, 'MA20': 1, 'MA50': 1, 'MA100': 1, } """ SECOND APPROACH
def test_stocks_errors(): """ This function raises errors on stock retrieval functions """ try: retrieve_stocks(test_mode=None) except: pass try: retrieve_stock_countries(test_mode=None) except: pass params = [ { 'country': ['error'] }, { 'country': 'error' }, ] for param in params: try: investpy.get_stocks(country=param['country']) except: pass try: investpy.get_stocks_list(country=param['country']) except: pass params = [ { 'country': ['error'], 'columns': None, 'as_json': False }, { 'country': 'spain', 'columns': None, 'as_json': 'error' }, { 'country': 'spain', 'columns': 0, 'as_json': True }, { 'country': 'spain', 'columns': ['error'], 'as_json': False }, ] for param in params: try: investpy.get_stocks_dict(country=param['country'], columns=param['columns'], as_json=param['as_json']) except: pass params = [ { 'stock': 'FERR', 'country': 'spain', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'stock': None, 'country': 'spain', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'stock': 'BBVA', 'country': None, 'as_json': False, 'order': 'ascending', 'debug': True }, { 'stock': 'BBVA', 'country': ['error'], 'as_json': False, 'order': 'ascending', 'debug': True }, { 'stock': 'BBVA', 'country': 'greece', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'stock': 'BBVA', 'country': 'spain', 'as_json': 'error', 'order': 'ascending', 'debug': True }, { 'stock': 'BBVA', 'country': 'spain', 'as_json': True, 'order': 'error', 'debug': True }, { 'stock': 'error', 'country': 'spain', 'as_json': True, 'order': 'ascending', 'debug': True }, { 'stock': ['error'], 'country': 'spain', 'as_json': True, 'order': 'ascending', 'debug': True }, { 'stock': 'BBVA', 'country': 'spain', 'as_json': True, 'order': 'ascending', 'debug': 'error' }, ] for param in params: try: investpy.get_stock_recent_data(stock=param['stock'], country=param['country'], as_json=param['as_json'], order=param['order'], debug=param['debug']) except: pass params = [ { 'stock': 'FERR', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'stock': None, 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'stock': 'BBVA', 'country': None, 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'stock': 'BBVA', 'country': ['error'], 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'stock': 'BBVA', 'country': 'greece', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'stock': 'BBVA', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'as_json': 'error', 'order': 'ascending', 'debug': True }, { 'stock': 'BBVA', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'as_json': False, 'order': 'error', 'debug': True }, { 'stock': 'BBVA', 'country': 'spain', 'from_date': 'error', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'stock': 'BBVA', 'country': 'spain', 'from_date': '01/01/2019', 'to_date': 'error', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'stock': 'error', 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'stock': ['error'], 'country': 'spain', 'from_date': '01/01/2018', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'stock': 'BBVA', 'country': 'spain', 'from_date': '01/01/1999', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'stock': 'BBVA', 'country': 'spain', 'from_date': '01/01/1900', 'to_date': '01/01/1950', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'stock': 'BBVA', 'country': 'spain', 'from_date': '01/01/1950', 'to_date': '01/01/2019', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'stock': 'BBVA', 'country': 'spain', 'from_date': '01/01/2019', 'to_date': '01/01/1999', 'as_json': False, 'order': 'ascending', 'debug': True }, { 'stock': 'BBVA', 'country': 'spain', 'from_date': '01/01/2019', 'to_date': '01/03/2019', 'as_json': False, 'order': 'ascending', 'debug': 'error' }, ] for param in params: try: investpy.get_stock_historical_data(stock=param['stock'], country=param['country'], from_date=param['from_date'], to_date=param['to_date'], as_json=param['as_json'], order=param['order'], debug=param['debug']) except: pass params = [ { 'stock': None, 'country': 'spain', 'language': 'spanish' }, { 'stock': 'BBVA', 'country': None, 'language': 'spanish' }, { 'stock': 'BBVA', 'country': 'greece', 'language': 'spanish' }, { 'stock': 'BBVA', 'country': 'spain', 'language': 'error' }, { 'stock': 'error', 'country': 'spain', 'language': 'spanish' }, { 'stock': ['error'], 'country': 'spain', 'language': 'spanish' }, ] for param in params: try: investpy.get_stock_company_profile(stock=param['stock'], country=param['country'], language=param['language']) except: pass params = [ { 'stock': None, 'country': 'spain', }, { 'stock': ['error'], 'country': 'spain', }, { 'stock': 'bbva', 'country': ['error'], }, { 'stock': 'bbva', 'country': 'error', }, { 'stock': 'error', 'country': 'spain', }, { 'stock': 'ALUA', 'country': 'argentina', }, ] for param in params: try: investpy.get_stock_dividends(stock=param['stock'], country=param['country']) except: pass params = [ { 'by': None, 'value': 'BBVA', }, { 'by': ['error'], 'value': 'BBVA', }, { 'by': 'error', 'value': 'BBVA', }, { 'by': 'name', 'value': None, }, { 'by': 'name', 'value': ['error'], }, { 'by': 'isin', 'value': 'BBVA', }, ] for param in params: try: investpy.search_stocks(by=param['by'], value=param['value']) except: pass
def get_company_summary(symbol): summary_text = inp.get_stock_company_profile(stock=symbol, country='turkey')['desc'] return summary_text
def test_investpy_stocks(): """ This function checks that stock data retrieval functions listed in investpy work properly. """ params = [ { 'country': 'spain', }, { 'country': None, }, ] for param in params: investpy.get_stocks(country=param['country']) investpy.get_stocks_list(country=param['country']) params = [ { 'country': None, 'columns': ['full_name', 'name'], 'as_json': True }, { 'country': None, 'columns': ['full_name', 'name'], 'as_json': False }, { 'country': 'spain', 'columns': ['full_name', 'name'], 'as_json': True }, { 'country': 'spain', 'columns': ['full_name', 'name'], 'as_json': False }, { 'country': 'spain', 'columns': None, 'as_json': False }, ] for param in params: investpy.get_stocks_dict(country=param['country'], columns=param['columns'], as_json=param['as_json']) investpy.get_stock_countries() params = [ { 'as_json': True, 'order': 'ascending', }, { 'as_json': False, 'order': 'ascending', }, { 'as_json': True, 'order': 'descending', }, { 'as_json': False, 'order': 'descending', }, ] for param in params: investpy.get_stock_recent_data(stock='BBVA', country='spain', as_json=param['as_json'], order=param['order'], interval='Daily') investpy.get_stock_historical_data(stock='BBVA', country='spain', from_date='01/01/1990', to_date='01/01/2019', as_json=param['as_json'], order=param['order'], interval='Daily') for value in ['spanish', 'english']: investpy.get_stock_company_profile(stock='BBVA', country='spain', language=value) params = [ { 'stock': 'bbva', 'country': 'spain', 'as_json': False }, { 'stock': 'bbva', 'country': 'spain', 'as_json': True }, { 'stock': 'HSBK', 'country': 'kazakhstan', 'as_json': False } ] for param in params: investpy.get_stock_information(stock=param['stock'], country=param['country'], as_json=param['as_json']) params = [ { 'country': 'spain', 'as_json': True, 'n_results': 50 }, { 'country': 'united states', 'as_json': False, 'n_results': 50 }, { 'country': 'bosnia', 'as_json': False, 'n_results': 50 }, { 'country': 'palestine', 'as_json': False, 'n_results': 50 }, { 'country': 'dubai', 'as_json': False, 'n_results': 50 }, { 'country': 'ivory coast', 'as_json': False, 'n_results': 50 } ] for param in params: investpy.get_stocks_overview(country=param['country'], as_json=param['as_json'], n_results=param['n_results']) params = [ { 'stock': 'bbva', 'country': 'spain' }, { 'stock': 'entel', 'country': 'chile' } ] for param in params: investpy.get_stock_dividends(stock=param['stock'], country=param['country']) params = [ { 'stock': 'bbva', 'country': 'spain', 'summary_type': 'balance_sheet', 'period': 'annual' }, { 'stock': 'aapl', 'country': 'united states', 'summary_type': 'income_statement', 'period': 'quarterly' }, { 'stock': 'barc', 'country': 'united kingdom', 'summary_type': 'cash_flow_statement', 'period': 'annual' } ] for param in params: investpy.get_stock_financial_summary(stock=param['stock'], country=param['country'], summary_type=param['summary_type'], period=param['period']) investpy.search_stocks(by='name', value='BBVA')
def test_investpy_stocks(): """ This function checks that stock data retrieval functions listed in investpy work properly. """ params = [ { 'country': 'spain', }, { 'country': None, }, ] for param in params: investpy.get_stocks(country=param['country']) investpy.get_stocks_list(country=param['country']) params = [ { 'country': None, 'columns': ['full_name', 'name'], 'as_json': True }, { 'country': None, 'columns': ['full_name', 'name'], 'as_json': False }, { 'country': 'spain', 'columns': ['full_name', 'name'], 'as_json': True }, { 'country': 'spain', 'columns': ['full_name', 'name'], 'as_json': False }, { 'country': 'spain', 'columns': None, 'as_json': False }, ] for param in params: investpy.get_stocks_dict(country=param['country'], columns=param['columns'], as_json=param['as_json']) investpy.get_stock_countries() params = [ { 'as_json': True, 'order': 'ascending', 'debug': False }, { 'as_json': False, 'order': 'ascending', 'debug': True }, { 'as_json': True, 'order': 'descending', 'debug': False }, { 'as_json': False, 'order': 'descending', 'debug': False }, ] for param in params: investpy.get_stock_recent_data(stock='BBVA', country='spain', as_json=param['as_json'], order=param['order'], debug=param['debug']) investpy.get_stock_historical_data(stock='BBVA', country='spain', from_date='01/01/1990', to_date='01/01/2019', as_json=param['as_json'], order=param['order'], debug=param['debug']) for value in ['spanish', 'english']: investpy.get_stock_company_profile(stock='BBVA', country='spain', language=value) investpy.get_stock_dividends(stock='BBVA', country='spain') investpy.search_stocks(by='name', value='BBVA')
# https://investpy.readthedocs.io/_info/introduction.html # Retrieve all the available stocks as a Python list stocks = investpy.get_stocks_list() funds = investpy.get_funds_list() etfs = investpy.get_etfs_list() # Retrieve the recent historical data (past month) of a stock as a pandas.DataFrame on ascending date order df_bbva = investpy.get_stock_recent_data(stock='bbva', country='spain', as_json=False, order='ascending') # Retrieve the company profile of the introduced stock on english profile = investpy.get_stock_company_profile(stock='bbva', country='spain', language='english') df_aapl = investpy.get_stock_historical_data(stock='AAPL', country='United States', from_date='01/01/2010', to_date='01/01/2020') df_fund = investpy.get_fund_historical_data( fund='bbva plan multiactivo moderado pp', country='spain', from_date='01/01/2010', to_date='01/01/2019') df_bbva_etf = investpy.get_etf_recent_data(etf='bbva accion dj eurostoxx 50', country='spain')
def get_company_profile(a): company_profile = investpy.get_stock_company_profile(stock=a, country='malaysia') return company_profile.get('desc','')
#stocks_prices # libraries import investpy as inv # declarations # execution preco = inv.get_stock_company_profile('IBFF11', 'brazil') print(preco)
def update_graph(ticker, selected_sector): # Get company info company_info = investpy.get_stock_company_profile( ticker, country='malaysia')['desc'] # Get sector volume if selected_sector == 'All': all_sec_list = lookup['sector'].unique().tolist() sec_vol_list = [] for sec in all_sec_list: sec_vol_list.append(get_sector_vol(sec)) sector_volume = sum(sec_vol_list) else: sector_volume = get_sector_vol(selected_sector) # Get latest closed price and volume for selected stock data = get_stock_data(ticker) latest_sto_close = data.iloc[-1]['Close'] latest_sto_vol = data.iloc[-1]['Volume'] # Get stock percentage contribution of volume percentage = (latest_sto_vol) / (sector_volume) * 100 percentage_str = "{0:.5f}%".format(percentage) # Set up overlap graphs figure = plotly.subplots.make_subplots(specs=[[{"secondary_y": True}]]) figure.add_trace( go.Scatter(x=data['Date'], y=data['Close'], mode="lines", name='Stock Price'), secondary_y=False, ) figure.add_trace(go.Bar(x=data['Date'], y=data['Volume'], name='Volume Traded'), secondary_y=True) # Set x-axis title figure.update_xaxes(title_text="Date") # Set y-axes titles figure.update_yaxes(title_text="Volume traded", secondary_y=True) figure.update_yaxes(title_text="Price (RM)", secondary_y=False) figure.update_xaxes( rangeslider_visible=True, rangeselector=dict(buttons=list([ dict(count=7, label="1w", step="day", stepmode="backward"), dict(count=1, label="1m", step="month", stepmode="backward"), dict(count=6, label="6m", step="month", stepmode="backward"), dict(count=1, label="1y", step="year", stepmode="backward"), dict(step="all") ])), rangebreaks=[ dict(enabled=True, bounds=['sat', 'mon']), #hide weekends (not working atm) ]) figure.update_layout( autosize=True, # height=380, # width = 850, margin=dict(l=55, r=15, b=50, t=50, pad=0), legend=dict(x=0.7, y=1.05, orientation='h'), ) return ([ company_info, latest_sto_close, latest_sto_vol, sector_volume, percentage_str, figure ])