1
|
|
|
#!/usr/bin/env python |
2
|
|
|
# |
3
|
|
|
# Copyright 2014 Quantopian, Inc. |
4
|
|
|
# |
5
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License"); |
6
|
|
|
# you may not use this file except in compliance with the License. |
7
|
|
|
# You may obtain a copy of the License at |
8
|
|
|
# |
9
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0 |
10
|
|
|
# |
11
|
|
|
# Unless required by applicable law or agreed to in writing, software |
12
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS, |
13
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
14
|
|
|
# See the License for the specific language governing permissions and |
15
|
|
|
# limitations under the License. |
16
|
|
|
|
17
|
|
|
from zipline.api import order, record, symbol |
18
|
|
|
|
19
|
|
|
|
20
|
|
|
def initialize(context): |
21
|
|
|
pass |
22
|
|
|
|
23
|
|
|
|
24
|
|
|
def handle_data(context, data): |
25
|
|
|
order(symbol('AAPL'), 10) |
26
|
|
|
record(AAPL=data[symbol('AAPL')].price) |
27
|
|
|
|
28
|
|
|
|
29
|
|
|
# Note: this function can be removed if running |
30
|
|
|
# this algorithm on quantopian.com |
31
|
|
|
def analyze(context=None, results=None): |
32
|
|
|
import matplotlib.pyplot as plt |
33
|
|
|
# Plot the portfolio and asset data. |
34
|
|
|
ax1 = plt.subplot(211) |
35
|
|
|
results.portfolio_value.plot(ax=ax1) |
36
|
|
|
ax1.set_ylabel('Portfolio value (USD)') |
37
|
|
|
ax2 = plt.subplot(212, sharex=ax1) |
38
|
|
|
results.AAPL.plot(ax=ax2) |
39
|
|
|
ax2.set_ylabel('AAPL price (USD)') |
40
|
|
|
|
41
|
|
|
# Show the plot. |
42
|
|
|
plt.gcf().set_size_inches(18, 8) |
43
|
|
|
plt.show() |
44
|
|
|
|
45
|
|
|
|
46
|
|
|
# Note: this if-block should be removed if running |
47
|
|
|
# this algorithm on quantopian.com |
48
|
|
|
if __name__ == '__main__': |
|
|
|
|
49
|
|
|
from datetime import datetime |
50
|
|
|
import pytz |
51
|
|
|
from zipline.algorithm import TradingAlgorithm |
52
|
|
|
from zipline.utils.factory import load_from_yahoo |
53
|
|
|
|
54
|
|
|
# Set the simulation start and end dates |
55
|
|
|
start = datetime(2014, 1, 1, 0, 0, 0, 0, pytz.utc) |
56
|
|
|
end = datetime(2014, 11, 1, 0, 0, 0, 0, pytz.utc) |
57
|
|
|
|
58
|
|
|
# Load price data from yahoo. |
59
|
|
|
data = load_from_yahoo(stocks=['AAPL'], indexes={}, start=start, |
60
|
|
|
end=end) |
61
|
|
|
|
62
|
|
|
# Create and run the algorithm. |
63
|
|
|
algo = TradingAlgorithm(initialize=initialize, handle_data=handle_data, |
64
|
|
|
identifiers=['AAPL']) |
65
|
|
|
results = algo.run(data) |
66
|
|
|
|
67
|
|
|
analyze(results=results) |
68
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.