Commit Graph

101 Commits

Author SHA1 Message Date
Scott Sanderson 0338dd73e1 ENH: Filter out empty lists from get_open_orders.
Filter out empty lists from `get_open_orders` so that we have consistent
behavior between the case where a user has never placed an order and the case
where the user has placed an order but it has been executed or cancelled.

A nice side-effect, which was the impetus for this change, is that you can
check if you have any open orders by doing:

```
len(get_open_orders()) == 0
```

Also adds a test for the behavior of `get_open_orders`, which was previously
lacking.
2014-05-29 13:04:53 -04:00
Scott Sanderson ecd9bff0d6 PERF/BUG: Make the portfolio property call updated_portfolio.
Make the portfolio property on TradingAlgorithm call `updated_portfolio`
internally.  This prevents needless recomputation of the portfolio between
calls to `handle_data`, and also prevents issues where the portfolio object
could be unexpectedly modified in place in the body of a `handle_data` call.

Noteworthy finding in the course of investigating this bug:

If you modify a Python dictionary while iterating over it, the language will
only throw an exception if the size of the dictionary changes between loop
iterations; this means that you can do:
```
x = {1:1, 2:2, 3:3}
for k in x:
    old_val = x[k]
    del x[k]
    x[f(k)] = old_val
    print k
```
and you'll only get an error if f(k) is already a key in the dictionary.
This can lead to bizarre/nondeterministic behavior in the key iterator.
2014-05-27 11:20:13 -04:00
Scott Sanderson c3075f0ece ENH: Add a classmethod to TradingAlgorithm to get all API methods. 2014-05-14 11:24:33 -04:00
Scott Sanderson 644486e6da ENH: Add trading controls to zipline API.
Adds four new methods to the Zipline API that can be used as circuit-breakers
to interrupt the execution of an algorithm.  The API methods are:

`set_max_position_size`
`set_max_order_size`
`set_max_order_count`
`set_long_only`

Internally, these methods are implemented by each registering a TradingControl
callback object with the TradingAlgorithm.  During
TradingAlgorithm.__validate_order_params (and thus before any side-effects of
the order call occur), each callback's `validate` method is called with
information about the order to be placed and the algorithm's current state,
raising an exception if the callback detects that an error condition has been breached.
2014-05-12 17:51:09 -04:00
twiecki f5086e4b0e ENH: Add IPython cell magic.
When zipline is imported it checks whether
it runs in the IPython notebook. If it does,
it registers a %%zipline magic that takes the
same arguments as the CLI with the addition of
a -o for specifying the output variable to store
the performance frame in.

The algo code in the cell is, as of yet, executed
in its own environment rather than that of the
IPython NB which is probably what we want.

Also adds cli option to save the perf dataframe
to a pickle file.

Also adds an IPython notebook buyapple example.
2014-05-07 15:34:41 -04:00
twiecki f9fded97ac ENH: Implement CLI.
Add a CLI that reads in an algorithm, loads data,
run the algorithm, and output performance metrics.

The examples are adapted to the new zipline API and
analyses are split into separate files.

Also add config files that run the example
algorithms with preset settings.
2014-05-07 15:34:36 -04:00
Scott Sanderson f1fafc34ce ENH: Add style parameters to order API helper methods.
Add `style` parameter to order_value, order_percent, order_target,
order_target_percent, and order_target_value methods.  The style parameter is
forwarded to the underlying call to `order`.
2014-04-22 23:22:21 -04:00
Scott Sanderson 119a1a4cda ENH: Update ordering API to support new ExecutionStyle class in favor of
existing `limit_price` and `stop_price` parameters.  The goal of this change is
to refactor the existing ordering API to provide a cleaner interface for
defining more complex order types.

Adds a new module, zipline.finance.execution, which defines the ExecutionStyle
abstract base class, along with concrete MarketOrder, LimitOrder, StopOrder,
and StopLimitOrder subclasses.

Adds a new `style` keyword argument to the function signature of the `order`
API method, which accepts an instance of ExecutionStyle.

The existing limit_price and stop_price parameters are still supported at this
time, but are converted into the new ExecutionStyle objects before being passed
to Blotter.order.
2014-04-22 23:22:21 -04:00
Scott Sanderson 47bfc2b536 MAINT: Clean up set_algo_instance usage in TradingAlgorithm.
TradingAlgorithm always uses set_algo_instance in pairs of
set_algo_instance(self) and set_algo_instance(None).  Refactoring this to use a
context manager.
2014-04-17 16:19:37 -04:00
twiecki e261438d01 ENH: Adapt history() to work on zipline. 2014-04-10 15:59:26 -04:00
Jeremiah Lowin 25659f9672 MAINT: Use current_data instead of last_sale_price
It seems more clear to get price values from
`self.trading_client.current_data[sid].price` than
from `self.portfolio.positions[sid].last_sale_price`.

The two values are the same, so this is just a readability change,
but it is also the same behavior as in `self.order_value()` and it's
good to have them all be the same.
2014-03-27 15:25:14 -04:00
Jeremiah Lowin d00edbcf04 BUG: check that self.logger exists
`self.logger` is initialized as `None` and there is no guarantee that
users have set it, so check that it exists before trying to pass
messages to it.
2014-03-24 22:06:03 -04:00
Eddie Hebert 4860a966b3 REL: Update copyright year on all files changed since the new year. 2014-03-07 22:31:41 -05:00
Eddie Hebert a203f69635 PERF: Remove alias_dt transform in favor of property on SIDData.
Adding a copy of the Event's dt field as datetime via the
`alias_dt` generator, so that the API was forgiving and allowed
both datetime and dt on a SIDData object, was creating noticeable
overhead, even on an noop algorithms.

Instead of incurring the cost of copying the datetime value and
assigning it to the Event object on every event that is passed
through the system, add a property to SIDData which acts as an
alias `datetime` to `dt`.

Eventually support for `data['foo'].datetime` may be removed,
and could be considered deprecated.
2014-03-07 10:55:59 -05:00
Eddie Hebert 57c56351e9 MAINT: Re-enable algorithms which omit initialize method.
Though defining the `initialize` method may end up being explicitly
required, in the meantime prevent existing algorithms from crashing
by providing a noop function when `initialize` is not defined.
2014-02-20 13:50:03 -05:00
Eddie Hebert e1608ad3f3 MAINT: Always defer to the algorithms data frequency.
For compatibility with existing behavior of having the,
data_frequency of the algorithm override the simulation parameters.

We may want to consider throwing an exception if the two do not match.
2014-02-10 15:24:18 -05:00
Eddie Hebert 8a22736f1e MAINT: Allow sim_params to provide data frequency for the algorithm.
In the case that data_frequency of the algorithm is None,
allow the sim_params to provide the data_frequency.

For less redundancy when setting up an algorithm.
2014-02-10 14:53:11 -05:00
Jamie Kirkpatrick 147242339d BUG: ensure perf stats are generated for all days
When running with minutely emissions the simulator would report to the
user that it simulated 'n - 1' days (where n is the number of days
specified in the simulation params).  Now the correct number of trading
days are reported as being simulated.
2014-01-30 16:04:29 -05:00
Jamie Kirkpatrick 45844bac31 BUG: adjust benchmark events to match market hours
Previously benchmark events were emitted at 0:00 on the day the
benchmark related to: in 'minute' emission mode this meant that
the benchmarks were emitted before any intra-day trades were
processed.

See: https://github.com/quantopian/zipline/issues/241
2014-01-30 16:01:58 -05:00
Thomas Wiecki b69590a2f7 ENH: Factor out API methods. Add support for algo scripts.
This is a step towards the goal of uniting Quantopian scripts
and zipline.

To make the syntax of zipline identical to Quantopian
we break out the API methods (like order) and turn them into
functions. To access the algo object we add a thread local reference
to the current algorithm that is accessed in the API functions.

TradingAlgorithm now takes either a string or two functions
(initialize and handle_data) that it executes.

Use api method decorator for methods available in algoscript.

Ported appropriate algorithm tests from internal code.
2014-01-16 12:07:33 -05:00
Eddie Hebert b4959e46cf MAINT: Use six for Python 3 compatible names and behavior.
Use the six module to import functions and types that are
consistent between Python 2 and 3, so that one code base can
support both versions.

- Use integer types instead of int and long.
- Use string_types instead of basestring.
- Account for iteritems, itervalues, iterkeys.
- Use six.moves for filter and zip, reduce
- Use compatible bytes for md5 hasher.
- xrange and range
2014-01-07 11:33:50 -05:00
Thomas Wiecki 8524039580 REF: Moved trading-related methods from AlgoProxy. 2013-12-19 09:59:34 -05:00
Thomas Wiecki d52a7b6d8e DOC: Added doc string for instant_fill. 2013-12-04 07:16:18 -05:00
Thomas Wiecki 860a340e55 BUG: Erroneous call to log. 2013-11-25 19:52:05 -05:00
Thomas Wiecki c199a0d956 STY: Move order_value from blotter to TradingAlgorithm. 2013-11-25 17:38:30 -05:00
Thomas Wiecki 579cb56663 STY: Long line break for pep8. 2013-11-25 12:16:41 -05:00
Thomas Wiecki 9cb9831c08 STY: Prepend order_ to all target methods. 2013-11-25 11:28:27 -05:00
Eddie Hebert ccb7f493f7 PERF: Only update the portfolio once per dt.
So that each reference to `.portfolio` in the algoscript,
cache the value of the portfolio, and mark the need for a new
value at the end of each dt in the tradesimulation loop.
2013-11-19 14:39:19 -05:00
fawce 6d46eb71ea PERF: moved performance calculation out of inner loop
lazy loading for portfolio
less repeating in performance period updates
2013-11-19 10:39:57 -05:00
stanh 1f1be35734 ENH: Added commission model PerDollar
Commissions will be calculated based on total dollar traded.
2013-11-15 11:49:58 -05:00
Jonathan Kamens 73faf9133e MAINT: Clean up imports of zipline.finance.trading
Use "from zipline.finance import trading" instead of "import
zipline.finance.trading as trading".
2013-10-29 13:50:14 -04:00
Eddie Hebert 37c56b9aa4 MAINT: Use Series throughout for daily returns.
Remove the lists of DailyReturn objects in favor of using pd.Series
to store the return values.

Should make it easier to inspect the values when stepping through,
make the windowing of data to a certain range more facile by using,
and have some performance increases due to removing object creation
and member access.
2013-10-19 23:06:18 -04:00
Thomas Wiecki 65637b9430 ENH: Add option of instantly filling orders. 2013-10-01 20:30:01 -04:00
Jeremiah Lowin 48486c9814 ENH: New order methods. 2013-08-08 15:54:59 -04:00
Thomas Wiecki e1475cc24f BUG: cum_perfs defined but not used. 2013-08-01 16:33:26 -04:00
Thomas Wiecki 37bab9bb72 ENH: Safe risk_report in TradingAlgorthm. 2013-08-01 16:08:56 -04:00
Eddie Hebert 9ff588e7fc BUG: Fix spelling of capital base in TradingAlgorithm repr.
s/captial_base/capital_base/
2013-07-23 14:40:39 -04:00
Eddie Hebert b7b4d397ba BUG: Revert "Merge ability to specify timing of fills."
This reverts commit e3a9ca27b1, reversing
changes made to 3d8bdeb429.

Conflicts:
	zipline/gens/tradesimulation.py

The aforementioned change needs a revert because it caused a 'doubling'
of orders, since the portfolio is not updated until after handle_data
is called a second time after an order has been processed.

The flexibility of fill_delay is still desired, but remove for now,
favoring reverting back to existing behavior over trying ot fix the
fill_delay logic.
2013-07-15 10:47:55 -04:00
Eddie Hebert d901a12e93 BUG: Prevent algorithm init failure due to missing fill_delay.
Provide a default value for data_frequency, choosing 'daily',
so that the fill_delay is set even when a data_frequency value
is not in kwargs.

This does open up a place for disjointedness if the sim_params that
is passed to run does not match the data_frequency set during initialize.
2013-07-09 12:45:56 -04:00
Thomas Wiecki 5a58ade0fc ENH: Add flag fill_delay kwarg to TradingAlgorithm. 2013-07-09 11:38:09 -04:00
Matti Hanninen 43d3757004 DOC: Fix docstring for TradingAlgorithm
Get the amount from the algorithm object instead of referring to
a (undefined) global.
2013-06-14 15:43:51 -04:00
Matti Hanninen d475766c63 DOC: Fix docstring for TradingAlgorithm
Fix the example given in the class docstring as the original didn't work
on REPL.
2013-06-14 15:43:40 -04:00
Eddie Hebert 4bde1e4c11 MAINT: Change slippage guard to check for slippage model base type.
Now that VolumeShareSlippage and FixedSlippage inherit from the same
class, check for `SlippageModel` instead of the inividual classes.
2013-06-10 10:27:16 -04:00
Jonathan Kamens f9580316c9 MAINT: Reformat comment to make flake8 happy 2013-05-30 10:06:23 -04:00
Eddie Hebert 0ef428c8e0 BUG: Fix exception when using capital_base as a kwarg to an algorithm.
Need to pop of the kwarg, since `initialize` does not use it as a
parameter.
2013-05-21 17:51:51 -04:00
Richard Frank 381df3534d MAINT: Ensure we're not setting the blotter to None. 2013-05-10 12:09:38 -04:00
Eddie Hebert b33243da63 BUG: Ensure that data_frequency set on algo is set on sim_params.
Set the data_frequency member of an algorithm on the sim_params
configuration object.

Though the extra setting is slightly redundant, it is needed to
ensure that the same data_frequency is used throughout.

Should fix a bug where an algo that was intended to be run in minute
mode was operating as if it were daily in performance.

Possible TODO: Remove data_frequency as a param to TradingAlgorithm,
in favor of only being a property of sim_params.
2013-05-09 03:44:51 -04:00
Eddie Hebert 91e5abbc44 MAINT: Use a for loop for main algorithm run loop instead of list
So that stepping through a debugger is a little easier, with
respect to having easy access to the algorithm object, and seeing
which step in `self.gen` the interpreter is currently at.
2013-05-07 17:19:38 -04:00
Eddie Hebert aa54d0ae0e MAINT: Allow the algorithm benchmark returns to be overrideable.
So that test data can be well defined with a short list of benchmarks.

This could also lead to having more customizable benchmarks for
backtests.
2013-05-07 16:09:58 -04:00
Eddie Hebert 4b7afb43d2 MAINT: Change repr's so that they are both human and machine readable.
For printability in the repr when debugging algo config and state,
change the repr of TradingAlgorithm and the objects it contains
so that the more closely adhere to the repr interface of being
able to recreate an object instance.
2013-05-04 22:26:28 -04:00