#!/usr/bin/env python
# coding: utf-8
#
# # ** 5-2 Finance Analysis - Rolling**
# 파이썬을 활용한 금융분석
#
# ## **1 이동평균선을 활용한 매매 분석**
# Golden Cross / Death Cross
#
# ### **01 데이터 불러오기**
# pandas datareader
# In[1]:
# from pandas_datareader import get_data_yahoo
# start_date = '2013-01-01'
# codes = ['KO', 'MS', '005930.KS', '000660.KS']
# result = {}
# for code in codes:
# result[code] = get_data_yahoo(code, start_date).Close
# import pandas as pd
# prices = pd.DataFrame(result)
# prices = prices.fillna(method='ffill')
# prices = prices.dropna()
# prices.to_csv('./data/stocks.csv', encoding="ms949")
# prices.tail(3)
# In[2]:
# 저장된 CSV 파일을 사용한다
import pandas as pd
prices = pd.read_csv('./data/stocks.csv')
prices = prices.set_index('Date')
prices.head(3)
prices.index = pd.DatetimeIndex(prices.index)
prices.info()
#
# ### **02 Series.rolling( ).mean()**
# 이동평균 데이터 생성하기 [정리 Blog](http://ordo.tistory.com/67)
# In[3]:
import numpy as np
import pandas as pd
data = [ i for i in range(1, 3000, 2)]
data = pd.Series(data)
data[:12]
# In[4]:
data.rolling(10).min()[:12]
# In[5]:
data.rolling(10, center=True).mean()[:12]
# In[6]:
data.rolling(10, min_periods=3).mean()[:15]
# In[7]:
prices['005930.KS'].rolling(60, center=True).mean().plot(figsize=(15,4), color="red")
prices['005930.KS'].rolling(60, min_periods=3).mean().plot()
prices['005930.KS'].rolling(60).mean().plot(color='Green')
#
# ### **03 삼성전자의 이동평균선 생성**
# pd.Series.rolling()
# In[8]:
import pandas as pd
price_df = prices['005930.KS']
price_df = pd.DataFrame(price_df)
price_df.columns = ['Close']
price_df.head(3)
# In[9]:
import numpy as np
price_df['15d'] = np.round(price_df['Close'].rolling(15).mean(),2)
price_df['40d'] = np.round(price_df['Close'].rolling(40).mean(),2)
price_df['15d-40d'] = price_df['15d'] - price_df['40d']
price_df.tail(5)
# In[10]:
get_ipython().run_line_magic('matplotlib', 'inline')
price_df.plot()
# In[11]:
price_df.head(3)
# In[12]:
get_ipython().run_line_magic('matplotlib', 'inline')
# price_df['Close'].plot(grid = True, figsize = (15, 7))
price_df['15d'].plot(grid = True, figsize = (15, 7))
price_df['40d'].plot(grid = True)
price_df['15d-40d'].plot(grid = True)
import matplotlib.pyplot as plt
plt.legend()
# In[13]:
price_df.iloc[:, :3].plot(figsize=(12,5))
#
# ### **04 매매 시점 데이터 생성하기**
# np.where(조건문, True 일떄 값, False 일떄 값)
# In[14]:
price_df['15d-40d'].plot(figsize=(15,4))
# In[15]:
X = 100
price_df['Stance'] = np.where(price_df['15d-40d']> X, 1, 0)
price_df['Stance'] = np.where(price_df['15d-40d']< -X, -1, price_df['Stance'])
price_df['Stance'].value_counts()
# In[16]:
price_df['Stance'].plot(lw = 2, ylim = [-1.1, 1.1], figsize=(12,4))
plt.axhline(y = 0, linestyle = '--', color = 'k')
#
# ### **05 SMAC_Strategy (이동평균선 전략)으로 인한 수익률 데이터 생성**
# 주가를 로그 수익률로 변환한다 : 복리공식에 비해 계산의 용이성
# ### **np.shift()**
# ### **np.log()**
# In[17]:
# 로그수익률
price_df['Stock_Returns'] = np.log(price_df['Close'] / price_df['Close'].shift(1))
price_df['SMAC_Strategy'] = price_df['Stock_Returns'] * price_df['Stance'].shift(1)
price_df[['Stock_Returns','SMAC_Strategy']].cumsum().apply(np.exp).plot(grid = True, figsize = (10,6))
plt.axhline(y = 1, linestyle = '--', color = 'k')
plt.show()
# In[18]:
price_df['Stance2'] = np.where(price_df['15d-40d']>X, 1, 0)
price_df['Stance2'].plot(lw = 2, ylim = [-1.1, 1.1], figsize=(12,4))
plt.axhline(y = 0, linestyle = '--', color = 'k')
# In[19]:
price_df['Stock_Returns'] = np.log(price_df['Close'] / price_df['Close'].shift(1))
price_df['SMAC_Strategy2'] = price_df['Stock_Returns'] * price_df['Stance2'].shift(1)
# In[20]:
# price_df_log
price_df_log = price_df[['Stock_Returns','SMAC_Strategy','SMAC_Strategy2']].cumsum().apply(np.exp)
price_df_log.head(3)
# In[21]:
price_df_log.plot(grid = True, figsize = (14,6))
# In[22]:
price_df.tail()
#
# ### **06 기간별 수익률 계산하기**
# 로그 수익률 계산하기
# In[23]:
price_df.SMAC_Strategy['2017-05'].sum()
# In[24]:
price_df.SMAC_Strategy2['2017-07'].sum()