Zipline Example: Repeated AAPL Purchases with Cost Assumptions
Summary
This small Zipline example selects Apple shares during initialization and configures per-share commission and volume-share slippage. On every data callback, it submits an order for ten shares and records the current share price. The example therefore demonstrates basic order submission, price recording, and explicit transaction-cost assumptions in an algorithmic trading framework.
An analysis routine plots portfolio value alongside the recorded Apple price, and a test helper supplies a historical start and end date. The code does not include an entry signal, exit rule, position limit, or performance evaluation; repeated buying can accumulate exposure over time. It is a framework demonstration rather than a complete or risk-managed strategy, and it provides no results showing how the approach performed.
Key ideas
- The algorithm selects Apple as its traded asset and configures commission and slippage assumptions.
- It submits a fixed-size buy order at each data callback.
- It records the share price and plots it beside portfolio value.
- The example has no signal-based exits or position management and reports no performance evidence.
Tags
Full text
# buyapple.py
```py
#!/usr/bin/env python
#
# Copyright 2014 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from zipline.api import order, record, symbol
from zipline.finance import commission, slippage
def initialize(context):
context.asset = symbol("AAPL")
# Explicitly set the commission/slippage to the "old" value until we can
# rebuild example data.
# github.com/quantopian/zipline/blob/master/tests/resources/
# rebuild_example_data#L105
context.set_commission(commission.PerShare(cost=0.0075, min_trade_cost=1.0))
context.set_slippage(slippage.VolumeShareSlippage())
def handle_data(context, data):
order(context.asset, 10)
record(AAPL=data.current(context.asset, "price"))
# Note: this function can be removed if running
# this algorithm on quantopian.com
def analyze(context=None, results=None):
import matplotlib.pyplot as plt
# Plot the portfolio and asset data.
plt.clf()
ax1 = plt.subplot(211)
results.portfolio_value.plot(ax=ax1)
ax1.set_ylabel("Portfolio value (USD)")
ax2 = plt.subplot(212, sharex=ax1)
results.AAPL.plot(ax=ax2)
ax2.set_ylabel("AAPL price (USD)")
# Show the plot.
plt.gcf().set_size_inches(18, 8)
plt.show()
def _test_args():
"""Extra arguments to use when zipline's automated tests run this example."""
import pandas as pd
return {"start": pd.Timestamp("2014-01-01"), "end": pd.Timestamp("2014-11-01")}
```Shown in full with attribution under the source's licence. Licence: Apache-2.0
This summary was written by Stratmill's research agent from the original; it is not a copy of the source.