Build a simple trading strategy¶
In [60]:
from IPython.core.display import display, HTML
display(HTML("<style>.container {width:90% !important; }</style>"))
In [1]:
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
1. Munging the stock data and add two columns - MA10 and MA50¶
In [2]:
#import FB's stock data, add two columns - MA10 and MA50
#use dropna to remove any "Not a Number" data
fb = pd.DataFrame.from_csv('../data/facebook.csv')
#주가평균이동치 계산하기 rolling(일수)
fb['MA10'] = fb['Close'].rolling(10).mean()
fb['MA50'] = fb['Close'].rolling(50).mean()
fb = fb.dropna()
fb.head()
Out[2]:
In [18]:
fb['Close'].plot(legend=True)
fb['MA10'].plot(legend=True)
fb['MA50'].plot(legend=True)
Out[18]:
종가와 10일 이동평균선이 50일 이동평균선을 우상향 하였다. 이는 계속해서 상승세를 이어간다는 것을 보여준다.
여기서 우리의 전략은, if MA10> MA50 이라면, 주식을 사서 보유하는 것이다.
In [10]:
ms = pd.DataFrame.from_csv('../data/microsoft.csv')
ms['MA10']=ms['Close'].rolling(10).mean()
ms['MA50']=ms['Close'].rolling(50).mean()
ms=ms.dropna()
In [14]:
ms.head()
Out[14]:
In [19]:
ms['Close'].plot(legend=True)
ms['MA10'].plot(legend=True)
ms['MA50'].plot(legend=True)
Out[19]:
2. Add "Shares" column to make decisions base on the strategy¶
In [20]:
#Add a new column "Shares", if MA10>MA50, denote as 1 (long one share of stock), otherwise, denote as 0 (do nothing)
fb["Shares"]=[1 if fb.loc[ei,'MA10']>fb.loc[ei,'MA50'] else 0 for ei in fb.index]
In [29]:
fb.head()
Out[29]:
In [30]:
#Add a new column "Profit" using List Comprehension, for any rows in fb, if Shares=1, the profit is calculated as the close price of
#tomorrow - the close price of today. Otherwise the profit is 0.
#Plot a graph to show the Profit/Loss
fb['Close1'] = fb['Close'].shift(-1)
fb['Profit']=[fb.loc[ei,'Close1']-fb.loc[ei,"Close"] if fb.loc[ei,'Shares']==1 else 0 for ei in fb.index]
In [34]:
print(fb['Profit'].head())
In [35]:
fb['Profit'].plot()
plt.axhline(y=0, color='red')
Out[35]:
my work: 이동평균선 전략 수익 그래프로 나타내기 feat microsoft¶
In [38]:
# 1) MA10>MA50인 날만 주식 샀다고 가정
ms['Share']=[1 if ms.loc[id,'MA10']> ms.loc[id,'MA50'] else 0 for id in ms.index]
ms.head()
Out[38]:
In [46]:
# 2) 주식 산 날짜에 한해서 수익 계산하기
# 'Profit' 변수를 새로 만든다음 다음날 종가와 당일 종가 비교하기
ms['Close_T']=ms['Close'].shift(-1)
ms["profit"]=[ms.loc[index,'Close_T']-ms.loc[index,'Close'] if ms.loc[index,'Share']==1 else 0 for index in ms.index]
ms=ms.dropna()
ms.tail()
Out[46]:
In [47]:
ms["profit"].plot()
plt.axhline(y=0, color='red')
Out[47]:
3. Use .cumsum() to display our model's performance if we follow the strategy¶
In [48]:
#Use .cumsum() to calculate the accumulated wealth over the period
fb['wealth'] = fb['Profit'].cumsum()
fb.tail()
Out[48]:
In [49]:
#plot the wealth to show the growth of profit over the period
fb['wealth'].plot()
plt.title('Total money you win is {}'.format(fb.loc[fb.index[-2], 'wealth']))
Out[49]:
In [55]:
ms['wealth'] = ms['profit'].cumsum()
ms.tail()
Out[55]:
In [57]:
ms['wealth'] .plot()
plt.title('Total money you win is {}'.format(fb.loc[ms.index[-1], 'wealth']))
Out[57]: