Advertisement
Guest User

Untitled

a guest
Aug 17th, 2020
428
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.67 KB | None | 0 0
  1. #SEÇÃO 1 = CARREGAR A PORRA TODA
  2.  
  3. import datetime
  4. import pandas as pd
  5. import matplotlib.pyplot as plt
  6. from matplotlib import style
  7. #dados yahoo
  8. import pandas_datareader.data as web
  9. import seaborn as sns
  10. import random
  11. import numpy as np
  12.  
  13. #corrigir bug do yahoo finance
  14. !pip install yfinance --upgrade --no-cache-dir
  15. import yfinance as yf
  16. yf.pdr_override()
  17.  
  18. #SEÇÃO 2 = PEGAR OS DADOS DE COTAÇÕES E VOLUME DO YAHOO
  19.  
  20. start = "2000-01-01"
  21. end="2020-08-15"
  22.  
  23. # LISTA SÓ DE AÇÕES ON
  24. # ATENÇÃO: EXISTEM ERROS NO YAHOO FINANCE PARA BRAP3, ENGI3 E TIET3, FORAM REMOVIDAS MANUALMENTE NA LISTAGEM ABAIXO
  25. tickers_ibov = "ITUB3.SA ODER3.SA BAUH3.SA MAPT3.SA SPRI3.SA RANI3.SA TASA13.SA TASA3.SA LREN3.SA HETA3.SA EEEL3.SA BRSR3.SA PATI3.SA GOAU3.SA PNVL3.SA LUXM3.SA CGRA3.SA KEPL3.SA FNCN3.SA STTR3.SA RCSL3.SA UCAS3.SA SANB3.SA MNPR3.SA GRND3.SA KLBN3.SA LUPA3.SA SLCE3.SA RAPT3.SA PTNT3.SA POMO3.SA MNDL3.SA FRAS3.SA HBTS3.SA JOPA3.SA FRTA3.SA MTSA3.SA RSUL3.SA SHUL3.SA MWET3.SA DOHL3.SA TUPY3.SA WEGE3.SA CLSC3.SA PTBL3.SA TXRX3.SA EALT3.SA CTKA3.SA TEKA3.SA CASN3.SA POSI3.SA MTIG3.SA HGTX3.SA INEP3.SA OIBR3.SA SAPR3.SA CPLE3.SA CRFB3.SA CYRE3.SA TEND3.SA BEEF3.SA VIVR3.SA RDNI3.SA CAML3.SA PINE3.SA AHEB13.SA AHEB3.SA CGAS3.SA RADL3.SA REDE3.SA ITSA3.SA DASA3.SA BALM3.SA AZEV3.SA AMAR3.SA APTI3.SA MYPK3.SA ETER3.SA CAMB3.SA ESTR3.SA ALPA3.SA NAFG3.SA RSID3.SA MGEL3.SA IDVL3.SA CALI3.SA CESP3.SA USIM3.SA NORD3.SA BDLL3.SA FLRY3.SA BRIV3.SA BBDC3.SA MSPA3.SA NEMO3.SA JBDU3.SA JPSA3.SA SLED3.SA LEVE3.SA PMAM3.SA PPAR3.SA WHRL3.SA ODPV3.SA BMKS3.SA ROMI3.SA EUCA3.SA TOTS3.SA JSLG3.SA PLAS3.SA SMTO3.SA IGTA3.SA NUTR3.SA VULC3.SA CSAN3.SA BOBR3.SA LLIS3.SA HBOR3.SA MGLU3.SA PCAR3.SA BAHI3.SA PFRM3.SA CEAB3.SA SBSP3.SA EVEN3.SA IGBR3.SA AALR3.SA BTTL3.SA WIZS3.SA LOGN3.SA BRKM3.SA BRQB3.SA QUSW3.SA BRDT3.SA BMIN3.SA UNIP3.SA CEGR3.SA VIVA3.SA GGBR3.SA VALE3.SA TKNO3.SA RPMG3.SA SOND3.SA IRBR3.SA UGPA3.SA WLMM3.SA HOOT3.SA VLID3.SA TCNO3.SA MOAR3.SA CBEE3.SA CSNA3.SA VVAR3.SA MERC3.SA JFEN3.SA FCAP3.SA LAME3.SA PETR3.SA NTCO3.SA HAGA3.SA BPAC3.SA SULA3.SA NRTQ3.SA SCAR3.SA BEES3.SA MILS3.SA CTNM3.SA FHER3.SA MOVI3.SA CTSA3.SA OFSA3.SA GNDI3.SA CATA3.SA PARD3.SA PRNR3.SA RLOG3.SA BBSE3.SA MEAL3.SA CSMG3.SA CEDO3.SA BRGE3.SA BMEB3.SA CRIV3.SA RPAD3.SA MEND3.SA MMAQ3.SA CMIG3.SA RENT3.SA DIRR3.SA ARZZ3.SA SUZB3.SA BSEV3.SA CSAB3.SA FESA3.SA CEEB3.SA CRPG3.SA CORR3.SA SNSY3.SA ELEK3.SA BKBR3.SA CNTO3.SA BGIP3.SA MDNE3.SA QUAL3.SA APER3.SA ENAT3.SA BPHA3.SA FLEX3.SA CEPE3.SA CVCB3.SA PRIO3.SA ADHM3.SA AFLT3.SA LCAM3.SA INNT3.SA B3SA3.SA TECN3.SA ANIM3.SA OMGE3.SA OSXB3.SA LOGG3.SA DMMO3.SA TRIS3.SA YDUQ3.SA CCPR3.SA MSRO3.SA GSHP3.SA BBRK3.SA PTCA3.SA GPAR3.SA RNEW3.SA CEED3.SA CPRE3.SA GUAR3.SA ALUP3.SA MRVE3.SA CSRN3.SA EZTC3.SA JHSF3.SA IGSN3.SA LPSB3.SA TCSA3.SA CCXC3.SA MTRE3.SA TAEE3.SA CRDE3.SA MULT3.SA SGPS3.SA EMBR3.SA AGRO3.SA SMFT3.SA ABEV3.SA CNSY3.SA BNBR3.SA MDIA3.SA COCE3.SA CTCA3.SA BRPR3.SA BRML3.SA LINX3.SA ALSO3.SA TESA3.SA SMLS3.SA HAPV3.SA SEER3.SA BPAR3.SA BAZA3.SA EQPA3.SA FRIO3.SA BIOM3.SA ENEV3.SA ECOR3.SA SQIA3.SA LIQO3.SA ENBR3.SA MRFG3.SA ENMT3.SA LIGT3.SA DTCY3.SA EQTL3.SA TPIS3.SA TRPL3.SA GEPA3.SA PDGR3.SA HYPE3.SA JBSS3.SA SHOW3.SA CCRO3.SA COGN3.SA STBP3.SA MMXM3.SA VIVT3.SA TIMP3.SA EGIE3.SA CPFE3.SA RAIL3.SA IDNT3.SA LMED3.SA LWSA3.SA TGMA3.SA EKTR3.SA EMAE3.SA GPCP3.SA PSSA3.SA ECPR3.SA PEAB3.SA CARD3.SA BRFS3.SA FIGE3.SA GFSA3.SA BBML3.SA LIPR3.SA NEOE3.SA CIEL3.SA VSPT3.SA BTOW3.SA STKF3.SA BIDI3.SA ATOM3.SA TELB3.SA CMSA3.SA CEBR3.SA ELET3.SA BSLI3.SA BBAS3.SA"
  26.  
  27. # SOBRE VIÉS DE SOBREVIVÊNCIA: PODE SER TANTO NEGATIVO QUANTO POSITIVO (DIVERSAS EMPRESAS EXCELENTES SAÍRAM DA BOLSA NESSE PERÍODO, COMO REDECARD, CETIP, SOUZA CRUZ, ETC, PAGANDO BEM AO ACIONISTA)
  28.  
  29. cotacoes_yahoo = web.get_data_yahoo(tickers = tickers_ibov,start = start, end = end)["Adj Close"]
  30. volume_yahoo = web.get_data_yahoo(tickers = tickers_ibov,start = start, end = end)["Volume"]
  31.  
  32. #SEÇÃO 3 = PEGAR OS DADOS DO ÍNDICE BOVESPA E CALCULAR RETORNO
  33.  
  34. #ibov = web.get_data_yahoo(tickers = "BOVA11.SA" , start = start, end=end)["Adj Close"]
  35. ibov = web.get_data_yahoo(tickers = "^BVSP" , start = start, end=end)["Adj Close"]
  36. retorno_ibov = ibov.pct_change()
  37. retorno_acum_ibov = (1+retorno_ibov).cumprod()
  38. retorno_acum_ibov.iloc[0]=1
  39. ibov = ibov/ibov.iloc[0]
  40.  
  41. #SEÇÃO 4 = MANIPULAR OS OS DADOS CONFORME NECESSIDADE
  42.  
  43. #removedor de cotações em dias que não tem volume, para funcionar as dimensões das matrizes devem ser as mesmas
  44. linhas=len(cotacoes_yahoo)
  45. colunas=len(cotacoes_yahoo.columns)
  46.  
  47. k=0
  48. j=0
  49.  
  50. for k in range (linhas):
  51. for j in range (colunas):
  52. if (volume_yahoo.iloc[k,j] > 0): continue
  53. else:
  54. cotacoes_yahoo.iloc[k,j] = np.nan
  55. #end if
  56. j=j+1
  57. end
  58. k=k+1
  59. end
  60.  
  61. #removedor dos que tem menos que TANTOS dias de dados, setado abaixo
  62. dados_yahoo = cotacoes_yahoo.dropna(axis='columns', thresh = 2000)
  63. cotacoes_yahoo.dropna(how ="all", inplace=True)
  64.  
  65. #SEÇÃO 5 = CALCULAR RETORNO DAS AÇÕES
  66.  
  67. retorno = cotacoes_yahoo.pct_change()
  68. print (retorno)
  69.  
  70. #removedor de erros do yahoo de mudança de escala/ordem de grandeza
  71. linhas=len(retorno)
  72. colunas=len(retorno.columns)
  73.  
  74. k=0
  75. j=0
  76.  
  77. for k in range (linhas):
  78. for j in range (colunas):
  79. if (retorno.iloc[k,j] < 5) and ((retorno.iloc[k,j] > -0.99)): continue
  80. else:
  81. retorno.iloc[k,j] = 0
  82. #end if
  83. j=j+1
  84. end
  85. k=k+1
  86. end
  87.  
  88. retorno_acum = (1+retorno).cumprod()
  89. retorno_acum.iloc[0]=1
  90.  
  91. tamanhopop = len(list(cotacoes_yahoo.columns))
  92. print ("A população é",tamanhopop,".")
  93.  
  94. #salvar em CSV para usar em excel ou referência
  95. #retorno_acum.to_csv('retorno_acumulado.csv', sep=";", decimal=",")
  96. #cotacoes_yahoo.to_csv('cotacoes_yahoo.csv', sep=";", decimal=",")
  97. #volume_yahoo.to_csv('volumes_yahoo.csv', sep=";", decimal=",")
  98.  
  99. #SEÇÃO FINAL = CALCULAR RETORNO DAS CARTEIRAS E MOSTRAR OUTPUT
  100.  
  101. sns.set()
  102. ativos = 20
  103. macacos = 1000
  104.  
  105. contador = 0
  106. for i in range (macacos):
  107.  
  108. #nao repetem os ativos
  109. carteira = random.sample(list(cotacoes_yahoo.columns), k=ativos)
  110. carteira = retorno_acum.loc[ : , carteira]
  111. carteira["saldo"] = carteira.mean(axis=1)
  112. carteira["saldo"].plot(figsize=(22,8))
  113.  
  114. if (carteira['saldo'].iloc[-1]> retorno_acum_ibov.iloc[-1]):
  115. contador = contador + 1
  116.  
  117. mediageral = retorno_acum.mean(axis=1)
  118. mediageral.plot(label = "ibov",color = "black")
  119. ibov.plot(label = "ibov",color = "yellow")
  120.  
  121. print ("\033[1m","Percentual de macacos que bateram o IBOVESPA: {} %".format(contador/macacos*100))
  122. print ("\033[0m","Teste com",macacos,"macacos entre",start,"e",end,".")
  123. print (" Cada macaco escolheu aleatoriamente",ativos,"ativos de uma base de",colunas,"empresas.")
  124. print (" Gráfico de retorno comparativo dos macacos (linhas coloridas) com IBOV (linha preta):")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement