import pandas as pd
import pandas_datareader.data as web
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('fivethirtyeight')
%matplotlib inline
sector_name = {'xlb':'BasicMaterials', 'xle':'Energy', 'xlf':'Financial', 'xli':'Industrial', 'xlk':'Technology', 'xlp':'ConsumerStaples'
, 'xlu':'Utilities', 'xlv':'HealthCare', 'xly':'ConsumerDiscretionary'}
Symbol = ['xlv','xly','xlk','xlp','xlu','xlf','xli','xle','xlb']
start = '2020/05/01'
end = '2020/12/15'
Price = web.get_data_yahoo(Symbol,start=start,end=end)
Price = Price['Adj Close'].rename(sector_name, axis='columns')
daily_returns = Price.pct_change().dropna()
daily_returns # เรียกดูตัวอย่างข้อมูล
Symbols | HealthCare | ConsumerDiscretionary | Technology | ConsumerStaples | Utilities | Financial | Industrial | Energy | BasicMaterials |
---|---|---|---|---|---|---|---|---|---|
Date | |||||||||
2020-05-01 | -0.019052 | -0.037393 | -0.027459 | -0.010985 | -0.024101 | -0.032032 | -0.030213 | -0.056579 | -0.021010 |
2020-05-04 | -0.000511 | 0.005435 | 0.013273 | -0.000521 | 0.007516 | -0.009066 | -0.012687 | 0.034589 | 0.003544 |
2020-05-05 | 0.021681 | 0.003633 | 0.013766 | 0.000868 | 0.008170 | -0.003202 | 0.003904 | 0.000809 | 0.002550 |
2020-05-06 | -0.009910 | -0.000177 | 0.007775 | -0.010930 | -0.034003 | -0.021570 | -0.013772 | -0.026131 | -0.017221 |
2020-05-07 | -0.000101 | 0.015719 | 0.014995 | -0.002807 | 0.004012 | 0.023452 | 0.011664 | 0.026003 | 0.020510 |
... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
2020-12-09 | -0.003461 | -0.000953 | -0.019163 | -0.003986 | -0.001758 | -0.002433 | 0.002242 | 0.002235 | 0.000558 |
2020-12-10 | -0.001692 | -0.000891 | 0.001447 | -0.004446 | -0.005123 | 0.001742 | -0.009507 | 0.030723 | -0.006132 |
2020-12-11 | -0.003924 | -0.004776 | -0.002087 | 0.002233 | 0.001609 | -0.010087 | 0.002371 | -0.011538 | -0.005749 |
2020-12-14 | -0.007522 | 0.001472 | 0.003620 | -0.003862 | -0.005141 | -0.011595 | -0.012955 | -0.035019 | -0.012694 |
2020-12-15 | 0.010826 | 0.013480 | 0.016673 | 0.002386 | 0.019703 | 0.017064 | 0.013924 | 0.019657 | 0.018143 |
159 rows × 9 columns
# calculate the correlation matrix
corr = daily_returns.corr()
# plot the heatmap
plt.figure(figsize=(15,8))
sns.heatmap(corr, annot=True, ).set_title("Sector Correlation")
Text(0.5, 1.0, 'Sector Correlation')
etf_return = Price.apply(lambda x: x / x[0])
etf_return.dropna().plot(figsize=(30,15))
<matplotlib.axes._subplots.AxesSubplot at 0x7fedfa6cdd10>
# calculate the correlation matrix
#ผลตอบแทนแต่ละ sector ถึงปัจจุบัน
return_rank = etf_return.iloc[-1].sort_values(ascending = False)-1
return_rank.plot.bar(figsize=(20,8)).set_title("Ranking Performance")
Text(0.5, 1.0, 'Ranking Performance')