Esempio n. 1
0
def compare_stocks(dfs, timestamps):
    '''
        Input: dfs - list of dataframes for the different stocks to be compared
               timestamps - list of start and end time of the time period to be analysed

        Output: daily_returns - dataframe of the daily returns of all the stocks
                fig1 - correlation grid of the adjusted closing price of all the stocks
                fig2 - correlation matrix of the daily returns of all the stocks

    '''

    closing = DataReader(dfs, 'yahoo', timestamps[0], timestamps[1])['Adj Close']
    daily_returns = closing.pct_change()
    x = [str(daily_returns.dropna().index[i]).split()[0] for i in range(len(daily_returns.dropna()))]

    fig1 = sns.PairGrid(daily_returns.dropna(), )
    fig1.map_upper(plt.scatter, color='#330C73')

    fig1.map_lower(sns.kdeplot, cmap='RdPu_r')

    fig1.map_diag(plt.hist, bins=30)
    fig1.fig.suptitle(
        f'Graphical correlation between the different stocks for the daily returns from {x[0]} to {x[len(x) - 1]}',
        fontsize=18, y=1.03)

    fig2, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 7))
    sns.heatmap(closing.corr(), annot=True, cmap='PuBu', ax=ax1)
    sns.heatmap(daily_returns.corr(), annot=True, cmap='PuRd', ax=ax2)

    fig2.suptitle(
        f'Correlation between the different stocks for the closing price and the daily returns from {x[0]} to {x[len(x) - 1]}',
        fontsize=18)
    ax1.set_title('Adjusted Closing Price USD ($)')
    ax2.set_title('Daily returns USD ($)')
    ax1.set_xlabel('')
    ax2.set_xlabel('')
    ax1.set_ylabel('')
    ax2.set_ylabel('')

    return daily_returns, fig1, fig2
bank_list = ['KBANK.BK','BBL.BK','SCB.BK','TMB.BK']
closing_df = DataReader(bank_list, 'yahoo', start, end)['Adj Close']
closing_df

bank_returns_df = closing_df.pct_change()
bank_returns_df

# Pairplot
sns.pairplot(bank_returns_df, kind='reg')
plt.show()

#Note: The pairplot shows that most of them are related, AKA, they go along together.

# Correlation Plot
fig, axes = plt.subplots(2,1, figsize=(16,8))
sns.heatmap(closing_df.corr(), annot=True, cmap='summer', ax=axes[0])
axes[0].set_title('Correlation of Percentage Return')
sns.heatmap(bank_returns_df.corr(), annot=True, cmap='summer', ax=axes[1])
axes[1].set_title('Correlation of Closing Price (Adj Close)')
plt.suptitle('Correlation')
plt.show()

#Note: BBL & TMB seem to have no correlation according to Percentage Return
#Note: KBANK & SCB seem to have strong correlation according to Percentage Return



### Risk and Return ###
# There are many ways we can quantify risk, 
# one of the most basic ways using the information we've gathered on 
# daily percentage returns is by comparing the expected return with the 
#Using map_upper we can specify what upper triangle will look like.
return_fig.map_upper(plt.scatter, color='purple')

#we can also define the lower triagle in the figure
#Colo map()
return_fig.map_lower(sns.kdeplot, cmap='cool_d')

#define the diagonal as a series of histrogram plot of the daily return
return_fig.map_diag(plt.hist, bins=30)

# %%
# Quick corellation on plot for the daily returns
sns.heatmap(tech_rets.corr(), annot=True, cmap='summer')
#%%

sns.heatmap(closing_df.corr(), annot=True, cmap='summer')
# %%
#New DataFrame withou the version of origianl Tech_rets DataFrame

rets = tech_rets.dropna()

area = np.pi * 20

plt.figure(figsize=(12, 10))
plt.scatter(rets.mean(), rets.std(), s=area)
plt.xlabel('Expected return')
plt.ylabel('Risk')

for label, x, y in zip(rets.columns, rets.mean(), rets.std()):
    plt.annotate(label,
                 xy=(x, y),