Commit Graph

128 Commits

Author SHA1 Message Date
Joe Jevnik f8f7f2fc4c ENH: Allows history to be dynamic and grow the container at runtime.
Previously, all specs had to be pre-allocated by using the 'add_history'
function. This is now no longer required and instead serves as a hint to
the HistoryContainer to pre-allocate the space for the given spec.

History can grow by increasing the length for a frequency, adding a
frequency, or adding a field. It can grow with any combination of
these.

HistoryContainer now is aware of the data_frequency of the algorithm,
and no longer uses the daily_at_midnight flag; instead, this is the
default behavior.
2014-11-03 15:57:44 -05:00
Scott Sanderson affeb2afbc DEV: Add tz kwarg to get_datetime. 2014-10-23 00:59:50 -04:00
Thomas Wiecki 820115f7be MAINT: Replace iterkv with iteritems.
iterkv is being deprecated as of pandas 0.14.
2014-10-22 17:25:37 +02:00
Joe Jevnik 615228b272 ENH: Changes the default time_rule for schedule_function to market_open() 2014-10-20 17:17:34 -04:00
Brian Fink 50c5b73a7b add account object to context 2014-10-10 17:10:45 -04:00
Joe Jevnik df234f516c BUG: Fixes various bugs with the event manager:
- NotHalfDay only worked at midnight
- week_(start|end) were actually month_(start|end)
- Removes check_args from api.
- Default offset of 30mins for market_(open|close)
2014-10-09 14:01:56 -04:00
Joe Jevnik 3c37704a5b ENH: Adds a new api method schedule_function.
schedule_function takes a date rule, a time rule, and a function and
will call the function, passing context and data only when the two rules
fire. This allows for code that is conditional to the datetime of the
algo.

This is implemented internally with `Event` objects which are pairings
of `EventRule`s and callbacks.

handle_data becomes a special event with a rule that always fires. This
makes the logic for handling events more complete and compact.
2014-10-06 13:42:36 -04:00
Scott Sanderson 97e4e5e94d MAINT: In _create_generator only overwrite perf_tracker when it's None. 2014-09-29 14:40:02 -04:00
Thomas Wiecki 011f072fe2 MAINT: Add assertion for incompatible history freq specification. Supplying 1m frequency to history but only providing daily source data resulted in an odd non-descript exception. This adds a specific check and raises a more informative exception. 2014-09-17 15:04:37 +02:00
Richard Frank 3784ed4ba9 ENH: A TradingAlgorithm method called before each trading day 2014-09-03 18:07:51 -04:00
llllllllll 7563124547 ENH: Adds a new api_method called get_environment so that users may
check if their algorithm is running in zipline or on Quantopian.
2014-08-14 11:48:19 -04:00
Scott Sanderson 3e978d0ebb MAINT: Remove unused methods from TradingAlgorithm.
Removes unused method `raw_positions` and `raw_orders` from `TradingAlgorithm`.
These methods existed to help support features in the Quantopian codebase,
which no longer use the existing interface.
2014-08-13 13:00:03 -04:00
llllllllll 90405b1c99 MAINT: Adds symbol to the list of api_methods. 2014-08-06 18:18:56 -04:00
Delaney Granizo-Mackenzie 62c9b96674 Merge pull request #372 from quantopian/moved-perf-tracker-assignment
BUG: Put initialization of perf_tracker back in __init__
2014-07-21 13:48:22 -04:00
Delaney Granizo-Mackenzie 97c88c3c30 BUG: Put initialization of perf_tracker back in __init__
The initialization of perf_tracker had been moved from __init__
in TradingAlgorithm to _create_generator. This caused perf_tracker
to not be ready when portfolio requested it. portfolio was consequently
not ready for access in init. portfolio can now be accessed in init
again, assuming valid sim_params are passed. Otherwise it will be
available in handle_data() after _create_generator() is called.
2014-07-21 12:17:07 -04:00
Scott Sanderson 4712891e88 ENH: Remove dividends from the event stream.
Removes support for handling dividends as part of the algorithm
simulation stream, replacing it with an API in `TradingAlgorithm` for
supplying dividends as a DataFrame.
2014-07-18 15:04:20 -04:00
Scott Sanderson 0176279404 MAINT: Refactor AlgorithmSimulator.transform.
Breaks out the main snapshot processing loop into its own function, and does
some minor variable renaming-shuffling.

Adds `TradingAlgorithm.on_dt_changed`, a function to be called when the
simulation dt changes, prior to processing any events.

There should be no difference in behavior as a result of this change.
2014-07-18 15:04:20 -04:00
Thomas Wiecki 6de4d32ee1 ENH: Change open and close to midnight if using daily input data. 2014-07-16 15:16:57 +02:00
Eddie Hebert 4980928394 MAINT: Remove redundant perf_tracker member.
The perf_tracker member of TradingMember was set to None twice
during __init__.

Remove one of those instances.
2014-07-12 00:06:09 -04:00
Delaney Granizo-Mackenzie 9b01d78f5d ENH: Implemented AUTO_INITIALIZE feature.
Created a new flag in TradingAlgorithm that enables subclasses to
decide if they want to handle setting self.initialized = True.
Before it was the responsibility of an overriding subclass to set
initalized = True. This was causing problems because it's easy to
forget this. Now it is the responsibility of TradingAlgorithm
unless explicity stated otherwise.
2014-07-08 14:03:53 -04:00
Delaney Granizo-Mackenzie 3521a11ed4 ENH: Added informative message for calling order in init.
Previously, calling order() in initalize resulted in a weird
stack trace. It now returns a well formulated error that is
readable to the user through the API. Adding a slippage
kwarg to test_algorithm and simfactor was necessary because
slippage can only be called during init. Previously initaliazed
was never set to true and calls to init-only function were sprinkled
around the code in non-init sections. Code changes were to enforce
init-only rules.
2014-07-08 14:03:53 -04:00
Delaney Granizo-Mackenzie c3169f60cd ENH: Added dynamic name functionality to record() API function.
Added the ability to pass *args before the **kwargs so that positional
arguments of the form name, value can be recorded.
2014-06-30 14:09:09 -04:00
Thomas Wiecki f8e84ecd48 MAINT: Remove unused annualizer code. 2014-06-30 17:28:02 +02:00
Thomas Wiecki 10885e1b77 MAINT: One way to set sim_params and data_frequency.
There were sevaral places you could supply sim_params
in TradingAlgorithm (__init__, run). This got confusing
as its not clear who updated what and which one was the
correct one to use at each time.

Then there were to ways to define data_frequency, one in
__init__() and one in the sim_params which also added code
complexity.

This refactor makes it explicit that sim_params are to be
passed to __init__() only. Moreover, data_frequency is
only stored in sim_params. For backwards compatibility,
it can still be supplied separately but will link to
the one in sim_params.

For example, you could create new sim params via:

sim_params = create_simulation_parameters(data_frequency='minute')
algo = MyAlgo(sim_params)
algo.run(data)

In addition, perf_tracker only gets initialized in one place:
_create_generator() which should also make the various ways
of running an algorithm more deterministic.

This also fixes a bug with SimulationParameters where
you could not change the period_start. Unfortunately, the
current implementation still requieres an implicit call to
update the internal variables.
2014-06-30 17:28:02 +02:00
Scott Sanderson 49eaeeb6ae BUG: Apply integer truncation to order amounts earlier in the pipeline.
Truncate non-integer order amounts in `TradingAlgorithm.order` instead of
`Blotter.order`.  This fixes an issue where non-integer orders coming out of
order_value can spuriously trigger a `LongOnly` trading guard.

Example:

sid.price == 2.0
order_value(sid, 5) -> order(sid, 2.5) -> truncated to order(sid, 2.0)
order_value(sid, -5) -> order(sid, -2.5) -> LongOnlyViolation b/c 2.0 - 2.5 < 0
2014-06-09 11:42:43 -04:00
David Edwards 7547ef535a MAINT: Removed unused keyword arg
Deleted keyword arg include_open_orders, it was left over from working
on handling open orders.
2014-06-04 20:08:52 +02:00
David Edwards 243c0348f3 MAINT: Refactored target order methods
Refactored the target order methods to separate their logic from the
other order methods.

This makes order_target the only target method that calls order()
directly.

order_target_value is passed to order_target instead of order_value.

order_target_percent is passed to order_target_value rather than
order_value.

This simplified the code and decouples the logic of target orders from
the other order methods. This allows the target order methods to be
developed independently from order_value and order_percent.
2014-06-04 20:08:52 +02:00
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