import pandas as pd
import yfinance as yf
import plotly
import plotly.graph_objs as go
colors_list=['royalblue', 'darkorange',
'dimgrey', 'rgb(86, 53, 171)', 'rgb(44, 160, 44)',
'rgb(214, 39, 40)', '#ffd166', '#62959c', '#b5179e',
'rgb(148, 103, 189)', 'rgb(140, 86, 75)',
'rgb(227, 119, 194)', 'rgb(127, 127, 127)',
'rgb(188, 189, 34)', 'rgb(23, 190, 207)']
def merge_time_series(df_1, df_2, how='outer'):
df = df_1.merge(df_2, how=how, left_index=True, right_index=True)
return df
def ichart(data, title='', colors=colors_list, yTitle='', xTitle='', style='normal',
hovermode='x', yticksuffix='', ytickprefix='',
ytickformat="", source_text='', y_position_source='-0.125', xticksuffix='',
xtickprefix='', xtickformat="", dd_range=[-50, 0], y_axis_range_range=None):
'''
style = normal, area, drawdowns_histogram
colors = color_list or lightcolors
hovermode = 'x', 'x unified', 'closest'
y_position_source = -0.125 or bellow
dd_range = [-50, 0]
ytickformat = ".1%"
'''
fig = go.Figure()
fig.update_layout(
paper_bgcolor='#F5F6F9',
plot_bgcolor='#F5F6F9',
hovermode=hovermode,
title=title,
title_x=0.5,
yaxis = dict(
ticksuffix=yticksuffix,
tickprefix=ytickprefix,
tickfont=dict(color='#4D5663'),
gridcolor='#E1E5ED',
range=y_axis_range_range,
titlefont=dict(color='#4D5663'),
zerolinecolor='#E1E5ED',
title=yTitle,
showgrid=True,
tickformat=ytickformat,
),
xaxis = dict(
title=xTitle,
tickfont=dict(color='#4D5663'),
gridcolor='#E1E5ED',
titlefont=dict(color='#4D5663'),
zerolinecolor='#E1E5ED',
showgrid=True,
tickformat=xtickformat,
ticksuffix=xticksuffix,
tickprefix=xtickprefix,
),
images= [dict(
name= "watermark_1",
source= "https://raw.githubusercontent.com/LuisSousaSilva/Articles_and_studies/master/FP-cor-positivo.png",
xref= "paper",
yref= "paper",
x= -0.07500,
y= 1.250,
sizey= 0.15,
sizex= 0.39,
opacity= 1,
layer= "below"
)],
annotations=[dict(
xref="paper",
yref="paper",
x= 0.5,
y= y_position_source,
xanchor="center",
yanchor="top",
text=source_text,
showarrow= False,
font= dict(
family="Arial",
size=12,
color="rgb(150,150,150)"
)
)
]
), # end
if style=='normal':
z = -1
for i in data:
z = z + 1
fig.add_trace(go.Scatter(
x=data.index,
y=data[i],
mode='lines',
name=i,
line=dict(width=1.3,
color=colors[z]),
))
if style=='area':
z = -1
for i in data:
z = z + 1
fig.add_trace(go.Scatter(
x=data.index,
y=data[i],
hoverinfo='x+y',
mode='lines',
name=i,
line=dict(width=0.7,
color=colors[z]),
stackgroup='one' # define stack group
))
if style=='drawdowns_histogram':
fig.add_trace(go.Histogram(x=data.iloc[:, 0],
histnorm='probability',
marker=dict(colorscale='RdBu',
reversescale=False,
cmin=-24,
cmax=0,
color=np.arange(start=dd_range[0], stop=dd_range[1]),
line=dict(color='white', width=0.2)),
opacity=0.75,
cumulative=dict(enabled=True)))
return fig
def compute_growth_index(dataframe, initial_value=100, initial_cost=0, ending_cost=0):
initial_cost = initial_cost / 100
ending_cost = ending_cost / 100
GR = ((1 + dataframe.pct_change()).cumprod()) * (initial_value * (1 - initial_cost))
GR.iloc[0] = initial_value * (1 - initial_cost)
GR.iloc[-1] = GR.iloc[-1] * (1 * (1 - ending_cost))
return GR
def download_quotes_yahoo(tickers,
growth_index=False,
start_date='1970-01-01',
end_date='2030-06-12'):
# Create empty DataFrame
ETFs = pd.DataFrame()
for ticker in tickers:
# Download Quotes
etf = yf.download(ticker,start = start_date, end = end_date, progress=False)
# Get only Adj Close column as Dataframe
etf = etf[['Adj Close']]
# Change Column name
etf.columns = [ticker]
# Merge time series de etf com ETFs
ETFs = merge_time_series(ETFs, etf)
# Start when all ETFs are on the market
ETFs = ETFs.dropna()
if growth_index:
ETFs = compute_growth_index(ETFs)
return ETFs
Download de cotações da yahoo finance
# Função para data actual para cromos usarem
from datetime import date
today_date = date.today().strftime("%Y-%m-%d")
today_date
# Download apple quotes
aapl_df = yf.download('AAPL',
start='1970-01-01',
end='2030-06-12',
progress=False,
)
# Get only Adj Close column as Dataframe
aapl_df = aapl_df[['Adj Close']]
# Change Column name
aapl_df.columns = ['AAPL']
print(aapl_df.head())
print(aapl_df.tail())
aapl_df.info()
aapl_df.plot();
For loop para download do yahoo finance
tickers = ['SPY','QQQ']
# Create empty DataFrame
ETFs = pd.DataFrame()
for ticker in tickers:
# Download Quotes
etf = yf.download(ticker,start='1970-01-01',
end='2030-06-12',
progress=False)
# Get only Adj Close column as Dataframe
etf = etf[['Adj Close']]
# Change Column name
etf.columns = [ticker]
# Merge time series de etf com ETFs
ETFs = merge_time_series(ETFs, etf)
# Start when all ETFs are on the market
ETFs = ETFs.dropna()
ETFs
ETFs_growth = compute_growth_index(ETFs['2020-01-01':])
ichart(round(ETFs_growth, 2))
Funções que resumem a live
etfs_yahoo_finance = download_quotes_yahoo(['SPY','QQQ'],
growth_index=True,
start_date='2020-01-01')
ichart(etfs_yahoo_finance)