def load_data(cls): # Read data from file logging.info(f'Reading data from: {cls.lc_file.name}') logging.info(f'Working in directory: {cls.lc_file.parent.resolve()}') try: time, flux, flux_err = np.loadtxt(cls.lc_file, unpack=True) except ValueError: try: time, flux = np.loadtxt(cls.lc_file, unpack=True) except ValueError: logging.error( f"Error: Couldn't load data from the lc_file: {cls.lc_file}" ) sys.exit(1) if cls.settings.include_errors: if flux_err is None: logging.error( f"Error: Need a flux_err column when include_errors is True" ) sys.exit(1) # Convert time to days and flux and err to ppm (if needed). Make copy to separate memory of arrays for C cls.time = time.copy() # keep days # cls.time = time.copy() / (24.*3600.) # seconds to days # cls.flux = flux.copy() # keep ppm cls.flux = (flux.copy() - 1.0) * 1e6 # frac to ppm if cls.settings.include_errors: # cls.flux_err = flux_err.copy() # keep ppm cls.flux_err = flux_err.copy() * 1e6 # frac to ppm
def outlet(self, unit, own_data=True): c_double_p = ctypes.POINTER(ctypes.c_double) time_ptr = c_double_p() data_ptr = c_double_p() n_time = ctypes.c_int() n_ports = ctypes.c_int() n_comp = ctypes.c_int() result = self.__api.getSolutionOutlet(self.__driver, unit, ctypes.byref(time_ptr), ctypes.byref(data_ptr), ctypes.byref(n_time), ctypes.byref(n_ports), ctypes.byref(n_comp)) n_time = n_time.value n_ports = n_ports.value n_comp = n_comp.value data = numpy.ctypeslib.as_array(data_ptr, shape=(n_time, n_ports, n_comp)) time = numpy.ctypeslib.as_array(time_ptr, shape=(n_time, )) if own_data: return (time.copy(), data.copy()) else: return (time, data)
def check_day_conflict(time: list, start: int, end: int) -> bool: if end < start: return False if len(time) == 0: return True time = time.copy() time.append((start, 0)) time.append((end, 1)) time.sort(key=lambda t: t[1], reverse=True) time.sort(key=lambda t: t[0]) cur = 0 for time, op in time: if op == 0: # start cur += 1 else: #op == 1 end cur -= 1 if not (cur == 0 or cur == 1): return False return cur == 0
def __init__(self, time, flux, fmax=40, fmin=0.000001, model='sin'): models = ['sin', 'pda', 'sin_analytic'] if model not in models: sys.exit( f'{model} not an available option for model. Try one in {models}' ) self.time = time.copy() self.flux = flux.copy() self.lc = lk.LightCurve(self.time, self.flux) self.resid = flux.copy() self.resid_lc = lk.LightCurve(self.time, self.resid) self.iterations = [] self.iters = 0 self.fmax = fmax self.fmin = np.min([fmin, 0.00001]) self.result = [] self.nofp = 1 self.var = np.var(flux) pdg = lk.LightCurve(time, flux).to_periodogram(maximum_frequency=fmax, minimum_frequency=self.fmin) pdg_func = interp.interp1d(pdg.frequency, pdg.power, fill_value='extrapolate') self.power_val = integ.quad(pdg_func, self.fmin, self.fmax, limit=5000, epsabs=1.49e-05, epsrel=1.49e-03)[0] self.n = len(time) self.aic_val = self.n * np.log( np.sum(self.flux**2) / self.n) + self.n + 2 * self.nofp self.bic_val = self.n * np.log( np.sum(self.flux**2) / self.n) + self.nofp * np.log(self.n) self.stop = 0 self.model = model if self.model == "pda": self.have_primary = False self.have_secondary = True
p_end = nframe / 2 for res_ind, vel_res in enumerate(vel): for loop_ind in range(p_start, p_end): vc[res_ind][frame_ind - 1 - loop_ind].append( np.mean( np.sum(vel[res_ind] * vel_ref[loop_ind][res_ind], axis=1))) base[res_ind][frame_ind - 1 - loop_ind].append( np.mean(np.sum(vel_ref[loop_ind][res_ind]**2, axis=1))) if sub_ind % 10 == 9: print 'Reading chunk', chunk_index + 1, 'and frame', chunk_index * chunk_size + sub_ind + 1 # if chunk_index == 0: # break time = np.arange(nframe - nframe / 2 + 1) * dt data = time.copy() data_raw = time.copy() pt_start = len(time) / 2 nvcf = [] vcf = [] print 'frames read:', chunk_index * chunk_size + sub_ind + 1 fig = plt.figure() for i, item in enumerate(vc): nvcf.append([]) vcf.append([]) for j in range(len(item)): nvcf[-1].append(np.mean(item[j]) / np.mean(base[i][j])) vcf[-1].append(np.mean(item[j])) nvcf[i] = np.array(nvcf[i]) vcf[i] = np.array(vcf[i]) * 1e6 / dt**2 ### units are m^2/s^2
def __init__(self, struct, pid, tflux, cflux, ratio, time, phottype, sleep, tx, ty, cx, cy, r, br1, br2, naxis1, naxis2, sigdet, contpix, driftlimit): """Default constructor.""" maxcolumn = 7 self.struct = struct self.infile = struct._HDUList__file.name self.name = self.struct[0].header['OBJECT'] self.pid = pid self.dtime = time.copy() self.tflux = tflux self.cflux = cflux self.ratio = ratio self.min_xlim = 10 self.radius = r['comparison'] self.r = r self.br1 = br1 self.br2 = br2 self.tx = tx self.ty = ty self.cx = cx self.cy = cy self.phottype = phottype self.naxis1 = naxis1 self.naxis2 = naxis2 self.sigdet = sigdet self.contpix = contpix self.driftlimit = driftlimit self.niter = 5 self.sigback = 5 self.fft = False self.stopplay = False self.sleep = sleep self.zbox = [] self.npoint = 4 self.id = 0 self.nframes = len(self.struct) self.header = self.struct[int(self.pid[self.id])].header self.goodframes = self.dtime * 0 + 1 if self.phottype == 'circular': self.npoint = 24 # Setup widget QtGui.QMainWindow.__init__(self) # Set main widget self.main = QtGui.QWidget(self) # Set window title self.setWindowTitle("SlotView %s" % self.infile) #set up the different pages self.slotPage = QtGui.QWidget() #set up the differen panels self.set_optionpanel() self.set_imagepanel() self.set_controlpanel() self.set_plotpanel() self.set_infopanel() # Set up the layout slotLayout = QtGui.QVBoxLayout(self.slotPage) slotLayout.addWidget(self.plotpanel) slotLayout.addWidget(self.optipanel) slotLayout.addWidget(self.imdisplay) slotLayout.addWidget(self.contpanel) slotLayout.addWidget(self.infopanel) #create the tabs #self.tabWidget=QtGui.QTabWidget() #self.tabWidget.addTab(self.slotPage, 'Slot') #layout the widgets mainLayout = QtGui.QVBoxLayout(self.main) mainLayout.addWidget(self.slotPage) #mainLayout.addWidget(self.tabWidget) #self.setLayout(mainLayout) # Set focus to main widget self.main.setFocus() # Set the main widget as the central widget self.setCentralWidget(self.main) # Destroy widget on close self.setAttribute(QtCore.Qt.WA_DeleteOnClose) # Close when config dialog is closed self.connect(self.main, QtCore.SIGNAL('keyPressEvent'), self.keyPressEvent)
for (x, y, w, h) in f: cv2.rectangle(i, (x, y), (x + w, y + h), (0, 0, 255), 3) X.append(x) Y.append(y) W.append(w) H.append(h) if (len(X) == 2): t = i[Y[0]:Y[0] + min(H), X[0]:X[0] + min(W), :].copy() i[Y[0]:Y[0] + min(H), X[0]:X[0] + min(W), :] = i[Y[1]:Y[1] + min(H), X[1]:X[1] + min(W), :].copy() i[Y[1]:Y[1] + min(H), X[1]:X[1] + min(W), :] = t.copy() print(r) cv2.imshow('img', i) k = cv2.waitKey(1) if (k == ord('q')): cv2.destroyAllWindows() v.release() break ## l=cv2.add(i,b) ## j=cv2.cvtColor(i,cv2.COLOR_BGR2GRAY) ## r,g=cv2.threshold(j,127,255,0) ## cv2.imshow('black',d) ## cv2.imshow('digital',g)
def __init__(self, time, flux, mode): self.time = time.copy() self.flux = flux.copy() self.lc = lk.LightCurve(self.time, self.flux) self.mode = mode
def __init__(self, struct, pid, tflux, cflux, ratio, time, phottype, sleep, tx, ty, cx, cy, r, br1, br2, naxis1, naxis2, sigdet, contpix, driftlimit): """Default constructor.""" maxcolumn=7 self.struct = struct self.infile=struct._HDUList__file.name self.name=self.struct[0].header['OBJECT'] self.pid=pid self.dtime=time.copy() self.tflux=tflux self.cflux=cflux self.ratio=ratio self.min_xlim=10 self.radius=r['comparison'] self.r=r self.br1=br1 self.br2=br2 self.tx=tx self.ty=ty self.cx=cx self.cy=cy self.phottype=phottype self.naxis1=naxis1 self.naxis2=naxis2 self.sigdet=sigdet self.contpix=contpix self.driftlimit=driftlimit self.niter=5 self.sigback=5 self.fft=False self.stopplay=False self.sleep=sleep self.zbox=[] self.npoint=4 self.id=0 self.nframes=len(self.struct) self.header=self.struct[int(self.pid[self.id])].header self.goodframes=self.dtime*0+1 if self.phottype=='circular': self.npoint=24 # Setup widget QtGui.QMainWindow.__init__(self) # Set main widget self.main = QtGui.QWidget(self) # Set window title self.setWindowTitle("SlotView %s" % self.infile) #set up the different pages self.slotPage=QtGui.QWidget() #set up the differen panels self.set_optionpanel() self.set_imagepanel() self.set_controlpanel() self.set_plotpanel() self.set_infopanel() # Set up the layout slotLayout = QtGui.QVBoxLayout(self.slotPage) slotLayout.addWidget(self.plotpanel) slotLayout.addWidget(self.optipanel) slotLayout.addWidget(self.imdisplay) slotLayout.addWidget(self.contpanel) slotLayout.addWidget(self.infopanel) #create the tabs #self.tabWidget=QtGui.QTabWidget() #self.tabWidget.addTab(self.slotPage, 'Slot') #layout the widgets mainLayout = QtGui.QVBoxLayout(self.main) mainLayout.addWidget(self.slotPage) #mainLayout.addWidget(self.tabWidget) #self.setLayout(mainLayout) # Set focus to main widget self.main.setFocus() # Set the main widget as the central widget self.setCentralWidget(self.main) # Destroy widget on close self.setAttribute(QtCore.Qt.WA_DeleteOnClose) # Close when config dialog is closed self.connect(self.main, QtCore.SIGNAL('keyPressEvent'), self.keyPressEvent)
coverage = np.ma.getdata(tas[0:12, :, :]) * 0 ref_period = np.where((time > 19860000) & (time < 20160000))[0] time_in_year = [t - int(t / 10000.) * 10000 for t in time[ref_period]] month = [int(t / 100.) - 1 for t in time_in_year] for i, t in zip(range(len(ref_period)), ref_period): coverage[month[i], :, :] += np.ma.getmask(tas[t, :, :]) coverage[coverage > 10] = np.nan coverage = np.ma.masked_invalid(coverage) coverage_ext = tas[0:1008, :, :].copy() for i, m in zip(range(1008), range(12) * 84): coverage_ext[i, :, :] = coverage[m, :, :] tas_ext = np.concatenate((tas, coverage_ext), axis=0) time_ext = time.copy() for year in range(2017, 2101): extension = time[0:12] - 18500000 + year * 10000 time_ext = np.concatenate((time_ext, extension)) nc_in = Dataset('CRU.nc', "r") # copy netcdf and write zoomed file out_file = 'CRU_extended.nc' os.system("rm " + out_file) nc_out = Dataset(out_file, "w") for dname, the_dim in nc_in.dimensions.iteritems(): nc_out.createDimension(dname, len(the_dim) if not the_dim.isunlimited() else None) # Copy variables
def __init__(self, struct, pid, tflux, cflux, ratio, time, phottype, sleep, vig_lo, vig_hi, \ tx, ty, cx, cy, r, br1, br2, naxis1, naxis2, clobber, logfile, verbose): """As the data is measured, plots the target and companion, the drift, both light curves and the ratio returns status """ #set up the variables status=0 maxcolumn=7 self.struct = struct self.infile=struct._HDUList__file.name self.pid=pid self.dtime=time.copy() self.tflux=tflux self.cflux=cflux self.ratio=ratio self.min_xlim=10 self.radius=r['comparison'] self.r=r self.br1=br1 self.br2=br2 self.tx=tx self.ty=ty self.cx=cx self.cy=cy self.phottype=phottype self.naxis1=naxis1 self.naxis2=naxis2 self.logfile=logfile self.clobber=clobber self.verbose=verbose self.fft=False self.stopplay=False self.sleep=sleep self.zbox=[] self.newphot=0 self.npoint=4 if self.phottype=='circular': self.npoint=24 if status==0: self.id=0 self.nframes=len(self.struct) self.header=self.struct[int(self.pid[self.id])].header self.goodframes=self.dtime*0+1 # Setup widget QtGui.QMainWindow.__init__(self) # Set main widget self.main = QtGui.QWidget(self) # Set window title self.setWindowTitle("Slotview: "+self.infile) #self.root.bind("<Destroy>", self.destroy) #self.root.bind("D", self.deleteframe) #self.root.bind("u", self.undeleteframe) #self.root.bind("n", self.call_playone) #self.root.bind("b", self.call_revone) #self.root.bind("?", self.help) #self.root.bind("q", self.destroy) #self.root.bind("<Button-1>", self.callback) #set up the variables for which graphs to plot #self.ratiovar=Tk.IntVar(master=self.root, value=1) #self.star1var=Tk.IntVar(master=self.root, value=0) #self.star2var=Tk.IntVar(master=self.root, value=0) #self.slotfig=plt.figure(figsize=(8,1.5),dpi=72) #plot the data #self.plotdataarray() #self.lcfig=plt.figure(figsize=(8,5),dpi=72) #plot the light curve #self.lcx1=self.dtime.min() #self.lcx2=self.dtime.max() #self.plotlightcurve() inrow=4 lcrow=0 pcrow=1 darow=2 cprow=3 qurow=5 #add light curve plot #self.lccanvas = FigureCanvasTkAgg(self.lcfig, master=self.root) #self.lccanvas.show() #self.lccanvas.get_tk_widget().grid(row = lcrow, column = 0, columnspan = maxcolumn, sticky = 'news') #self.lccanvas.mpl_connect('button_press_event',self.lcpickstar) #self.lccanvas.mpl_connect('motion_notify_event',self.lcdrawbox) #self.lccanvas.mpl_connect('button_release_event',self.lczoom) #add data array plot #self.canvas = FigureCanvasTkAgg(self.slotfig, master=self.root) #self.canvas.show() #self.canvas.blit() #self.canvas.get_tk_widget().grid(row = darow, column = 0, columnspan = maxcolumn, sticky = 'news') #self.canvas.mpl_connect('key_press_event',self.newphoto) #add the control widget #self.cpFrame = Tk.Frame(master=self.root) #self.cpFrame.grid(row=cprow, column=0, columnspan=maxcolumn, sticky='ew') #self.frevbutton = Tk.Button(master=self.cpFrame, text='< <', width=5, command=self.freverse) #self.frevbutton.grid(row=0, column=0, sticky='ew') #self.revbutton = Tk.Button(master=self.cpFrame, text='<',width=5, command=self.reverse) #self.revbutton.grid(row=0, column=1, sticky='ew') #self.rev1button = Tk.Button(master=self.cpFrame, text='-',width=5, command=self.revone) #self.rev1button.grid(row=0, column=2, sticky='ew') #self.play1button = Tk.Button(master=self.cpFrame, text='+',width=5, command=self.playone) #self.play1button.grid(row=0, column=4, sticky='ew') #self.playbutton = Tk.Button(master=self.cpFrame, text='>',width=5, command=self.play) #self.playbutton.grid(row=0, column=5, sticky='ew') #self.fplaybutton = Tk.Button(master=self.cpFrame, text='> >',width=5, command=self.fplay) #self.fplaybutton.grid(row=0, column=6, sticky='ew') #self.stopbutton = Tk.Button(master=self.cpFrame, text='Stop',width=5, command=self.stop) #self.stopbutton.grid(row=0, column=3, sticky='ew') #add the information panel #self.idtext= Tk.StringVar(master=self.root ) #self.imgtext= Tk.StringVar(master=self.root ) #self.timetext= Tk.StringVar(master=self.root ) #self.idLabel = Tk.Label(master=self.root, fg='#000000',textvariable=self.idtext, relief='solid') #self.idLabel.grid(row=inrow, column=0, sticky='ew') #self.imgLabel = Tk.Label(master=self.root, textvariable=self.imgtext, relief='solid') #self.imgLabel.grid(row=inrow, column=1, columnspan=3, sticky='ew') #self.timeLabel = Tk.Label(master=self.root, textvariable=self.timetext, relief='solid') #self.timeLabel.grid(row=inrow, column=4, columnspan=3, sticky='ew') #self.setinfolabels() #add the plot control panel #self.ratiobutton=Tk.Checkbutton(master=self.root, text='Flux Ratio', variable=self.ratiovar, \ # command=self.calllccheck) #self.ratiobutton.grid(row=pcrow, column=0, sticky='ew') #self.star1button=Tk.Checkbutton(master=self.root, text='Star1 Flux', variable=self.star1var, \ # command=self.calllccheck) #self.star1button.grid(row=pcrow, column=1, sticky='ew') #self.star2button=Tk.Checkbutton(master=self.root, text='Star2 Flux', variable=self.star2var, \ # command=self.calllccheck) #self.star2button.grid(row=pcrow, column=2, sticky='ew') #self.resetbutton = Tk.Button(master=self.root, text='Reset', command=self.callreset) #self.resetbutton.grid(row=pcrow, column=6, sticky='ew') #self.savebutton = Tk.Button(master=self.root, text='save', command=self.callsave) #self.savebutton.grid(row=pcrow, column=5, sticky='ew') #add the quit button #self.quFrame = Tk.Frame(master=self.root) #self.quFrame.grid(row=qurow, column=0, columnspan=maxcolumn, sticky='ew') #self.exitbutton = Tk.Button(master=self.quFrame, text='Quit', command=self.exit) #self.exitbutton.grid(row=0, column=3, sticky='ew') #create the tabs self.tabWidget=QtGui.QTabWidget() #layout the widgets mainLayout = QtGui.QVBoxLayout(self.main) mainLayout.addWidget(self.tabWidget) # Set the main widget as the central widget self.setCentralWidget(self.main) # Destroy widget on close self.setAttribute(QtCore.Qt.WA_DeleteOnClose) return
def main(): st.sidebar.header("Explorador de ativos") n_sprites = st.sidebar.radio("Escolha uma opção", options=[ "Análise técnica e fundamentalista", "Comparação de ativos", "Descobrir novos ativos" ], index=0) st.sidebar.markdown( 'É preciso ter paciência e disciplina para se manter firme em suas convicções quando o mercado insiste que você está errado.!' ) st.sidebar.markdown('Benjamin Graham') st.sidebar.markdown('Email para contato: [email protected]') st.sidebar.markdown('Portfólio: https://github.com/lucasvascrocha') # ------------------------------ INÍCIO ANÁLISE TÉCNICA E FUNDAMENTALISTA ---------------------------- if n_sprites == "Análise técnica e fundamentalista": st.image('https://media.giphy.com/media/rM0wxzvwsv5g4/giphy.gif', width=400) #image = Image.open('imagens/logo.jpg') #st.image(image, use_column_width=True) st.title('Análise Técnica e fundamentalista') st.subheader('Escolha o ativo que deseja analisar e pressione enter') nome_do_ativo = st.text_input('Nome do ativo') st.write( 'Este explorador funciona melhor para ações, porém também suporta alguns fundos imobiliários' ) st.write( 'Os parâmetros utilizados em grande maioria foram seguindo as teorias de Benjamin Graham' ) if nome_do_ativo != "": nome_do_ativo = str(nome_do_ativo + '.SA') st.subheader('Analisando os dados') df = Ticker(nome_do_ativo, country='Brazil') time = df.history(period='max') st.dataframe(time.tail()) # ------------------------------ RESUMO ---------------------------- resumo = pd.DataFrame(df.summary_detail) resumo = resumo.transpose() if len(nome_do_ativo) == 8: fundamentus = get_specific_data(nome_do_ativo[:5]) fundamentus = pd.DataFrame([fundamentus]) pfizer = yf.Ticker(nome_do_ativo) info = pfizer.info st.title('PERFIL DA EMPRESA') st.subheader(info['longName']) st.markdown('** Setor **: ' + info['sector']) st.markdown('** Atividade **: ' + info['industry']) st.markdown('** Website **: ' + info['website']) try: fundInfo = { 'Dividend Yield (%) -12 meses': round(info['dividendYield'] * 100, 2), 'P/L': fundamentus['P/L'][0], 'P/VP': fundamentus['P/VP'][0], 'Próximo pagamento de dividendo:': (pfizer.calendar.transpose() ['Earnings Date'].dt.strftime('%d/%m/%Y')[0]) } fundDF = pd.DataFrame.from_dict(fundInfo, orient='index') fundDF = fundDF.rename(columns={0: 'Valores'}) st.subheader('Informações fundamentalistas') st.table(fundDF) except: exit else: st.write( '---------------------------------------------------------------------' ) st.dataframe(resumo) pfizer = yf.Ticker(nome_do_ativo) info = pfizer.info st.title('Company Profile') st.subheader(info['longName']) try: st.markdown('** Sector **: ' + info['sector']) st.markdown('** Industry **: ' + info['industry']) st.markdown('** Website **: ' + info['website']) except: exit # ------------------------------ GRÁFICOS DE RENDIMENTO ---------------------------- if len(nome_do_ativo) == 8: import datetime fundamentalist = df.income_statement() fundamentalist['data'] = fundamentalist[ 'asOfDate'].dt.strftime('%d/%m/%Y') fundamentalist = fundamentalist.drop_duplicates('asOfDate') fundamentalist = fundamentalist.loc[ fundamentalist['periodType'] == '12M'] #volatilidade TRADING_DAYS = 360 returns = np.log(time['close'] / time['close'].shift(1)) returns.fillna(0, inplace=True) volatility = returns.rolling( window=TRADING_DAYS).std() * np.sqrt(TRADING_DAYS) vol = pd.DataFrame(volatility.iloc[-360:]).reset_index() #sharpe ratio sharpe_ratio = returns.mean() / volatility sharpe = pd.DataFrame(sharpe_ratio.iloc[-360:]).reset_index() div = time.reset_index() div['year'] = pd.to_datetime(div['date']).dt.strftime('%Y') div_group = div.groupby('year').agg({ 'close': 'mean', 'dividends': 'sum' }) div_group['dividendo(%)'] = round( (div_group['dividends'] * 100) / div_group['close'], 4) from plotly.subplots import make_subplots fig = make_subplots( rows=3, cols=2, specs=[[{ "type": "bar" }, { "type": "bar" }], [{ "type": "bar" }, { "type": "bar" }], [{ "type": "scatter" }, { "type": "scatter" }]], subplot_titles=("Receita Total", "Lucro", 'Dividendos (%)', 'Dividendos unitário R$', 'Volatilidade', 'Sharpe ratio (Retorno/ Risco)')) fig.add_trace(go.Bar( x=pfizer.financials.transpose().index, y=pfizer.financials.transpose()['Total Revenue']), row=1, col=1) fig.add_trace(go.Bar(x=pfizer.financials.transpose().index, y=pfizer.financials.transpose() ['Net Income From Continuing Ops']), row=1, col=2) fig.add_trace(go.Bar( x=div_group.reset_index().tail(5)['year'], y=div_group.reset_index().tail(5)['dividendo(%)']), row=2, col=1) fig.add_trace(go.Bar( x=div_group.reset_index().tail(5)['year'], y=div_group.reset_index().tail(5)['dividends']), row=2, col=2) fig.add_trace(go.Scatter(x=vol['date'], y=vol['close']), row=3, col=1) fig.add_trace(go.Scatter(x=sharpe['date'], y=sharpe['close']), row=3, col=2) fig.update_layout(height=800, showlegend=False) st.plotly_chart(fig) else: #volatilidade TRADING_DAYS = 160 returns = np.log(time['close'] / time['close'].shift(1)) returns.fillna(0, inplace=True) volatility = returns.rolling( window=TRADING_DAYS).std() * np.sqrt(TRADING_DAYS) vol = pd.DataFrame(volatility.iloc[-160:]).reset_index() #sharpe ratio sharpe_ratio = returns.mean() / volatility sharpe = pd.DataFrame(sharpe_ratio.iloc[-160:]).reset_index() from plotly.subplots import make_subplots fig = make_subplots( rows=1, cols=2, specs=[[{ "type": "scatter" }, { "type": "scatter" }]], subplot_titles=('Volatilidade', 'Sharpe ratio (Retorno/ Risco)')) fig.add_trace(go.Scatter(x=vol['date'], y=vol['close']), row=1, col=1) fig.add_trace(go.Scatter(x=sharpe['date'], y=sharpe['close']), row=1, col=2) fig.update_layout(height=800, showlegend=False) st.plotly_chart(fig) # ------------------------------ GRÁFICOS DE Candlestick---------------------------- fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.03, subplot_titles=('OHLC', 'Volume'), row_width=[0.2, 0.7]) # Plot OHLC on 1st row fig.add_trace(go.Candlestick(x=time.reset_index()['date'][-90:], open=time['open'][-90:], high=time['high'][-90:], low=time['low'][-90:], close=time['close'][-90:], name="OHLC"), row=1, col=1) # Bar trace for volumes on 2nd row without legend fig.add_trace(go.Bar(x=time.reset_index()['date'][-90:], y=time['volume'][-90:], showlegend=False), row=2, col=1) # Do not show OHLC's rangeslider plot fig.update(layout_xaxis_rangeslider_visible=False) fig.update_layout( autosize=False, width=800, height=800, ) st.plotly_chart(fig) # ------------------------------ GRÁFICOS DE Retorno acumulado---------------------------- layout = go.Layout(title="Retorno acumulado", xaxis=dict(title="Data"), yaxis=dict(title="Retorno")) fig = go.Figure(layout=layout) fig.add_trace( go.Scatter( x=time.reset_index()['date'][-365:], y=time.reset_index()['close'][-365:].pct_change().cumsum(), mode='lines', line_width=3, line_color='rgb(0,0,0)')) fig.update_layout( autosize=False, width=800, height=800, ) st.plotly_chart(fig) # ------------------------------ GRÁFICOS DE Médias móveis---------------------------- rolling_50 = time['close'].rolling(window=50) rolling_mean_50 = rolling_50.mean() rolling_20 = time['close'].rolling(window=20) rolling_mean_20 = rolling_20.mean() rolling_10 = time['close'].rolling(window=10) rolling_mean_10 = rolling_10.mean() layout = go.Layout(title="Médias móveis", xaxis=dict(title="Data"), yaxis=dict(title="Preço R$")) fig = go.Figure(layout=layout) fig.add_trace( go.Scatter(x=time.reset_index()['date'][-120:], y=time["close"][-120:], mode='lines', line_width=3, name='Real', line_color='rgb(0,0,0)')) fig.add_trace( go.Scatter(x=time.reset_index()['date'][-120:], y=rolling_mean_50[-120:], mode='lines', name='MM(50)', opacity=0.6)) fig.add_trace( go.Scatter(x=time.reset_index()['date'][-120:], y=rolling_mean_20[-120:], mode='lines', name='MM(20)', opacity=0.6)) fig.add_trace( go.Scatter(x=time.reset_index()['date'][-120:], y=rolling_mean_10[-120:], mode='lines', name='MM(10)', opacity=0.6, line_color='rgb(100,149,237)')) # fig.add_trace(go.Candlestick(x=time.reset_index()['date'][-120:], open=time['open'][-120:],high=time['high'][-120:],low=time['low'][-120:],close=time['close'][-120:])) fig.update_layout( autosize=False, width=800, height=800, ) st.plotly_chart(fig) # ------------------------------ GRÁFICOS DE Retração de Fibonacci---------------------------- time_fibo = time.copy() periodo_fibonacci = int( st.number_input(label='periodo fibonacci', value=90)) Price_Min = time_fibo[-periodo_fibonacci:]['low'].min() Price_Max = time_fibo[-periodo_fibonacci:]['high'].max() Diff = Price_Max - Price_Min level1 = Price_Max - 0.236 * Diff level2 = Price_Max - 0.382 * Diff level3 = Price_Max - 0.618 * Diff st.write('0% >>' f'{round(Price_Max,2)}') st.write('23,6% >>' f'{round(level1,2)}') st.write('38,2% >>' f'{round(level2,2)}') st.write('61,8% >>' f'{round(level3,2)}') st.write('100% >>' f'{round(Price_Min,2)}') time_fibo['Price_Min'] = Price_Min time_fibo['level1'] = level1 time_fibo['level2'] = level2 time_fibo['level3'] = level3 time_fibo['Price_Max'] = Price_Max layout = go.Layout(title=f'Retração de Fibonacci', xaxis=dict(title="Data"), yaxis=dict(title="Preço")) fig = go.Figure(layout=layout) fig.add_trace( go.Scatter( x=time_fibo[-periodo_fibonacci:].reset_index()['date'], y=time_fibo[-periodo_fibonacci:].close, mode='lines', line_width=3, name='Preço real', line_color='rgb(0,0,0)')) fig.add_trace( go.Scatter( x=time_fibo[-periodo_fibonacci:].reset_index()['date'], y=time_fibo[-periodo_fibonacci:].Price_Min, mode='lines', line_width=0.5, name='100%', line_color='rgb(255,0,0)', )) fig.add_trace( go.Scatter( x=time_fibo[-periodo_fibonacci:].reset_index()['date'], y=time_fibo[-periodo_fibonacci:].level3, mode='lines', line_width=0.5, name='61,8%', line_color='rgb(255,255,0)', fill='tonexty', fillcolor="rgba(255, 0, 0, 0.2)")) fig.add_trace( go.Scatter( x=time_fibo[-periodo_fibonacci:].reset_index()['date'], y=time_fibo[-periodo_fibonacci:].level2, mode='lines', line_width=0.5, name='38,2%', line_color='rgb(0,128,0)', fill='tonexty', fillcolor="rgba(255, 255, 0, 0.2)")) fig.add_trace( go.Scatter( x=time_fibo[-periodo_fibonacci:].reset_index()['date'], y=time_fibo[-periodo_fibonacci:].level1, mode='lines', line_width=0.5, name='23,6%', line_color='rgb(128,128,128)', fill='tonexty', fillcolor="rgba(0, 128, 0, 0.2)")) fig.add_trace( go.Scatter( x=time_fibo[-periodo_fibonacci:].reset_index()['date'], y=time_fibo[-periodo_fibonacci:].Price_Max, mode='lines', line_width=0.5, name='0%', line_color='rgb(0,0,255)', fill='tonexty', fillcolor="rgba(128, 128, 128, 0.2)")) fig.update_layout( autosize=False, width=800, height=800, ) st.plotly_chart(fig) # ------------------------------ GRÁFICOS DE RSI---------------------------- periodo_RSI = int(st.number_input(label='periodo RSI', value=90)) delta = time['close'][-periodo_RSI:].diff() up, down = delta.copy(), delta.copy() up[up < 0] = 0 down[down > 0] = 0 period = 14 rUp = up.ewm(com=period - 1, adjust=False).mean() rDown = down.ewm(com=period - 1, adjust=False).mean().abs() time['RSI_' + str(period)] = 100 - 100 / (1 + rUp / rDown) time['RSI_' + str(period)].fillna(0, inplace=True) layout = go.Layout(title=f'RSI {periodo_RSI}', xaxis=dict(title="Data"), yaxis=dict(title="%RSI")) fig = go.Figure(layout=layout) fig.add_trace( go.Scatter(x=time.reset_index()['date'][-periodo_RSI:], y=round(time['RSI_14'][-periodo_RSI:], 2), mode='lines', line_width=3, name=f'RSI {periodo_RSI}', line_color='rgb(0,0,0)')) fig.update_layout( autosize=False, width=800, height=800, ) st.plotly_chart(fig) # ------------------------------ GRÁFICOS DE pivôs---------------------------- periodo_pivo = int(st.number_input(label='periodo RSI', value=20)) time['PP'] = pd.Series( (time['high'] + time['low'] + time['close']) / 3) time['R1'] = pd.Series(2 * time['PP'] - time['low']) time['S1'] = pd.Series(2 * time['PP'] - time['high']) time['R2'] = pd.Series(time['PP'] + time['high'] - time['low']) time['S2'] = pd.Series(time['PP'] - time['high'] + time['low']) layout = go.Layout(title=f'Pivô', xaxis=dict(title="Data"), yaxis=dict(title="Preço")) fig = go.Figure(layout=layout) fig.add_trace( go.Scatter(x=time.reset_index()['date'][-periodo_pivo:], y=round(time['close'][-periodo_pivo:], 2), mode='lines', line_width=3, name=f'preço real', line_color='rgb(0,0,0)')) fig.add_trace( go.Scatter(x=time.reset_index()['date'][-periodo_pivo:], y=round(time['PP'][-periodo_pivo:], 2), mode='lines', line_width=1, name=f'Ponto do pivô', line_color='rgb(0,128,0)')) fig.add_trace( go.Scatter(x=time.reset_index()['date'][-periodo_pivo:], y=round(time['R1'][-periodo_pivo:], 2), mode='lines', line_width=1, name=f'Resistência 1', line_color='rgb(100,149,237)')) fig.add_trace( go.Scatter(x=time.reset_index()['date'][-periodo_pivo:], y=round(time['S1'][-periodo_pivo:], 2), mode='lines', line_width=1, name=f'Suporte 1', line_color='rgb(100,149,237)')) fig.add_trace( go.Scatter(x=time.reset_index()['date'][-periodo_pivo:], y=round(time['R2'][-periodo_pivo:], 2), mode='lines', line_width=1, name=f'Resistência 2', line_color='rgb(255,0,0)')) fig.add_trace( go.Scatter(x=time.reset_index()['date'][-periodo_pivo:], y=round(time['S2'][-periodo_pivo:], 2), mode='lines', line_width=1, name=f'Suporte 2', line_color='rgb(255,0,0)')) fig.update_layout( autosize=False, width=800, height=800, ) st.plotly_chart(fig) # ------------------------------ GRÁFICOS DE Bolinger---------------------------- periodo_bolinger = int( st.number_input(label='periodo Bolinger', value=180)) time['MA20'] = time['close'].rolling(20).mean() time['20 Day STD'] = time['close'].rolling(window=20).std() time['Upper Band'] = time['MA20'] + (time['20 Day STD'] * 2) time['Lower Band'] = time['MA20'] - (time['20 Day STD'] * 2) layout = go.Layout(title=f'Banda de Bolinger', xaxis=dict(title="Data"), yaxis=dict(title="Preço")) fig = go.Figure(layout=layout) fig.add_trace( go.Scatter(x=time.reset_index()['date'][-periodo_bolinger:], y=round(time['Upper Band'][-periodo_bolinger:], 2), mode='lines', line_width=1, name=f'Banda superior', line_color='rgb(255,0,0)')) fig.add_trace( go.Scatter(x=time.reset_index()['date'][-periodo_bolinger:], y=round(time['Lower Band'][-periodo_bolinger:], 2), mode='lines', line_width=1, name=f'Banda inferior', line_color='rgb(255,0,0)', fill='tonexty', fillcolor="rgba(255, 0, 0, 0.1)", opacity=0.2)) fig.add_trace( go.Scatter(x=time.reset_index()['date'][-periodo_bolinger:], y=round(time['close'][-periodo_bolinger:], 2), mode='lines', line_width=3, name=f'preço real', line_color='rgb(0,0,0)')) fig.add_trace( go.Scatter(x=time.reset_index()['date'][-periodo_bolinger:], y=round(time['MA20'][-periodo_bolinger:], 2), mode='lines', line_width=2, name=f'MM 20', line_color='rgb(0,128,0)')) fig.update_layout( autosize=False, width=800, height=800, ) st.plotly_chart(fig) # ------------------------------ Previsões---------------------------- st.subheader('Previsões') st.write( 'As previsões são feitas levando em conta apenas o movimento gráfico, porém o movimento do preço de um ativo é influenciado por diversos outros fatores, com isso, deve se considerar as previsões como uma hipótese de o preço do ativo variar somente pela sua variação gráfica' ) st.write( 'Previsão considerando os últimos 365 dias, pode ser entendida como uma tendência dos dados segundo o último ano' ) time = time.reset_index() time = time[['date', 'close']] time.columns = ['ds', 'y'] #Modelling m = Prophet() m.fit(time[-360:]) future = m.make_future_dataframe(periods=30) forecast = m.predict(future[-30:]) from fbprophet.plot import plot_plotly, plot_components_plotly fig1 = plot_plotly(m, forecast) st.plotly_chart(fig1) #st.plotly_chart(m, forecast) fig2 = m.plot_components(forecast) st.plotly_chart(fig2) #st.write('Previsão considerando as últimas semanas, pode ser entendida como uma tendência dos dados segundo os últimos dias. Leva em consideração diversos fatores como: Índice de força relativa RSI, oscilador estocástico %K, Indicador Willian %R além do movimento gráfico dos últimos dias') #predict = stocker.predict.tomorrow(nome_do_ativo) #st.write('Previsão para o dia:',f'{predict[2]}','é que a ação feche no valor de: R$',f'{predict[0]}') #preço_ontem= round(time['y'][-1:].values[0],2) #if predict[0] < preço_ontem: #st.write('Previsão para o dia:',f'{predict[2]}','é que a ação caia de ',f'{preço_ontem}', 'para valor de: R$ ',f'{predict[0]}') #else: #st.write('Previsão para o dia:',f'{predict[2]}','é que a ação suba de ',f'{preço_ontem}', 'para valor de: R$ ',f'{predict[0]}') # ------------------------------ INÍCIO Comparação de ativos ------------------------------------------------------------------------------------ if n_sprites == "Comparação de ativos": st.image('https://media.giphy.com/media/JtBZm3Getg3dqxK0zP/giphy.gif', width=300) #image = Image.open('imagens/logo.jpg') #st.image(image, use_column_width=True) st.title('Comparação de ativos') st.subheader('Escolha até 4 ativos para comparar') nome_do_ativo1 = st.text_input('Nome do 1º ativo') nome_do_ativo2 = st.text_input('Nome do 2º ativo') nome_do_ativo3 = st.text_input('Nome do 3º ativo') nome_do_ativo4 = st.text_input('Nome do 4º ativo') if nome_do_ativo4 != "": st.subheader('Analisando os dados') nome_do_ativo1 = str(nome_do_ativo1 + '.SA') nome_do_ativo2 = str(nome_do_ativo2 + '.SA') nome_do_ativo3 = str(nome_do_ativo3 + '.SA') nome_do_ativo4 = str(nome_do_ativo4 + '.SA') df = Ticker([ nome_do_ativo1, nome_do_ativo2, nome_do_ativo3, nome_do_ativo4 ], country='Brazil') time = df.history( start='2018-01-01', end=(dt.datetime.today() + dt.timedelta(days=1)).strftime(format='20%y-%m-%d')) lista = get_data() todos = pd.DataFrame(flatten(lista).keys()).transpose() todos.columns = todos.iloc[0] for i in range(len(lista)): todos = pd.concat([todos, pd.DataFrame(lista[i]).transpose()]) todos = todos.iloc[1:] todos['P/L'] = todos['P/L'].str.replace('.', '') todos['DY'] = todos['DY'].str.replace('%', '') todos['Liq.2m.'] = todos['Liq.2m.'].str.replace('.', '') todos['Pat.Liq'] = todos['Pat.Liq'].str.replace('.', '') todos = todos.replace(',', '.', regex=True) todos = todos.apply(pd.to_numeric, errors='ignore') comparar = todos.loc[todos.index.isin([ nome_do_ativo1[:5], nome_do_ativo2[:5], nome_do_ativo3[:5], nome_do_ativo4[:5] ])] st.dataframe(comparar) # ------------------------------ INÍCIO Comparação DY --------------- layout = go.Layout(title="DY", xaxis=dict(title="Ativo"), yaxis=dict(title="DY %")) fig = go.Figure(layout=layout) fig.add_trace( go.Bar(x=comparar.sort_values('DY', ascending=True).index, y=comparar.sort_values('DY', ascending=True)['DY'])) fig.update_layout( autosize=False, width=800, height=400, ) st.plotly_chart(fig) # ------------------------------ INÍCIO Comparação P/L --------------- layout = go.Layout(title="P/L", xaxis=dict(title="Ativo"), yaxis=dict(title="P/L")) fig = go.Figure(layout=layout) fig.add_trace( go.Bar(x=comparar.sort_values('P/L', ascending=True).index, y=comparar.sort_values('P/L', ascending=True)['P/L'])) fig.update_layout( autosize=False, width=800, height=400, ) st.plotly_chart(fig) # ------------------------------ INÍCIO Comparação P/V--------------- layout = go.Layout(title="P/VP", xaxis=dict(title="Ativo"), yaxis=dict(title="P/VP")) fig = go.Figure(layout=layout) fig.add_trace( go.Bar(x=comparar.sort_values('P/VP', ascending=True).index, y=comparar.sort_values('P/VP', ascending=True)['P/VP'])) fig.update_layout( autosize=False, width=800, height=400, ) st.plotly_chart(fig) # ------------------------------ INÍCIO Comparação P/L * P/VP--------------- layout = go.Layout(title="P/L X P/VP", xaxis=dict(title="Ativo"), yaxis=dict(title="P/L X P/VP")) fig = go.Figure(layout=layout) fig.add_trace( go.Bar(x=comparar.index, y=comparar['P/L'] * comparar['P/VP'])) fig.update_layout( autosize=False, width=800, height=400, ) st.plotly_chart(fig) # ------------------------------ GRÁFICOS DE retorno acumulado---------------------------- periodo_inicio = int( st.number_input(label='periodo retorno acumulado', value=360)) ret = time.reset_index() layout = go.Layout(title="Retorno acumulado", xaxis=dict(title="Data"), yaxis=dict(title="Retorno")) fig = go.Figure(layout=layout) for i in range(len(ret['symbol'].unique())): fig.add_trace( go.Scatter( x=ret.loc[ret['symbol'] == ret['symbol'].unique() [i]][-periodo_inicio:]['date'], y=ret.loc[ret['symbol'] == ret['symbol'].unique()[i]] [-periodo_inicio:]['close'].pct_change().cumsum(), mode='lines', name=ret.reset_index()['symbol'].unique()[i])) fig.update_layout( autosize=False, width=800, height=800, ) st.plotly_chart(fig) # ------------------------------ GRÁFICOS DE MÉDIAS MÓVEIS 50---------------------------- rolling_50 = time['close'].rolling(window=50) rolling_mean_50 = rolling_50.mean() rolling_mean_50 = pd.DataFrame(rolling_mean_50.reset_index()) # mm50 = time.reset_index() layout = go.Layout(title="MÉDIAS MÓVEIS 50", xaxis=dict(title="Data"), yaxis=dict(title="Preço R$")) fig = go.Figure(layout=layout) for i in range(len(rolling_mean_50['symbol'].unique())): fig.add_trace( go.Scatter( x=rolling_mean_50.loc[ rolling_mean_50['symbol'] == rolling_mean_50['symbol'].unique()[i]]['date'], y=rolling_mean_50.loc[ rolling_mean_50['symbol'] == rolling_mean_50['symbol'].unique()[i]]['close'], mode='lines', name=time.reset_index()['symbol'].unique()[i])) fig.update_layout( autosize=False, width=800, height=800, ) st.plotly_chart(fig) # ------------------------------ GRÁFICOS DE MÉDIAS MÓVEIS 20---------------------------- rolling_50 = time['close'].rolling(window=20) rolling_mean_50 = rolling_50.mean() rolling_mean_50 = pd.DataFrame(rolling_mean_50.reset_index()) # mm50 = time.reset_index() layout = go.Layout(title="MÉDIAS MÓVEIS 20", xaxis=dict(title="Data"), yaxis=dict(title="Preço R$")) fig = go.Figure(layout=layout) for i in range(len(rolling_mean_50['symbol'].unique())): fig.add_trace( go.Scatter( x=rolling_mean_50.loc[ rolling_mean_50['symbol'] == rolling_mean_50['symbol'].unique()[i]]['date'], y=rolling_mean_50.loc[ rolling_mean_50['symbol'] == rolling_mean_50['symbol'].unique()[i]]['close'], mode='lines', name=time.reset_index()['symbol'].unique()[i])) fig.update_layout( autosize=False, width=800, height=800, ) st.plotly_chart(fig) # ------------------------------ GRÁFICOS DE volatilidade--------------------------- TRADING_DAYS = 360 returns = np.log(time['close'] / time['close'].shift(1)) returns.fillna(0, inplace=True) volatility = returns.rolling( window=TRADING_DAYS).std() * np.sqrt(TRADING_DAYS) vol = pd.DataFrame(volatility).reset_index() vol = vol.dropna() layout = go.Layout(title=f"Volatilidade", xaxis=dict(title="Data"), yaxis=dict(title="Volatilidade")) fig = go.Figure(layout=layout) for i in range(len(vol['symbol'].unique())): fig.add_trace( go.Scatter(x=vol.loc[vol['symbol'] == vol['symbol'].unique()[i]]['date'], y=vol.loc[vol['symbol'] == vol['symbol'].unique()[i]]['close'], name=vol['symbol'].unique()[i])) fig.update_layout( autosize=False, width=800, height=400, ) st.plotly_chart(fig) # ------------------------------ GRÁFICOS DE sharpe_ratio--------------------------- sharpe_ratio = returns.mean() / volatility sharpe = pd.DataFrame(sharpe_ratio).reset_index() sharpe = sharpe.dropna() layout = go.Layout(title=f"SHARP (Risco / Volatilidade)", xaxis=dict(title="Data"), yaxis=dict(title="Sharp")) fig = go.Figure(layout=layout) for i in range(len(sharpe['symbol'].unique())): fig.add_trace( go.Scatter( x=sharpe.loc[sharpe['symbol'] == sharpe['symbol'].unique()[i]]['date'], y=sharpe.loc[sharpe['symbol'] == sharpe['symbol'].unique()[i]]['close'], name=sharpe['symbol'].unique()[i])) fig.update_layout( autosize=False, width=800, height=400, ) st.plotly_chart(fig) # ------------------------------ GRÁFICOS DE correlação-------------------------- st.subheader('Correlação') time = time.reset_index() time = time[['symbol', 'date', 'close']] df_1 = time.loc[time['symbol'] == time['symbol'].unique()[0]] df_1 = df_1.set_index('date') df_1.columns = df_1.columns.values + '-' + df_1.symbol.unique() df_1.drop(df_1.columns[0], axis=1, inplace=True) df_2 = time.loc[time['symbol'] == time['symbol'].unique()[1]] df_2 = df_2.set_index('date') df_2.columns = df_2.columns.values + '-' + df_2.symbol.unique() df_2.drop(df_2.columns[0], axis=1, inplace=True) df_3 = time.loc[time['symbol'] == time['symbol'].unique()[2]] df_3 = df_3.set_index('date') df_3.columns = df_3.columns.values + '-' + df_3.symbol.unique() df_3.drop(df_3.columns[0], axis=1, inplace=True) df_4 = time.loc[time['symbol'] == time['symbol'].unique()[3]] df_4 = df_4.set_index('date') df_4.columns = df_4.columns.values + '-' + df_4.symbol.unique() df_4.drop(df_4.columns[0], axis=1, inplace=True) merged = pd.merge(pd.merge(pd.merge(df_1, df_2, left_on=df_1.index, right_on=df_2.index, how='left'), df_3, left_on='key_0', right_on=df_3.index, how='left'), df_4, left_on='key_0', right_on=df_4.index, how='left').rename({ 'key_0': 'date' }, axis=1).set_index('date') retscomp = merged.pct_change() plt.figure(figsize=(10, 8)) sns.heatmap(retscomp.corr(), annot=True) st.pyplot() # ------------------------------ GRÁFICOS DE mapa de risco-------------------------- map = returns.reset_index() layout = go.Layout(title=f"Mapa de Risco x Retorno", xaxis=dict(title="Retorno esperado"), yaxis=dict(title="Risco")) fig = go.Figure(layout=layout) for i in range(len(map['symbol'].unique())): fig.add_trace( go.Scatter( x=[ map.loc[map['symbol'] == map['symbol'].unique()[i]] ['close'].mean() * 100 ], y=[ map.loc[map['symbol'] == map['symbol'].unique()[i]] ['close'].std() * 100 ], name=map['symbol'].unique()[i], marker=dict(size=30))) #fig.add_trace(go.Scatter(x=[map['close'].mean()], y=[map['close'].std()],text=map['symbol'].unique())) fig.update_xaxes(zeroline=True, zerolinewidth=2, zerolinecolor='Red') #, range=[-0.005, 0.01]) fig.update_yaxes(zeroline=True, zerolinewidth=2, zerolinecolor='Red') #, range=[-0.01, 0.1]) fig.update_traces(textposition='top center') fig.update_layout( autosize=False, width=800, height=600, ) st.plotly_chart(fig) # ------------------------------ INÍCIO Comparação de ativos ------------------------------------------------------------------------------------ if n_sprites == "Descobrir novos ativos": st.image('https://media.giphy.com/media/3ohs4gux2zjc7f361O/giphy.gif', width=400) #image = Image.open('imagens/logo.jpg') #st.image(image, use_column_width=True) st.title('Descobrir novos ativos') PL_mínimo = int(st.number_input(label='PL_mínimo', value=10)) PL_máximo = int(st.number_input(label='PL_máximo', value=15)) PVP_mínimo = int(st.number_input(label='PVP_mínimo', value=0.7)) PVP_máximo = int(st.number_input(label='PVP_máximo', value=1.5)) DY_mínimo = int(st.number_input(label='DY_mínimo', value=4)) DY_máximo = int(st.number_input(label='DY_máximo', value=30)) lista = get_data() todos = pd.DataFrame(flatten(lista).keys()).transpose() todos.columns = todos.iloc[0] for i in range(len(lista)): todos = pd.concat([todos, pd.DataFrame(lista[i]).transpose()]) todos = todos.iloc[1:] todos['P/L'] = todos['P/L'].str.replace('.', '') todos['DY'] = todos['DY'].str.replace('%', '') todos['Liq.2m.'] = todos['Liq.2m.'].str.replace('.', '') todos['Pat.Liq'] = todos['Pat.Liq'].str.replace('.', '') todos = todos.replace(',', '.', regex=True) todos = todos.apply(pd.to_numeric, errors='ignore') if st.checkbox("Filtrar"): st.dataframe(todos.loc[(todos['P/L'] >= PL_mínimo) & (todos['P/L'] <= PL_máximo) & (todos['P/VP'] >= PVP_mínimo) & (todos['P/VP'] <= PVP_máximo) & (todos['DY'] >= DY_mínimo) & (todos['DY'] <= DY_máximo)])