-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompleted.py
224 lines (156 loc) · 6.34 KB
/
completed.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# -*- coding: utf-8 -*-
"""completed.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1hUi1VvpPqAVDFcqjK4IK_kYV3FqpgjS2
## Task 1 - Set Up
#### 1.1 Import Necessary Libraries
"""
# TASK 1.1: Import libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# %matplotlib inline
plt.style.use('fivethirtyeight')
# ignore warnings
import warnings
warnings.filterwarnings('ignore')
"""#### 1.2 Import Financial Data"""
# TASK 1.2: Import Apple's stock market price from 2006 to 2019
import pandas_datareader as pdr
import datetime
aapl = pdr.get_data_yahoo('AAPL',
start=datetime.datetime(2006, 10, 1),
end=datetime.datetime(2019, 1, 1))
"""## Task 2 - Work with Pandas Dataframe
#### 2.1 Check Data
"""
# Task 2.1.1 Check the structure of a Pandas Dataframe
print(aapl)
# Task 2.1.2 Use the describe() function to get some useful summary statistics about your data
print(aapl.describe(include = 'all'))
# Task 2.1.3 Check the general information of the dataframe
print(aapl.info())
# Task 2.1.4 Check the shape, columns and index of a Pandas Dataframe
print(aapl.shape)
print(aapl.columns)
print(aapl.index)
# Task 2.1.5 Check first few rows of dataframe
print(aapl.head())
# Task 2.1.6 Check last 10 rows of dataframe
print(aapl.tail(10))
# Task 2.1.7 Check the existence of null values
print(aapl.isnull().sum())
"""#### 2.2 Clean Data"""
# Task 2.2.1 Drop a column
aapl = aapl.drop(columns = ['High', 'Low'])
# Check the column has been dropped
print(aapl.head())
# Task 2.2.2 Keep wanted columns
aapl = aapl[['Close', 'Adj Close']]
print(aapl.head())
"""## Task 3 - Visualize Data (Exploratory Data Analysis)"""
# Task 3.1 Plot the closing price
aapl['Close'].plot()
# Task 3.2 Plot the closing price with some nice adjustments
aapl['Close'].plot(figsize = (15,5), linewidth = 1, legend = True)
# Task 3.2 Plot the closing and adjusted closing prices
aapl['Close'].plot(figsize = (15,5), linewidth = 1, legend = True)
aapl['Adj Close'].plot(figsize = (15,5), linewidth = 1, legend = True)
plt.legend(['Close', 'Adj Close'])
plt.title('Apple Stock Price')
plt.show()
"""## Task 4 - Build Your Trading Strategy"""
# Task 4.1 Initialize the short and long windows
short_window = 50
long_window = 100
# Task 4.2 Create moving averages over the short window
aapl['short_ma'] = aapl['Close'].rolling(window = short_window, min_periods = 1).mean()
aapl['long_ma'] = aapl['Close'].rolling(window = long_window, min_periods = 1).mean()
# Check the dataframe
aapl
# Task 4.3 Initilize as 0
aapl['higher_short_ma'] = 0
# Task 4.4 Set 1 for rows where short_ma is higher
aapl['higher_short_ma'][short_window:] = np.where(aapl['short_ma'][short_window:] > aapl['long_ma'][short_window:], 1, 0)
# Task 4.5 Print rows where higher_short_ma is of value 1
aapl[aapl['higher_short_ma'] == 1]
# Task 4.6 Generate trading signals
aapl['Signal'] = aapl['higher_short_ma'].diff()
# Check days when there is a trading signal
aapl[aapl['Signal'] != 0]
# Check the data in December of 2006 when buying happens
aapl['2006-12':].head(15)
# Check the data in February of 2008 when selling happens
aapl['2008-02':].head(15)
## Task 4.6 plot the short and long moving averages, together with the buy and sell signals
# Initialize the plot figure
fig = plt.figure(figsize = (15,5))
# Add a subplot and label for y-axis
ax1 = fig.add_subplot(111, ylabel='Price')
# Plot the closing price
aapl['Close'].plot(ax = ax1, color = 'r', linewidth = 1, legend = True)
# Plot the short and long moving averages
aapl[['short_ma', 'long_ma']].plot(ax = ax1, linewidth = 1, legend = True)
# Plot the buy signals
ax1.plot(aapl[aapl['Signal'] == 1].index,
aapl[aapl['Signal'] == 1]['short_ma'],
'^', markersize = 10, color = 'r', alpha = 0.6)
# Plot the sell signals
ax1.plot(aapl[aapl['Signal'] == -1].index,
aapl[aapl['Signal'] == -1]['short_ma'],
'v', markersize = 10, color = 'g', alpha = 0.6)
# Show the plot
plt.show()
"""## Task 5 - Test Your Strategy"""
# Task 5.1 Imagine you have 1 million
initial_capital= 1000000
# Task 5.2 Buy or Sell a 5k shares on the days that the signal is 1 or -1
aapl['Order'] = 5000 * aapl['Signal']
# Task 5.3 Calculate the transaction price paying (buy stocks) or receiving (sell stocks)
aapl['Transaction'] = aapl['Order'].multiply(aapl['Adj Close'], axis=0)
# Check data
aapl[aapl['Transaction'] != 0]
# Task 5.4 Calculate the number in shares owned
aapl['Shares'] = aapl['Order'].cumsum()
# Task 5.5 Calculate the value of shares owned
aapl['Holdings'] = aapl['Shares'].multiply(aapl['Adj Close'], axis=0)
# Task 5.6 Calculate the value of cash owned
aapl['Cash'] = initial_capital - (aapl['Transaction']).cumsum()
# Check the data in December of 2006 when buying happens
aapl['2006-12':].head(15)
# Check the data in February of 2008 when selling happens
aapl['2008-02':].head(15)
# Task 5.7 Calculate the total value of your portfolio
aapl['Total'] = aapl['Cash'] + aapl['Holdings']
# Check the data in December of 2006 when buying happens
aapl['2006-12':].head(15)
# Task 5.8 Visualize the portfolio value or over the years
# Create a figure
fig = plt.figure(figsize = (15,5))
ax1 = fig.add_subplot(111, ylabel='Portfolio value')
# Plot the equity curve
aapl['Total'].plot(ax = ax1, linewidth = 1)
ax1.plot(aapl[aapl['Signal'] == 1].index,
aapl[aapl['Signal'] == 1.0]['Total'],
'^', markersize = 10, color = 'r', alpha = 0.6)
ax1.plot(aapl[aapl['Signal'] == -1].index,
aapl[aapl['Signal'] == -1.0]['Total'],
'v', markersize = 10, color = 'g', alpha = 0.6)
# Show the plot
plt.show()
# Task 5.9 Visualize the portfolio value or over the years
# Resample `aapl` to 12 months, take last observation as value
yearly = aapl['Total'].resample('Y', convention='end').apply(lambda x: x[-1])
print(yearly)
# Task 5.10 Calculate the yearly return
yearly.pct_change()
# Task 5.11 Plot the yearly return
yearly.pct_change().plot(figsize = (15,5))
# aapl['Total'].plot(figsize = (15,5), linewidth = 1, legend = True)
# googl['Total'].plot(figsize = (15,5), linewidth = 1, legend = True)
# ibm['Total'].plot(figsize = (15,5), linewidth = 1, legend = True)
# amzn['Total'].plot(figsize = (15,5), linewidth = 1, legend = True)
# plt.legend(['AAPL', 'GOOGL', 'IBM', 'AMZN'])
# plt.title('Portfolio Value')
# plt.show()