Commit Graph

513 Commits

Author SHA1 Message Date
Jeremiah Lowin dd37a49f2f ENH Allow order_percent to work with various market values
Currently, `order_percent()` and `order_target_percent()` both operate as a percentage of `self.portfolio.portfolio_value`. This PR lets them operate as percentages of other important MVs.

(also adds `context.get_market_value()`, which enables this functionality)

For example:
```python
order_percent('AAPL', 0.5)

order_percent('AAPL', 0.5, percent_of='cash')

order_target_percent('MSFT', 0.1, percent_of='shorts')

tech_stocks = ('AAPL', 'MSFT', 'GOOGL')
tech_filter = lambda p: p.sid in tech_stocks
for stock in tech_stocks:
    order_target_percent(stock, 1/3, percent_of_fn=tech_filter)
```
2015-02-12 14:15:20 +01:00
Dale Jung 38e8d5214d PERF: History Perf Enhancements
Limited use of `pandas` data structures in both `HistoryContainer` and
`RollingPanel`. Where possible, methods were amended to return raw
`ndarrays` with the indexing logic done separately. This allows us to
cut down the number of times pandas objects are created both as returns
and intermediate values. The separation of indexing from data access
allowed us to minimize the times we’d make use of pandas indexes.

This required that that certain methods like `NDFrame.ffill` be replaced
with versions that work with `ndarrays`. Some of this was done via
straight numpy methods and others by access pandas internal
machinery. Outside of allowing us to use faster ndarrays, many of these
function provided speedups over their pandas counterparts as we didn’t
require the extra features like handling multiple dtypes. i.e. np.isnan
is faster than pd.isnull, but only works with certain dtypes.
2015-02-11 06:25:53 -05:00
fawce 412baa3c3f fixed catastrophic bug in load_from_directory
and added a new test case
was not iterating over lookup date directory names, and
therefore mising all by one list of stocks.
discovered because of differing sort orders between
my local machine, other devs, and travis ci.
2015-02-05 13:57:41 -05:00
fawce 08a0d1b604 python 3.3 compatible iterators 2015-02-05 13:57:40 -05:00
fawce 1ab082102a first edition of leveraged etf list 2015-02-05 13:57:28 -05:00
fawce 536ace94b8 new security list class
and tests
2015-02-05 13:57:27 -05:00
fawce 909b412e9b modified do not order guard to take an iteratble or a container
container allows for dynamic restrictions, necessary for a
point in time implementation of the restricted list.
2015-02-05 13:56:46 -05:00
fawce 52f78fcbc7 restricted list trading control added. 2015-02-05 13:56:45 -05:00
fawce 6c3e1e1ba4 added tests for performance pack fields 2015-01-07 21:47:13 -05:00
fawce 22cb6dcb40 added leverage and gross leverage to account.
added tests and conditions for account values.
2014-12-18 17:07:19 -05:00
fawce 34647ec6c4 added tests to confirm the full environment returns as expected. 2014-12-08 16:47:11 -05:00
fawce 0411627169 Modified get_environment to provide multiple fields. 2014-12-07 08:26:13 -05:00
Joe Jevnik e7a5e097c4 BUG: Explicitly guard against empty bar data in history container
contstruction.

BarData can be falsey. in create_buffer_panel, the intention of the
check against bar_data was to see if it was passed at all, not if it was
truthey. In order to make that check more explicit, the check now
asserts that bar_data is not None.
2014-11-19 11:55:13 -05:00
Joe Jevnik fcea785b01 MAINT: Makes RandomWalkSource emit midnight UTC events in daily mode. 2014-11-19 11:55:13 -05:00
Joe Jevnik f7b4d3100d ENH: Makes the offset of market_close relative to 20:00 UTC
Changed from relative to 20:01 UTC.
2014-11-19 11:38:26 -05:00
Joe Jevnik 68e44353ce MAINT: Make RandomWalkSource accept the standard daily instead of day for the frequency 2014-11-18 15:23:10 -05:00
Joe Jevnik e3d8b1034e ENH: Replaces the simple transforms with history calls. Switches
transforms to quantopian syntax.

Adds the sid attribute to the siddata so it is aware of which security
it represents.
2014-11-17 13:16:30 -05:00
Joe Jevnik c2aae2e0f4 BUG: rolling panel data became misaligned after extend_back 2014-11-12 16:47:44 -05:00
Joe Jevnik 8df1a49031 BUG: When increasing the length dynamically, the rolling panel was
getting filled with the wrong datetimes and causing errors.

Updates the logic for addressing missing datetimes and adds unit tests
for the 2 main cases (no missing datetimes, and some missing datetimes).
2014-11-11 13:29:57 -05:00
Joe Jevnik ca59abcc43 ENH: Makes schedule_function work in daily mode. 2014-11-06 10:49:49 -05:00
Joe Jevnik 93429d69f5 BUG: HistoryContainer creation at runtime did not work as intended. 2014-11-05 18:31:11 -05:00
llllllllll 9ddb033e67 ENH: Changes the default offset for time_rules.market_open to 1, and
makes it an offset from 13:30 UTC.

This is to be more consistent with the market_close, which is an offset
from 20:00 UTC.

This also makes market_open and market_close cache the dt to offset from
for each day.
2014-11-05 14:59:48 -05:00
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 c6e85d08f0 ENH: Does value checking for time offsets for market_open and market_close 2014-10-20 17:17:34 -04:00
Joe Jevnik 69124cb6ab BUG: Fixed a bug with offsets in week_start and week_end 2014-10-20 17:17:34 -04:00
Joe Jevnik d360b9d9bd ENH: Provides a more descriptive error if market_open or market_close are provided a non-keyword argument that is not a datetime.timedelta 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 490391b9ae TEST: Remove uncessary copy calls from history tests. 2014-10-03 06:07:02 -04:00
Scott Sanderson 235954d480 DEV: Overhaul core history logic.
Overhaul the core HistoryContainer logic to be more robust to changing
universes.

Major Changes
-------------
* Remove `return_frame` cache.  The original purpose of using
  return_frames was to avoid having to create new DataFrames on each
  iteration of handle_data, but we ended up having to copy the return
  frames anyway because user code could mutate the frames in place.
  Removing the return_frames reduces unnecessary copying, and reduces
  the logic of `get_history` to just forward-filling and concatenating
  two DataFrames.

* Use a `MultiIndex`ed DataFrame to represent
  `last_known_prior_values`.  This makes lookups faster and greatly
  simplifies the logic of adding and dropping sids.

* HistoryContainer no longer attempts to determine its universe based on
  the contents of its internal buffers.  The TradingAlgorithm
  controlling the container is now responsible for explicitly calling
  `add_sids` or `drop_sids` when securities enter or leave the
  algorithm's universe.  These methods, along with the internal
  `_realign` method, provide a clean interface for changing the universe
  of securities managed by the container.

* Refactor index mutation logic in `RollingPanel` into a
  `MutableIndexRollingPanel` subclass.  Maintenance of the old behavior
  is regrettably necessary to support `BatchTransform`.

* Refactor shared logic from `roll` and `get_history` into a single
  `aggregate_ohlcv_panel` method that's responsible for collapsing an
  OHLCV buffer into a frame.
2014-09-29 14:42:57 -04:00
Scott Sanderson b3c7c26cee MAINT: Remove unused function in test_rolling_panel.py. 2014-09-29 14:40:03 -04:00
Joe Jevnik 4db4256cfe MAINT: Adds a tests/utils/ directory and renames test_utils.py
to utils/test_factory.py
2014-09-29 12:57:39 -04:00
Thomas Wiecki 4615b57fc2 MAINT: Add custom exception for incompatible history frequency specification. 2014-09-18 16:20:28 +02:00
Thomas Wiecki cbb8e28f8e TST: Fix history unittest. 2014-09-17 18:17:36 +02: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
Eddie Hebert 7eb1d719ed MAINT: Check attributes instead of contains for event fields.
In support of source that emits a subclass of Event which defines some
fields as properties instead of doubling the value in the
`Event.__dict__`

Use hasattr instead of the overridden __contains__ method of the Event
class, so that when non-algorithm facing code checks for field existence,
properties count.

Intentionally not touching the `__contains__` in Event, to avoid
changing, at the moment, any algo behavior that relies on the
`__contains__` behavior's use of `__dict__`
2014-09-08 11:09:41 -04:00
Richard Frank 3784ed4ba9 ENH: A TradingAlgorithm method called before each trading day 2014-09-03 18:07:51 -04:00
Delaney Granizo-Mackenzie 5488da0dc2 ENH: Well formed exception for any value passed to OrderStyle
This commit adds support for arbitrary objects in addition to NaN
and infinity values. The object well be returned in string format
as part of the error message.
2014-08-26 14:02:28 -04:00
Delaney Granizo-Mackenzie 15f33d3e9d BUG: Exception will be raised when nan value sent to order()
Previously order was not checking for nan values sent as
limit or stop prices. It will now raise a runtime exception
in the event that an attempt to order with a nan price is made.
2014-08-25 11:23:28 -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 d02dd972d5 BUG: Fix crash in transforms on malformed CUSTOM events.
Fixes a crash in various transforms when providing CUSTOM events whose fields
don't match the fields required for the transform.

This is fixed by requiring all `EventWindow` subclasses to supply a `fields`
property, which returns a list of strings that are required keys for any event
that can be processed by the window.  Any CUSTOM events the don't supply the
required fields for a transform window are ignored by that window.
2014-08-13 12:54:29 -04:00
John Ricklefs dd97292a94 TST: Add tests for behavior of rejected/held orders.
Also made a tweak to the handling of Order.status
for when a held order is filled (partial or full).
2014-08-06 15:00:26 -04:00
Thomas Wiecki e9b7209c13 MAINT: Factor talib tests out to separate file. 2014-08-04 13:17:21 +02:00
Delaney Granizo-Mackenzie 0fd78cd54a BUG: Fixed random dips in returns as shown to user.
Previously the last sale price was not correctly being set on
positions when the transaction arrived before the trade event.
The last sale price was defaulted to zero and never updated. This resulted
in one holding stocks that were bough >>0 and now had value 0 from
the perspective of returns. The returns would display correctly again
when the next trade of that security happened. For most securities trading is
frequent enough that there's no issue, but for some illiquid ones it took
hours to fix itself.

Updated test_perf_tracking:TestPerformanceTracker.test_minute_tracker
This test was based on assuming that last_sale_price was zero,
allowing the sharpe ratio to be calculated. The sharpe ratio can no longer
be calculated for this specific tested scenario and the test has been changed
accordingly.
2014-07-29 11:07:13 -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 1039919340 STY: In test_perf_tracking, import datetime/timedelta via from-import. 2014-07-18 15:04:20 -04:00