import seaborn as sns
import pandas as pd
tips=sns.load_dataset('tips')
print(tips)
#corr() : 상관 계수 계산
corr=tips[['total_bill','tip']].corr()
print(corr)
total_bill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4
.. ... ... ... ... ... ... ...
239 29.03 5.92 Male No Sat Dinner 3
240 27.18 2.00 Female Yes Sat Dinner 2
241 22.67 2.00 Male Yes Sat Dinner 2
242 17.82 1.75 Male No Sat Dinner 2
243 18.78 3.00 Female No Thur Dinner 2
[244 rows x 7 columns]
total_bill tip
total_bill 1.000000 0.675734
tip 0.675734 1.000000
sns.regplot(x='total_bill',y='tip',data=tips)
import seaborn as sns
# 데이터셋 불러오기
tips=sns.load_dataset('tips')
#total_bill과 tip 간의 피어슨 상관계수 계산하기
corr=tips['total_bill'].corr(tips['tip'],method='pearson')
print('Pearson correlation coefficeint: ',corr)
Pearson correlation coefficeint: 0.6757341092113641
# 공분산 실습
covariance=tips['total_bill'].cov(tips['tip'])
print('Covariance between total_bill and tip:',covariance)
Covariance between total_bill and tip: 8.323501629224854
# total_bill과 tip 간의 관계를 산점도 그리기
sns.scatterplot(x='total_bill',y='tip',data=tips)
import numpy as np
# 선형 관계 데이터 생성
x_linear=np.linspace(0,10,100)
y_linear=2*x_linear+1
# 비선형 관계 데이터 생성
x_nonlinear=np.linspace(-10,10,100)
y_nonlinear=x_nonlinear**2
import matplotlib.pyplot as plt
# 선형 관계 시각화
plt.scatter(x_linear,y_linear)
plt.title('Linear Relationship')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
import matplotlib.pyplot as plt
# 비선형 관계 시각화
plt.scatter(x_nonlinear,y_nonlinear)
plt.title('Nonlinear Relationship')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
import seaborn as sns
# titanic 데이터 셋에서 일부 변수 선택
cols=['survived','pclass','age','fare']
# 선택한 변수들을 가지고 새로운 데이터 프레임 생성
df=sns.load_dataset('titanic')[cols].dropna()
print(df)
print('----------------------------------------------------')
# 다중 상관 분석 수행
corr=df.corr()
#결과 출력
print(corr)
survived pclass age fare
0 0 3 22.0 7.2500
1 1 1 38.0 71.2833
2 1 3 26.0 7.9250
3 1 1 35.0 53.1000
4 0 3 35.0 8.0500
.. ... ... ... ...
885 0 3 39.0 29.1250
886 0 2 27.0 13.0000
887 1 1 19.0 30.0000
889 1 1 26.0 30.0000
890 0 3 32.0 7.7500
[714 rows x 4 columns]
----------------------------------------------------
survived pclass age fare
survived 1.000000 -0.359653 -0.077221 0.268189
pclass -0.359653 1.000000 -0.369226 -0.554182
age -0.077221 -0.369226 1.000000 0.096067
fare 0.268189 -0.554182 0.096067 1.000000
import pandas as pd
import random
import os
# 랜덤하게 각 주식의 가격 100개의 데이터 생성
# 시계열 데이터는 항상 date형식으로 되어있어야함
dates=pd.date_range(start='2021-01-04',periods=100,freq='D')
# 삼성 전자 주식 데이터
samsung_prices=[random.randint(70000,90000) for _ in range(100)]
samsung_data={'Date':dates,'005930.KS':samsung_prices}
samsung_df=pd.DataFrame(samsung_data)
samsung_df.set_index('Date',inplace=True) # index를 Date로
# LG 전자 주식 데이터
lg_prices=[random.randint(140000,160000) for _ in range(100)]
lg_data={'Date':dates,'066570.KS':lg_prices}
lg_df=pd.DataFrame(lg_data)
lg_df.set_index('Date',inplace=True)
# 두 데이터프레임을 합쳐서 하나의 데이터프레임으로 만들기
df=pd.concat([samsung_df,lg_df],axis=1)
df=df.loc[:,['005930.KS','066570.KS']]
df.columns=['Samsung','LG']
# 폴더가 존재하는지 확인함
# exist_ok:이미 폴더가 생성되어있으면 error가 발생하는데 이를 방지하기 위함
os.makedirs('../data',exist_ok=True)
# csv 파일로 저장
df.to_csv('../data/stock_price.csv')
Samsung LG
Date
2021-01-04 83858 156996
2021-01-05 85268 140916
2021-01-06 77379 143397
2021-01-07 74939 149689
2021-01-08 76791 157237
... ... ...
2021-04-09 77304 149304
2021-04-10 81356 148745
2021-04-11 87872 150190
2021-04-12 78124 152083
2021-04-13 77708 149614
위의 내용인 Stock_price.csv로 data 폴더에 저장되었음
# csv 읽기
df=pd.read_csv('../data/stock_price.csv')
df['Date']=pd.to_datetime(df['Date'])
df.set_index('Date',inplace=True)
print(df)
# 두 종목의 수익률 계산
# 이전의 행값과의 비교를 통해 계산하게 됨
# 이전 값이 없는 2021-01-04 항은 NaN 값이 발생
returns = df.pct_change()
print(returns)
# 수익률 간의 상관 계수 계산
corr_matrix=returns.corr()
print(corr_matrix)
Samsung LG
Date
2021-01-04 84442 148737
2021-01-05 71308 155273
2021-01-06 83527 151413
2021-01-07 89668 149309
2021-01-08 76579 143914
... ... ...
2021-04-09 82455 152055
2021-04-10 76952 140631
2021-04-11 85507 157621
2021-04-12 83193 152896
2021-04-13 88491 148444
[100 rows x 2 columns]
Samsung LG
Date
2021-01-04 NaN NaN
2021-01-05 -0.155539 0.043943
2021-01-06 0.171355 -0.024859
2021-01-07 0.073521 -0.013896
2021-01-08 -0.145972 -0.036133
... ... ...
2021-04-09 0.141467 0.084604
2021-04-10 -0.066739 -0.075131
2021-04-11 0.111173 0.120813
2021-04-12 -0.027062 -0.029977
2021-04-13 0.063683 -0.029118
[100 rows x 2 columns]
Samsung LG
Samsung 1.000000 -0.099192
LG -0.099192 1.000000
import seaborn as sns
import matplotlib.pyplot as plt
# 히트맵 그리기
sns.heatmap(corr_matrix,annot=True,cmap='coolwarm')
plt.title('Stock Returns Correlation')
plt.show()
ex) 주가와 대통령 선거 결과 사이의 상관 관계 분석, 기업의 매출과 비용의 상관 관계 분석
ex) 어떤 제품의 판매량과 광고 비용 간에 어떤 상관 관계가 있는지를 분석하여 광고 비용을 얼마나 투자해야하는지