# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

import json
import requests
import pandas as pd

source = 'yahoo_url'
ibov = r'https://br.advfn.com/indice/ibovespa'


# +
def get_url():
    with open('../ref/config.json', 'r') as f: 
        return json.load(f).get(source)

def get_quotes(symbols: list, columns: list=None):
    url = get_url().format(','.join(symbols))
    r = requests.get(url)
    if r.status_code == 200:
        body = r.json().get('quoteResponse').get('result')
        if body is not None: 
            df = pd.DataFrame(body)
            df = df if columns is None else df[columns]
            return df
        else:
            return body
    else:
        return None

def get_ibov_rics():
    ativos = pd.read_html(requests.get(ibov).text)[3][:-1]['Ativo'].to_list()
    return list(map(lambda x: x + '.SA', ativos))

def get_percent_change(change):
    values = [float(i) for i in change.split('-')]
    diff = values[1] - values[0]
    return round((diff / values[0]) * 100,2)


# +
cols = ['symbol', 'longName', 'regularMarketPrice', 'regularMarketChangePercent', 'fiftyDayAverageChangePercent',
        'twoHundredDayAverageChangePercent', 'fiftyTwoWeekRange','epsTrailingTwelveMonths', 'trailingPE', 'trailingAnnualDividendYield']

adj_cols = ['fiftyDayAverageChangePercent', 'twoHundredDayAverageChangePercent', 'trailingAnnualDividendYield']
# -

rics = get_ibov_rics()
df = get_quotes(rics)[cols]

# +
for c in adj_cols: 
    df[c] = round(df[c] * 100,2)

    
df['12mMinMaxChange'] = df['fiftyTwoWeekRange'].apply(lambda x: get_percent_change(x))
# -



df.sort_values('epsTrailingTwelveMonths', ascending=False).to_csv('ibov.csv', index=False)

df

# get quote for single simbol
get_quotes(['CPLE6.SA']).T.to_csv('petr4.csv')



StarcoderdataJupyterScriptsDedupFiltered