def verificar(ativo: str) -> bool: """ :param ativo: Recebe o código de uma ação. :return: Retorna True se a ação recebida existir no pacote investpy. """ return True if ativo in [x for x in get_stocks('brazil')['symbol'] ] else False
def get_companies(): companies = inp.get_stocks(country='turkey') companies.columns = [ 'Ülke', 'Kısa İsim', 'Şirket', 'ISIN', 'Para Birimi', 'Sembol' ] companies = companies.set_index('Sembol') return companies
def get_stock_lists(): '''Retrieve stock lists as dataframe tables, from investpy library''' stocks = investpy.get_stocks() etfs = investpy.get_etfs() indices = investpy.get_indices() return stocks, etfs, indices
def main(): # Group issue #1 Issue 229 # tester = investpy.get_stock_historical_data(stock='AAPL', country='United States') # print(tester) # Group issue #2 issue 203 data = investpy.get_stocks(country='India') print(data)
def _build_index(self): def with_index(df, type, column, new_name="symbol"): if not "country" in df: df["country"] = "unknown" else: df["country"] = df["country"].replace({ None: "unknown", "": "unknown" }).fillna('unknown') df.index = pd.MultiIndex.from_tuples([ (s, type, c) for s, c in zip(df[column].to_list(), df["country"].to_list()) ]).rename([ new_name if new_name is not None else column, "type", "country" ]) df = df.drop([column, "country"], axis=1) df = df.drop(df.index[df.index.duplicated('first')], axis=0) return df.loc[df.index.dropna()] symbols_df = pd.concat( [ with_index(ip.get_bonds(), "BOND", "name"), # country "name" full_name with_index( ip.get_certificates(), "CERT", "symbol" ), # country', 'name', 'full_name', '"symbol"', 'issuer', 'isin', 'asset_class', 'underlying' with_index(ip.get_cryptos(), "CRYPTO", "symbol"), # 'name', '"symbol"', 'currency' with_index( ip.get_commodities(), "COMM", "name" ), # 'title', 'country', '"name"', 'full_name', 'currency', 'group' with_index( ip.get_etfs(), "ETF", "symbol" ), # 'country', 'name', 'full_name', '"symbol"', 'isin', 'asset_class', 'currency', 'stock_exchange', 'def_stock_exchange' # with_index(ip.get_funds(), "FUND", "isin"), # 'country', 'name', 'symbol', 'issuer', '"isin"', 'asset_class', 'currency', 'underlying' with_index( ip.get_indices(), "INDEX", "symbol" ), # 'country', 'name', 'full_name', '"symbol"', 'currency', 'class', 'market' with_index( ip.get_stocks(), "STOCK", "symbol" ), # ['country', 'name', 'full_name', 'isin', 'currency', '"symbol"' with_index( pd.DataFrame( [f'{c}/USD' for c in ip.get_available_currencies()], columns=['symbol']), "FX", "symbol") ], axis=0) # update the index table upsert(self.engine, symbols_df, DataProvider.symbols_table_name, if_row_exists='ignore')
def lessrisk_moregains(self,datei,datef,index_,qts): country_='Brazil' ##I don't know how the symbols of stocks in other country works, so i will limit my code to Brazil symbols = inv.get_stocks(country=country_).symbol my_rank = pd.DataFrame({'symb':[],'abv_bench_mean':[],'beta':[],'ratio':[]}) bench_hist = inv.get_index_historical_data(index=index_,country=country_,from_date=datei,to_date=datef,interval="Monthly").Open bench_hist_change = bench_hist[bench_hist!=0].pct_change() bench_hist_change = bench_hist_change.dropna() how_many_errors=0 ###counts how many unavailable assets for symb in symbols: if symb[-1]!='3': continue ##There's some stocks names listed in inv.get_stocks that information is unavailable ##so i will do a test first works=False try: asset_hist = inv.get_stock_historical_data(stock=symb,country=country_,from_date=datei,to_date=datef,interval="Monthly").Open asset_hist_change = asset_hist[asset_hist!=0].pct_change() asset_hist_change = asset_hist_change.dropna() works=True sort = pd.DataFrame({'benchmark':bench_hist_change,'asset':asset_hist_change}).dropna().reset_index() except: if(how_many_errors<30): how_many_errors+=1 print("Sorry, but "+symb+" is not available, it will be excluded from the rank") print("How many unavailable:"+str(how_many_errors)) if(how_many_errors==30): print("More than 30 assets unavailable, it could be a connection problem") how_many_errors+=1 pass ##sort = data sorted by common dates and delete dates not in common if (works)and(len(sort.benchmark)!=0)and(len(sort.asset)!=0): beta = line(sort.benchmark,sort.asset)[0] if(beta<=0): continue abv_bench = sort.asset-sort.benchmark abv_bench_mean = abv_bench.mean() ratio = abv_bench_mean/beta add={'symb':symb,'abv_bench_mean':(str(round(abv_bench_mean*100,2))+"%"),'beta':round(beta,4),'ratio':ratio} my_rank = my_rank.append(add,ignore_index=True) my_rank = my_rank.sort_values(by='ratio',ascending=False).head(qts) my_rank = my_rank.drop('ratio',1) fig,ax = plt.subplots(figsize=[10,5]) ax.set_title("Top "+str(qts)+" stocks with highest gains above "+index_+" index and lowest risks in "+country_) period_string = ("Period: "+datei +" to "+datef) ax.set_xlabel("Average monthly relative rentability(AMRR)="+" Average gains above Benchmark("+index_+" Index)\n"+period_string) plt.xticks([]) plt.yticks([]) ax.table(bbox=[0,0.1,1,0.8],rowLabels=range(1,qts+1),colLabels=['Symbol','AMRR','Beta(risk)'],cellText=my_rank.values,loc='center',rowLoc='center',cellLoc='center') fig.savefig('Rank.png') plt.show()
def get_tickers(country): # function to get a dictionary of all tickers/stocks available # in a specific country try: tickers_df = investpy.get_stocks(country=country.lower()) except: tickers_df = pd.DataFrame(data=dict(name=['No results'], symbol=['No results']) ) # extract names and symbols tickers_df.loc[:, 'name'] = tickers_df.loc[:, 'name'].apply(lambda x: x.strip('u200b') ) labels= [', '.join(i) for i in tickers_df.loc[:, ['name','symbol']].values] values = tickers_df.loc[:, ['symbol']].values.T[0] tickers_dict = [{'label':i, 'value':j} for i,j in zip(labels, values)] return tickers_dict
def getStocksIsin(n_asset_mkt): country = "united states" df = pd.DataFrame(inv.get_stocks(country=country)) df = np.array(df["isin"]) array_pulito = [] for i in df: if i[:2] == "US": array_pulito.append(i) df = pd.DataFrame(array_pulito) df.columns = ["Isin"] head = df[:n_asset_mkt].values.tolist() return head
def getStocks(country): # function to get a dictionary of all tickers/stocks available # in a specific country try: dfStocks = investpy.get_stocks(country=country.lower()) except: dfStocks = pd.DataFrame( data=dict(name=['No results'], symbol=['No results'])) # extract names/labels and symbols dfStocks.sort_values('name', inplace=True) dfStocks.loc[:, 'name'] = dfStocks.loc[:, 'name'].apply( lambda x: x.strip('u200b')) labels = [', '.join(i) for i in dfStocks.loc[:, ['name', 'symbol']].values] values = dfStocks.loc[:, ['symbol']].values.T[0] dictStocks = [{'label': i, 'value': j} for i, j in zip(labels, values)] return dictStocks
def getStocksIsin(n_asset_mkt): df = pd.DataFrame(inv.get_stocks( country=country_isin.get("US"))) #get infos about US market df = np.array(df["isin"]) array_pulito = [] for i in df: if i[:2] == "US": array_pulito.append(i) df = pd.DataFrame(array_pulito) df.columns = ["Isin"] head = df[:n_asset_mkt].values.tolist() #get first n_asset_mkt head_lista = [] for i in head: head_lista.append(i[0]) return head_lista #First 15obs from mkt
def getSoaringStock(): currentDate = datetime.datetime.today().strftime('%d/%m/%Y') startDate = (datetime.datetime.today() - datetime.timedelta(soaringGap)).strftime('%d/%m/%Y') stocks = investpy.get_stocks(country='United States') i = 0 soaringStocks = [] for s in stocks['symbol']: try: com = investpy.get_stock_historical_data(stock=s, country='United States', from_date=startDate, to_date=currentDate) avgVol = 0 currentVol = com['Volume'][len(com) - 1] for data in com['Volume']: avgVol += int(data) avgVol -= currentVol avgVol = avgVol / (len(com) - 1) isSoaringStock = (currentVol >= avgVol * 8) # 800% if (isSoaringStock and avgVol != 0 and currentVol != 0): soaringStocks.append(s) print(f'[Info] {s}') print(f'Mean: {avgVol}') print(f'Current: {currentVol}') print(f'SoaringStock: {isSoaringStock}') else: i += 1 print(f'[{i}/{len(stocks)}] {s}') except: i += 1 print(f'[{i}/{len(stocks)}] {s} - Err') print(soaringStocks)
import investpy from TrieStruct import * import sqlite3 import pandas as pd from datetime import datetime import CurrencyManager as cm #initialization stocks_usa = investpy.get_stocks('United States') stocks_kor = investpy.get_stocks('South Korea') stocks = pd.concat([stocks_usa, stocks_kor]) stocks_name_temp = list(stocks['name']) stocks_code = list(stocks['symbol']) stocks_country = list(stocks['country']) stocks_name = [] for sc in stocks_name_temp: scu = sc.upper() stocks_name.append(scu) stocks_dict_code_name = { name: value for name, value in zip(stocks_code, stocks_name) } stocks_dict_name_code = { code: value for code, value in zip(stocks_name, stocks_code) } stocks_dict_code_country = { country: value
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')
""" Get stock data """ import datetime import time import investpy import pymysql while True: with open("/password1.txt", "r") as f: connection = pymysql.connect(host="fumire.moe", user="******", password=f.readline().strip(), db="fumiremo_StockDB", charset="utf8", port=3306) cursor = connection.cursor(pymysql.cursors.DictCursor) for country in ["south korea", "japan", "united states"]: print(country) for _, row1 in investpy.get_stocks(country=country).iterrows(): print("-", row1["name"]) for date, row2 in investpy.get_stock_historical_data(stock=row1["symbol"], country=country, from_date="01/01/1900", to_date=datetime.datetime.today().strftime("%d/%m/%Y"), order="descending").iterrows(): query = "SELECT * FROM `StockData` WHERE `country` LIKE '%s' AND `Name` LIKE '%s' AND `Symbol` LIKE '%s' AND `Date` = '%s'" % (country, row1["name"], row1["symbol"], date.date()) cursor.execute(query) if cursor.fetchall(): break query = "INSERT INTO `StockData` (`IndexColumn`, `Country`, `Name`, `Symbol`, `Date`, `Open`, `High`, `Low`, `Close`, `Volume`, `Currency`) VALUES (NULL, '%s', '%s', '%s', '%s', '%f', '%f', '%f', '%f', '%d', '%s');" % (country, row1["name"], row1["symbol"], date.date(), row2["Open"], row2["High"], row2["Low"], row2["Close"], row2["Volume"], row2["Currency"]) cursor.execute(query) print("--", date.date()) connection.close()
type="candle", mav=(2, 4, 6), volume=True, ylabel="OHLC Candles") mc = mpf.make_marketcolors(up="r", down="b", inherit=True) s = mpf.make_mpf_style(marketcolors=mc) mpf.plot(investpy_candle_chart, **kwargs, style=s) ######################################################################################################################## # 현재 접근 가능한 국가 리스트 countriesAvailable = investpy.get_certificate_countries() print(countriesAvailable) # 현재 접근 가능한 주식 currentCountry = countriesAvailable[1] stocks = investpy.get_stocks(currentCountry) print(stocks) print(type(stocks)) # 미국 ETF 리스트 검색 df_us_etf = investpy.get_etfs(country='United States') df_us_etf_search = df_us_etf[df_us_etf['symbol'].str.contains("IEF")] countriesAvailable = investpy.get_index_countries() investpy.indices.get_indices_list(country=None) list_indices = investpy.indices.get_indices_list(country='United States') # investpy 패키지를 사용하여 KOSPI 자료 받기 investpy_kospi = investpy.get_index_historical_data(index="KOSPI", country="south korea",
def create_data(apps, schema_editor): Stock = apps.get_model("stocks", "Stock") stocks = inv.get_stocks("brazil") for stock in stocks.itertuples(): Stock(symbol=stock.symbol, name=stock.name).save()
bond_sheet = 'bonds' etf_sheet = 'etfs' crypto_sheet = 'cryptos' home_sheet = 'Home' fund_country = xw.sheets[home_sheet].range('F3').value index_country = xw.sheets[home_sheet].range('F4').value stock_country = xw.sheets[home_sheet].range('F5').value bond_country = xw.sheets[home_sheet].range('F6').value etf_country = xw.sheets[home_sheet].range('F7').value req_funds = investpy.get_funds(country=fund_country) req_indices = investpy.get_indices(country=index_country) req_stocks = investpy.get_stocks(country=stock_country) req_bonds = investpy.get_bonds(country=bond_country) req_etfs = investpy.get_etfs(country=etf_country) def GetFunds(): wb = xw.Book.caller() wb.sheets[fund_sheet].range('D1').value = req_funds def GetIndices(): wb = xw.Book.caller() wb.sheets[index_sheet].range('D1').value = req_indices
def main(): """ Despliega un menú de opciones en la consola del terminal """ ot1 = 0 ValorGrafico = Valor() while ot1 == 0: # Primer while principal para la identificación del código y el país del valor global num_exis num_exis = 0 a = -1 while a != 1 and a != 2 and a != 3: # Bucle que repite la opción de la elección de lista print( "\n\nEste programa realiza recomendaciones de compra o venta de un valor según un análisis técnico con los datos obtenidos de Investing.com\n" ) print("(1) Ver lista de países ") print("(2) Ver lista de valores de todos los países ") print("(3) Ver lista de valores según el país ") a = int(input("\n¿Qué desea hacer?\n")) if a == 1: # Se imprimen todos los países que están registrados en el mercado de valores for i in investpy.get_stock_countries(): print("País {}: {}".format( investpy.get_stock_countries().index(i) + 1, i)) elif a == 2: # Se imprime un panda.DataFrame de todos los valores sin importar el país print(investpy.get_stocks(country=None)) elif a == 3: # Se imprime un panda.DataFrame de todos los valores según el país indicado otra = 1 while otra != 0: try: b = input("Escribe el país de donde quieres buscar:\n") print(investpy.get_stocks(country=b)) otra = 0 except ValueError: # Evita que se ejecute el error ValueError cuando la palabra insertada no se encuentra entre los países de la lista print("Escribe un pais existente\n") ott = 1 while ott != 0: # Permite la opción de salida del primer bucle while principal ot = str(input("¿Desea ver otra lista? Sí(S) o No (N):\n")) if ot == 'S' or ot == 's': ot1 = 0 ott = 0 elif ot == 'N' or ot == 'n': ot1 = 1 ott = 0 else: ott = 1 ot2 = 0 while ot2 == 0: # Segundo while principal para ingresar el país y el valor, o salir del programa a1 = -1 while a1 != 1 and a1 != 2: # Bucle que repite la opción de la elección de continuar con el análisis o salir del programa print( "\nElija si desea realizar un análisis técnico de un valor en el mercado de valores\n" ) print("(1) Analizar un valor ") print("(2) Salir ") a1 = int(input("\n¿Qué desea hacer?\n")) if a1 == 1: # Se ingresa el país y el valor para su análisis técnico otr = 1 while otr != 0: try: print("¿Qué valor deseas ver?\n") pais = input( "Ingresa el país (Segunda columna en la lista de valores)\n" ) stock_valor = input( "Ingresa el código del valor (Séptima columna en la lista de valores)\n" ).upper() p = 0 while p == 0: # Permite la opción de especificar un rango de tiempo p1 = str( input( "¿Desea establecer un rango de tiempo? Sí(S) o No (N):\n" )) if p1 == 'S' or p1 == 's': print( "Escriba el rango de tiempo con el formato (dd/mm/aaaa)" ) pi = str(input("Escriba el día de inicio : ")) pf = str(input("Escriba el día de término: ")) df = extraer(1, stock_valor, pais, pi, pf) print(df) mpf.plot( df, axtitle=f'Gráfica del valor (De {pi} a {pf})', style='yahoo', xrotation=15, type='candle') mpf.show() p = 1 elif p1 == 'N' or p1 == 'n': df = extraer(2, stock_valor, pais) print(df) mpf.plot( df, axtitle='Gráfica del valor (últimos 30 días)', style='yahoo', xrotation=15, type='candle') mpf.show() p = 1 else: p = 0 otr = 0 except ValueError: print("Escribe un país existente\n") elif a1 == 2: # Sale del programa break otq = 0 while otq == 0: z = -1 while z != 1 and z != 2 and z != 3: # Bucle que repite la opción de la elección de indicador print("\n¿Cuál indicador deseas ver?\n") print( "(1) RSI (Relative Strength Index) " ) print( "(2) SMA (Simple Moving Average) " ) print( "(3) Ambos " ) z = int(input("\n¿Qué desea hacer?\n")) indic1 = Indicador_tecnico(df) if z == 1: indic1.RSI() t = "RSI" elif z == 2: indic1.SMA() t = "SMA" elif z == 3: indic1.All() Grafico(indic1, indic1._RSI, indic1._SMA) señ1 = señal(z, stock_valor, pais) if z != 3: print( f"\n\nEl indicador {t} en el valor búrsatil '{señ1[0]}' es de {señ1[1]}, e indica que se recomienda {señ1[2]}.\n\n" ) else: print( f"\n\nCon el valor búrsatil '{señ1[0]}', con el indicador RSI, el cual es de {señ1[1]}, recomienda {señ1[2]}; mientras que el indicador SMA, el cual es de {señ1[3]}, recomienda {señ1[4]}.\n\n" ) ott2 = 1 while ott2 != 0: # Permite la opción de salida del bucle while otp = str(input( "¿Desea ver otro indicador? Sí(S) o No (N):\n")).upper() if otp == 'S': otq = 0 ott2 = 0 elif otp == 'N': otq = 1 ott2 = 0 else: ott2 = 1 ValorGrafico.agregar_valor(stock_valor, indic1) otw = 0 while otw == 0: ddd = 1 while ddd != 0: # Permite la opción de salida del bucle while otp5 = str( input( "¿Desea ver algún valor registrado? Sí(S) o No (N):\n") ).upper() if otp5 == 'S': otw = 0 ddd = 0 elif otp5 == 'N': otw = 1 ddd = 0 break else: ddd = 1 if otp5 == 'S': valReg = str( input( "Escriba el símbolo del valor registrado que quiere buscar: " )).upper() VR = ValorGrafico.mostrar_valor(valReg) elif otp5 == 'N': break Grafico(VR[0], VR[1], VR[2]) if VR[1] == 1 and VR[2] == 0: t1 = "RSI" z1 = 1 elif VR[1] == 0 and VR[2] == 1: t1 = "SMA" z1 = 2 elif VR[1] == 1 and VR[2] == 1: z1 = 3 señ2 = señal(z1, valReg, pais) if z1 != 3: print( f"\n\nEl indicador {t1} en el valor búrsatil '{señ2[0]}' es de {señ2[1]}, e indica que se recomienda {señ2[2]}.\n\n" ) else: print( f"\n\nCon el valor búrsatil '{señ2[0]}', con el indicador RSI, el cual es de {señ2[1]}, recomienda {señ2[2]}; mientras que el indicador SMA, el cual es de {señ2[3]}, recomienda {señ2[4]}.\n\n" ) ott2 = 1 while ott2 != 0: # Permite la opción de salida del bucle while otp7 = str( input( "¿Desea ver otro valor registrado? Sí(S) o No (N):\n")) if otp7 == 'S' or otp7 == 's': otw = 0 ott2 = 0 elif otp7 == 'N' or otp7 == 'n': otw = 1 ott2 = 0 break else: ott2 = 1 valReg = str( input( "Escriba el símbolo del valor registrado que quiere buscar: " )).upper() ValorGrafico.mostrar_valor(valReg) VR1 = ValorGrafico.mostrar_valor(valReg) Grafico(VR1[0], VR1[1], VR1[2]) if VR1[1] == 1 and VR1[2] == 0: t2 = "RSI" z2 = 1 elif VR1[1] == 0 and VR1[2] == 1: t2 = "SMA" z2 = 2 elif VR1[1] == 1 and VR1[2] == 1: z2 = 3 señ3 = señal(z2, valReg, pais) if z2 != 3: print( f"\n\nEl indicador {t2} en el valor búrsatil '{señ3[0]}' es de {señ3[1]}, e indica que se recomienda {señ3[2]}.\n\n" ) else: print( f"\n\nCon el valor búrsatil '{señ3[0]}', con el indicador RSI, el cual es de {señ3[1]}, recomienda {señ3[2]}; mientras que el indicador SMA, el cual es de {señ3[3]}, recomienda {señ3[4]}.\n\n" ) ott3 = 1 while ott3 != 0: # Permite la opción de salida del segundo bucle while principal otp3 = str(input("¿Desea ver otro valor? Sí(S) o No (N):\n")) if otp3 == 'S' or otp3 == 's': ot2 = 0 ott3 = 0 elif otp3 == 'N' or otp3 == 'n': ot2 = 1 ott3 = 0 else: ott3 = 1
def validate(self): """ Method used to validate that the introduced Stock is valid before adding it to the StockPortfolio. This method is the one in charge of the validation of the introduced Stock via checking the introduced data with the one indexed in investpy, so to check if the data match. Also, the introduced parameters are checked in order to determine if the type is correct of those values is correct, if not, an exception will be raised. The result of this function is just setting either True or False to the self.valid value if the Stock is valid or not, respectively. """ if not isinstance(self.stock_symbol, str): raise ValueError( "ERROR [0005]: The introduced stock_symbol is mandatory and should be a str." ) if not isinstance(self.stock_country, str): raise ValueError( "ERROR [0006]: The introduced stock_country is mandatory and should be a str." ) try: datetime.datetime.strptime(self.purchase_date, '%d/%m/%Y') except ValueError: raise ValueError( "ERROR [0007]: The introduced purchase_date is not properly formatted (dd/mm/yyyy)." ) purchase_date_ = datetime.datetime.strptime(self.purchase_date, '%d/%m/%Y') if purchase_date_ > datetime.datetime.now(): raise ValueError( "ERROR [0008]: The introduced purchase_date is not valid since it should be earlier than " "the current date.") if not isinstance(self.num_of_shares, int): raise ValueError( "ERROR [0009]: The introduced num_of_shares is mandatory and should be an int higher " "than 0.") else: if self.num_of_shares <= 0: raise ValueError( "ERROR [0009]: The introduced num_of_shares is mandatory and should be an int higher " "than 0.") if not isinstance(self.cost_per_share, float): raise ValueError( "ERROR [0010]: The introduced cost_per_share is mandatory and should be a float higher " "than 0.") else: if self.cost_per_share <= 0: raise ValueError( "ERROR [0010]: The introduced Stock is not valid.") stock_countries = investpy.get_stock_countries() if self.stock_country.lower() in stock_countries: stocks = investpy.get_stocks(country=self.stock_country) search_results = stocks[stocks['symbol'].str.lower() == self.stock_symbol.lower()] if len(search_results) > 0: data = investpy.get_stock_historical_data( stock=self.stock_symbol, country=self.stock_country, from_date=self.purchase_date, to_date=datetime.date.today().strftime("%d/%m/%Y")) try: purchase_date_ = purchase_date_.strftime("%Y-%m-%d") min_value = data.loc[purchase_date_]['Low'] max_value = data.loc[purchase_date_]['High'] except KeyError: raise KeyError( "ERROR [0004]: The introduced purchase_date is not valid since the market was " "closed.") if min_value <= self.cost_per_share <= max_value: self.valid = True else: raise ValueError( "ERROR [0011]: The introduced value is not possible, because the range stock " "values of the purchase data were between " + str(min_value) + " and " + str(max_value)) else: raise ValueError( "ERROR [0003]: No results were found for the introduced stock_symbol in the specified " "stock_country.") else: raise ValueError( "ERROR [0002]: The introduced stock_country is not valid or does not have any indexed " "stock.")
def my_get_stocks(country=None): return investpy.get_stocks(country=country)
def update_model(apps, schema_editor): Stock = apps.get_model("stocks", "Stock") stocks = inv.get_stocks("brazil") for index, stock in stocks.iterrows(): new_stock = Stock(symbol=stock.symbol, name=stock["name"], price=0.00) new_stock.save()
# In[84]: #!pip install investpy yfinance import investpy from datetime import datetime import yfinance as yf import pandas as pd # In[69]: # Retrieve all the available stocks as a Python list investpy.get_stocks(country='brazil') # In[70]: # Retrieve all the available etfs as a Python list investpy.get_etfs(country='brazil') # In[138]: # Retrieve all the indexes investpy.get_indices()
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_stock_info(self, stock): """ Method to get the stock information once it is validated. This method retrieves the historical data of the introduced Stock in order to get its current price which will be used for the required calculations to generate the StockPortfolio. So on, this function is both going to retrieve Stock data and calculate the required values for the StockPortfolio. Args: stock (:obj:`pyrtfolio.Stock`): Stock object with all its information after validated. Returns: :obj:`dict` - stock_information: Returns a :obj:`dict` which contains all the values from the introduced Stock in order to create its portfolio row. """ stocks = investpy.get_stocks(country=stock.stock_country) stock_name = stocks.loc[(stocks['symbol'].str.lower() == stock.stock_symbol.lower()).idxmax(), 'name'] data = investpy.get_stock_historical_data( stock=stock.stock_symbol, country=stock.stock_country, from_date=stock.purchase_date, to_date=date.today().strftime("%d/%m/%Y")) currency = data['Currency'][0] purchase_cost = self.calculate_purchase_cost( cost_per_share=stock.cost_per_share, num_of_shares=stock.num_of_shares) current_price = self.get_current_price(data=data) gross_current_value = self.calculate_gross_current_value( current_price=current_price, num_of_shares=stock.num_of_shares) dividends = investpy.get_stock_dividends(stock=stock.stock_symbol, country=stock.stock_country) dividends = dividends.loc[dividends['Payment Date'] < pd.to_datetime( stock.purchase_date, dayfirst=True)].reset_index(drop=True) if len(dividends) > 0: total_dividends = self.calculate_total_dividends( dividends=dividends, num_of_shares=stock.num_of_shares) else: total_dividends = 0 net_current_value = self.calculate_net_current_value( gross_current_value=gross_current_value, total_dividends=total_dividends) total_gain_loss = self.calculate_total_gain_loss( net_current_value=net_current_value, purchase_cost=purchase_cost) total_gain_loss_percentage = self.calculate_total_gain_loss_percentage( total_gain_loss=total_gain_loss, purchase_cost=purchase_cost) info = { 'stock_symbol': stock.stock_symbol, 'stock_name': stock_name, 'stock_country': stock.stock_country, 'stock_currency': currency, 'purchase_date': stock.purchase_date, 'num_of_shares': stock.num_of_shares, 'cost_per_share': stock.cost_per_share, 'purchase_cost': purchase_cost, 'current_price': current_price, 'gross_current_value': gross_current_value, 'total_dividends': total_dividends, 'net_current_value': net_current_value, 'total_gain_loss': total_gain_loss, 'total_gain_loss_percentage': total_gain_loss_percentage, } return info