Commit graph

252 commits

Author SHA1 Message Date
Andrew Liang
0955515c46 TEST: Test capital changes using target values 2016-07-25 10:05:47 -04:00
Jean Bredeche
63ef840363 ENH: Verify params passed to get_datetime 2016-07-21 20:42:28 -04:00
Jean Bredeche
5a0f840917 Clean up daily bar reader/writer to take advantage of new trading calendar. The reader
is backwards-compatible with the previous format.

In USEquityLoader, use dailyreader's trading_calendar.

This is backwards compatible and will fall back to the NYSE calendar if
the reader doesn’t have a calendar specified.
2016-07-15 15:13:57 -04:00
Jean Bredeche
6fb4923cc7 Re-implemented the Calendar API.
Instead of having separate ExchangeCalendar and TradingSchedule objects, we
now just have TradingCalendar.  The TradingCalendar keeps track of each
session (defined as a contiguous set of minutes between an open and a close).
It's also responsible for handling the grouping logic of any given minute
to its containing session, or the next/previous session if it's not a market
minute for the given calendar.
2016-07-12 13:13:50 -04:00
Eddie Hebert
4840e124af TST: Speed up TestMiscellaneousAPI
Limit the date range to one day, instead of a year.

On my local machine the following goes from taking 12 seconds to 0.6 seconds.

`$ nosetests -x tests/test_algorithm.py:TestMiscellaneousAPI`
2016-07-11 10:34:08 -04:00
Eddie Hebert
51eda06323 MAINT: Add equity to naming of bar data classes.
In preparation of adding futures, add equity to the names of both the
classes and methods for writing bcolz data. Futures data will use a
different minutes per day with a separate reader. This change will allow
both equity and futures fixtures to be side by side.

Also, break out the method which generates the dataframes and trading
days member into fixtures (`EquityMinuteBarData` and
`EquityDailyBarData`) on which the `*BarReader` fixture depends.  This
fixture is separated out to enable reader/writers in different formats
to use the same data setup. (There is internal code which needs to write
minute and daily bar data in a database format.)
2016-06-30 08:21:42 -04:00
Eddie Hebert
ca58632815 MAINT: Remove DataSource and derived classes.
The `DataSource` class and other classes derived from it are no longer
used. Instead `DataPortal` and various `MinuteBarReader` and
`DailyBarReaders` should be used.
2016-06-27 13:06:41 -04:00
Joe Jevnik
ca37d73c7b TST: fix setup in test_flip_algo 2016-06-21 15:07:03 -04:00
jfkirk
39cc355066 TST: Finishes fixing fixes for the fixed fixtures 2016-06-08 13:34:23 -04:00
jfkirk
d437a5d675 MAINT: Rebase fixes 2016-06-08 13:34:23 -04:00
jfkirk
2a8f69fc01 MAINT: DataPortal env -> asset_finder 2016-06-08 13:34:22 -04:00
jfkirk
581e817603 MAINT: Rebase reconciliation 2016-06-08 13:34:22 -04:00
jfkirk
75e0e4723d TST: Refactors more tests to use WithTradingSchedule 2016-06-08 13:34:20 -04:00
jfkirk
d9fc514fa8 TST: Adds TradingSchedule test fixture 2016-06-08 13:34:20 -04:00
jfkirk
4b7390ac81 WIP: Refactors tests to use TradingSchedule 2016-06-08 13:34:19 -04:00
jfkirk
c8304e8601 ENH: Adds ExchangeCalendar, TradingSchedule, and implementations
Conflicts:
	tests/data/test_minute_bars.py
	tests/data/test_us_equity_pricing.py
	tests/finance/test_slippage.py
	tests/pipeline/test_engine.py
	tests/pipeline/test_us_equity_pricing_loader.py
	tests/serialization_cases.py
	tests/test_algorithm.py
	tests/test_assets.py
	tests/test_bar_data.py
	tests/test_benchmark.py
	tests/test_exception_handling.py
	tests/test_fetcher.py
	tests/test_finance.py
	tests/test_history.py
	tests/test_perf_tracking.py
	tests/test_security_list.py
	tests/utils/test_events.py
	zipline/algorithm.py
	zipline/data/data_portal.py
	zipline/data/us_equity_loader.py
	zipline/errors.py
	zipline/finance/trading.py
	zipline/testing/core.py
	zipline/utils/events.py
2016-06-08 13:34:18 -04:00
Andrew Liang
1056501b27 MAINT: Support the passing of a time rule positionally on the date_rule arg
But log a warning to the user
2016-06-03 15:28:53 -04:00
Andrew Daniels
71f12ec272 MAINT: Adds first_trading_day arg to DataPortal
Instead of inferring it from the minute/daily writer, we now require the
first trading day to be passed explicitly, so the creator of the
DataPortal controls what is used as the first trading day.
2016-06-02 13:16:43 -04:00
Scott Sanderson
5caccaeed5 Merge pull request #1230 from quantopian/pipeline-example
DOC/TEST: Add example algo using Pipeline.
2016-05-25 22:35:59 -04:00
Scott Sanderson
244664b6a3 MAINT: Clean up default handling in TradingAlgorithm. 2016-05-24 22:17:01 -04:00
Andrew Liang
40f42b43f5 DEV: Adjust performance calculations for capital changes
Refactor PerformancePeriod so that it creates a sub-period every
time a capital change happens within the period
2016-05-24 17:23:36 -04:00
Jean Bredeche
39bf1dbd7b DEV: Re-implement commission models to return correct results in the case of multiple fills. 2016-05-23 21:19:06 -04:00
Joe Jevnik
d888c4faaa DOC: update docs for api functions 2016-05-06 15:25:30 -04:00
Andrew Liang
7641247b41 BUG: DAY_END action not emitted during minute emission
Refactor AlgorithmSimulator so that DAY_END is emitted for both
minute and daily emission, and that handling of end-of-minute
and end-of-day are separated
2016-05-06 10:25:44 -04:00
Joe Jevnik
efac476976 ENH: make BcolzMinuteBarWriter.write take iterable
Updates the BcolzMinuteBarWriter.write api to allow users to pass their
data as a stream instead of requiring that they loop over their data
externally. This matches the API presented by BcolzDailyBarWriter.
2016-04-29 16:14:48 -04:00
Andrew Liang
7332586abe FIX: Crashing on calculating benchmarking when no trading days
When we run a simulation that starts and ends on the same weekend,
return an empty series for the benchmark so as to not crash
2016-04-29 14:30:46 -04:00
Andrew Liang
d69b960c49 BUG: Don't save empty positions when user access non-existent position
Previously, whenever we try to access a missing value on the Positions
dict, we return a default Position and save it to the dict. Instead,
just return the Position
2016-04-26 13:28:35 -04:00
Andrew Liang
5809ae17f1 DEV: Better error message for sid= in get_open_orders
Let the user to know to use asset= instead
2016-04-26 12:23:57 -04:00
Jean Bredeche
c404c60d68 BUG: don't allow ordering in before_trading_start 2016-04-26 10:56:36 -04:00
Jean Bredeche
c323506f40 BUG: we were improperly checking iterable kwargs in BarData 2016-04-21 11:06:46 -04:00
Joe Jevnik
bc0b117dc9 MAINT: make the data loading apis more consistent.
Changes BcolzDailyBarWriter to not be an abc, data is passed as an
iterator of (sid, dataframe) pairs to the write method.

Changes the AssetsDBWriter to be a single class which accepts an engine
at construction time and has a `write` method for writing dataframes for
the various tables. We no longer support writing the various other data
types, callers should coerce their data into a dataframe themselves. See
zipline.assets.synthetic for some helpers to do this.

Adds many new fixtures and updates some existing fixtures to use the new
ones:

WithDefaultDateBounds
  A fixture that provides the suite a START_DATE and END_DATE. This is
  meant to make it easy for other fixtures to synchronize their date
  ranges without depending on eachother in strange ways. For example,
  WithBcolzMinuteBarReader and WithBcolzDailyBarReader by default should
  both have data for the same dates, so they may use depend on
  WithDefaultDates without forcing a dependency between them.

WithTmpDir, WithInstanceTmpDir
  Provides the suite or individual test case a temporary directory.

WithBcolzDailyBarReader
  Provides the suite a BcolzDailyBarReader which reads from bcolz data
  written to a temporary directory. The data will be read from
  dataframes and then converted to bcolz files with
  BcolzDailyBarWriter.write

WithBcolzDailyBarReaderFromCSVs
  Provides the suite a BcolzDailyBarReader which reads from bcolz data
  written to a temporary directory. The data will be read from a
  collection of CSV files and then converted into the bcolz data through
  BcolzDailyBarWriter.write_csvs

WithBcolzMinuteBarReader
  Provides the suite a BcolzMinuteBarReader which reads from bcolz data
  written to a temporary directory. The data will be read from
  dataframes and then converted to bcolz files with
  BcolzMinuteBarWriter.write

WithAdjustmentReader
  Provides the suite a SQLiteAdjustmentReader which reads from an in
  memory sqlite database. The data will be read from dataframes and then
  converted into sqlite with SQLiteAdjustmentWriter.write

WithDataPortal
  Provides each test case a DataPortal object with data from temporary
  resources.
2016-04-15 23:46:10 -04:00
Jean Bredeche
63bd7589b7 BUG: support passing an empty list to data methods.
Our type checking code was a bit too aggressive.
2016-04-14 11:11:08 -04:00
Andrew Liang
8dc3ed73ab FIX: Check types of args passed to api methods on data 2016-04-13 09:47:07 -04:00
Jean Bredeche
fac5905c10 Merge pull request #1114 from quantopian/handle-data-optional
ENH: make handle_data optional
2016-04-13 09:31:41 -04:00
Richard Frank
8b610a2ab7 TST: Cleaned up test references to adjustments db
If we don't clean them up, then windows can delete
the temp dir with the db.
2016-04-12 19:33:22 -04:00
Richard Frank
32a400a9fb BUG: Fixing bitness issues on 32-bit systems
by being explicit with sizes
2016-04-12 17:07:50 -04:00
Jean Bredeche
bd5e2b183d BUG: Properly log partially filled sell orders. 2016-04-12 13:57:50 -04:00
Jean Bredeche
4203c54417 ENH: make handle_data optional 2016-04-07 09:50:09 -04:00
Jean Bredeche
dc01c45dc4 DEV: Apply adjustments for portfolio and account in BTS
completely copied from https://github.com/quantopian/zipline/pull/1104/

All credit goes to Andrew Liang (@lianga888)
2016-04-05 11:37:34 -04:00
Eddie Hebert
16fd6681a6 ENH: Rewrite of Zipline to use lazy access pattern
More documentation to follow in release notes.

Based on lazy-mainline branch, see for more details.

Also-By: Jean Bredeche <jean@quantopian.com>
Also-By: Andrew Liang <aliang@quantopian.com>
Also-By: Abhijeet Kalyan <akalyan@quantopian.com>
2016-04-04 16:12:58 -04:00
Joe Jevnik
721dd36116 TST: move test_utils and adds test fixture classes
Renames zipline.utils.test_utils to zipline.testing

Adds zipline.testing.fixtures.ZiplineTestCase to manage setup and
teardown and adds mixins to define fixtures like an asset finder or
trading calendar.
2016-03-10 15:39:52 -05:00
dmichalowicz
5be63f36d5 ENH: Add auto_close_date support for equities 2016-02-22 13:51:20 -05:00
jfkirk
db1e62971a ENH: Adds tick_size and renames futures multiplier 2016-01-22 14:56:30 -05:00
Joe Jevnik
3b76981270 Merge pull request #846 from grundgruen/data_test
TST: tests removing of expired data and removes ffill in DataPanelSource
2016-01-19 13:05:15 -05:00
warren-oneill
ef323a3165 ENH: adds lookup_expired_futures to asset_finder 2015-12-01 15:24:02 +01:00
jfkirk
bbe3ab99ac TST: Adds asset type verification to test_order tests 2015-11-30 12:25:04 -05:00
warren-oneill
987d6d4e48 TST: tests removing of expired data and removes ffill in DataPanelSource 2015-11-17 17:22:31 +01:00
jfkirk
11b7cd2dd0 TST: Fixes test_order_methods_for_future 2015-11-16 11:47:00 -05:00
llllllllll
0cb4c38717 ENH: Allow users to pass a context manager to wrap all scheduled
functions.

This includes handle_data.
2015-11-11 14:19:13 -05:00
Scott Sanderson
a14c61e7ff MAINT: Remove unused 'asset_type' metadata entry. 2015-11-05 13:35:05 -05:00
Richard Frank
ec5318ec88 TST: Fixed up test result comparison 2015-11-05 10:18:57 -05:00
Richard Frank
d2ba11dac0 STY: Fixed typo and appeased flake8 2015-11-05 10:18:57 -05:00
Richard Frank
6b245ab06a TST: Removed extra parameters 2015-11-05 10:18:57 -05:00
puppy
a82415c77b BUG: Address issue #801 and add test. Pass panel directly to
object instead of data.
2015-11-05 10:18:57 -05:00
jfkirk
7d29bb6a67 BUG: Fixes failure to account for Futures transaction prices 2015-10-30 12:04:38 -04:00
warren-oneill
3f66e6c66a TST: adds future flip test 2015-10-30 10:07:46 -04:00
Stewart Douglas
4e2039c9b0 ENH: Coerce user input with API method decorator
Previously we have capitalized input strings at different levels in
our code: in the user-facing API methods and in the asset finder.
This commit moves input string capitalization exclusively to the API
method to which the string was supplied. Specifically, the string is
capitalized by a preprocess API method decorator. The preprocess
decorator passes the input string to the newly defined
ensure_upper_case() method, which returns a TypeError if the argument
supplied is not a string.

ensure_upper_case() is defined in a new file, zipline/utils/input_validation.py.
The existing expect_types() method is also moved there.

Various tests in tests/test_assets.py are modified to account for the
fact that the asset finder method lookup_symol() no longer capitalizes
its supplied argument.
2015-10-08 15:41:33 -04:00
Stewart Douglas
3ef0ddf0c6 ENH: Add future_symbol API method 2015-10-05 11:19:04 -04:00
Eddie Hebert
cbb3d807b7 TST: Remove instant fill from close position test.
'instant fill' execution may be on the path to deprecation, (the removal
is currently proposed by the branch which removes events in favor of
operating over dts.), so remove instant_fill from the close position
tests so that the input and output is the same between the proposed
branch and here.

(This was one of the few places where instant fill was used that
was not testing instant fill behavior explicitly, so may be better to
align this test with the rest of the suite.)

Also, change test methods to make it more clear on which day the values
the expected and actual results differed.
2015-09-28 14:48:19 -04:00
Richard Frank
136eb8aa0d BUG: Running an algo with a df/panel of Assets was raising SidNotFound 2015-09-24 21:49:45 -04:00
Richard Frank
0b6b11a080 MAINT: Removed some unnecessary instance attributes 2015-09-24 21:49:45 -04:00
John Ricklefs
38ff4cc913 BUG: Normalize dates in AssetDateBounds control checks
Assumes that if a given asset's end_date is
e.g. 9/17/2015 00:00:00 UTC that it means the
asset is still tradeable on 9/17/2015 during
the market day.
2015-09-18 15:19:15 -04:00
jfkirk
d84bdefef8 MAINT: Removes lookup_symbol_resolve_multiple method
lookup_symbol_resolve_multiple was identical to lookup_symbol, except that lookup_symbol performed upper-casing of the input string and lookup_symbol would return Nones. Now, lookup_symbol has a kwarg 'default_None=True' and all symbols are upper-cased on insertion and request.
2015-09-16 09:54:37 -04:00
jfkirk
a6ce1e5e8d ENH: Adds auto_close_date field to Future objects 2015-09-11 14:08:03 -04:00
jfkirk
6e6ef447d2 TST: Adds tearDownClass methods to delete TradingEnvironments 2015-09-10 11:53:29 -04:00
jfkirk
608dff245b TST: Updates test for set_symbol_lookup_date 2015-09-10 11:53:29 -04:00
jfkirk
dc964a7e7d MAINT: Removes the ability to reference a global TradingEnvironment
This commit removes the ability to reference a shared TradingEnvironment through the zipline.finance.trading module. In place, the classes that require a TradingEnvironment, or its child AssetFinder, contain their own references to those objects.

This commit also adds serialization utilities that allow for the pickling/unpickling of objects without unintentionally their TradingEnvironments or AssetFinders.
2015-09-10 11:53:28 -04:00
Stewart Douglas
d3516959a3 MAINT: Don't set string to upper before writing, remove unused libs 2015-09-10 11:53:27 -04:00
Stewart Douglas
7be2cf8652 MAINT: Allow algo.run() to write to db 2015-09-10 11:53:27 -04:00
Stewart Douglas
1ef2274d11 MAINT: Update tests to conform to new reader/writer structure 2015-09-10 11:53:26 -04:00
Stewart Douglas
1c512c5478 TST: Update test_algorithm.py to incorporate TradingEnvironment.write_data 2015-09-10 11:53:25 -04:00
Stewart Douglas
e507ee097d TST: Add coverage for set_symbol_lookup_date method 2015-09-08 11:01:04 -04:00
jfkirk
cf41373f8f BUG: Symbol look-up now uses the sim_params.period_end as a look-up date 2015-09-01 12:39:03 -04:00
Jonathan Kamens
2521263c06 TST: Prevent some test cases from being split 2015-08-25 11:56:36 -04:00
jfkirk
67c56f768b ENH: Adds auto-closing feature and implements for Futures 2015-07-31 10:38:44 -04:00
Scott Sanderson
f13e9fd125 TEST: Add test asserting dynamic api_methods. 2015-07-29 12:30:46 -04:00
Scott Sanderson
ef4f642e62 ENH: Compute engine architecture for FFC API.
This patch lays the groundwork for a compute engine designed to
facilitate construction of factor-based universe screening and portfolio
allocation.  It contains:

A new module, `zipline.modelling`, containing entities that can be used
to express computations as dependency graphs.  Each node in such a graph
is an instance of the base `Term` class, defined in
`zipline.modelling.term`.  Dependency graphs are executed by instances
of `FFCEngine`, defined in `zipline.modelling.engine`.

A new module, `zipline.data.ffc`, containing loaders and dataset
definitions for inputs to the modelling API.

New `TradingAlgorithm` api methods: `add_factor`, and `add_filter`.
These methods can only be called from `initialize`, and are used to
inform the algorithm that each day it should compute the given terms.
Computed factor results are made available through a new attribute of
the `data` object in `before_trading_start` and `handle_data`.  Computed
filter results control which assets are available in the factor matrix
on each day.
2015-07-29 12:30:46 -04:00
Eddie Hebert
36319122cc PERF: Change asset finder to be backed by sqlite3.
Attack the startup bottleneck of creating the asset finders caches for a
large universe, which was between 1-2 seconds on development and
production machines.

Instead, allow the AssetFinder to be passed a sqlite3 file that has
already been populated and then hydrate asset objects only when an
equity is referenced for the first time.

To create aforementioned sqlite3, create an AssetFinder with an db_path
and `create_table` set to True. If `create_table` is set to False, the
prepopulated data in the sqlite file found at db_path will be used.

Default behavior is to use an in memory database.

Behavior that changes:

- Fuzzy lookup now only works on one character, that character needs to be
specified at write/metadata consumption time, since the fuzzy lookup key
is created by dropping the character from each symbol.

- Overwriting partially written metadata is no longer
  supported. i.e. some unit tests allowed for inserting just the identifier,
  and then later updating the symbol, end_date, etc.

  Instead of building an upsert behavior at this time, this patch
  changes the unit tests so that the data for each asset is only
  inserted once.

Other notes:

- populate_cache is now removed, since there is no longer a two step
  process of inserting metadata and then realizing that metadata into
  assets. _spawn_asset is rolled into insert_metadata, so that a call to
  insert_metadata both converts the metadata and makes it available in
  the data store.
2015-07-14 09:54:38 -04:00
Andrew Daniels
2ab9f8a63c ENH: Futures API 2015-07-13 09:50:36 -04:00
Eddie Hebert
ad4126bf58 STY: Remove unused import.
Mea culpa.
2015-07-10 17:03:44 -04:00
Eddie Hebert
2616a12551 TST: Remove test for lookup of future contract by symbol.
The lookup of future contract by individual symbol is a constraint on
incoming changes of changing how the asset finder stores data.

(i.e. the asset finder is changing so that there are separate tables for
both futures and equities.)

Since this lookup is not yet fully supported, we can add it back in on
top of the new asset finder.
2015-07-10 14:59:33 -04:00
Eddie Hebert
9688989eba MAINT: Use symbol lookup directly from algorithm.
Instead of using the generic lookup, use the asset finder symbol method
directly when `symbol` is used in an algorithm.
2015-07-08 14:41:02 -04:00
jfkirk
a4ce9712b8 DEP: Removes sids field from SimulationParameters 2015-07-01 13:43:31 -04:00
jfkirk
eced4e700d TST: Adds close position tests for both Equity and Future 2015-06-12 10:07:50 -04:00
jfkirk
3ee3a1226b BUG: Fixes handling of CLOSE_POSITION events for Futures 2015-06-11 11:40:54 -04:00
warren-oneill
0d7e23857e TST: add unittest for CLOSE_POSTION event type for futures, add commission to TestAlgorithm 2015-06-11 11:39:10 -04:00
jfkirk
a5d1f79a37 TST: Reconciles tests with asset management system 2015-06-11 11:35:49 -04:00
jfkirk
9da644f767 ENH: Moves calling of TradingAlgorithm.initialize to _create_generator 2015-06-11 10:14:07 -04:00
warren-oneill
3d18a2954f TST:adds algo unittest for ClOSE_POSITON event type, adds commission as parameter to TestAlgorithm 2015-06-11 10:11:01 -04:00
jfkirk
9996502573 DEP: Removes use of 'count'-defined test sources
Test sources are now defined by the sim_params period_start and period_end, rather than by the period_start and a defined 'count' of bars. This allows us to consider the sim_params.period_end as the canonical definition of the end of a simulation.
2015-05-28 12:29:33 -04:00
Jonathan Kamens
fd0530d889 MAINT: Flake8 2015-05-01 11:03:01 -04:00
Jonathan Kamens
557e6a3009 Every setup_logger needs a teardown_logger 2015-05-01 07:38:42 -04:00
Jonathan Kamens
5c546b4f6c TST: overwrite_sim_params=False in tests when using list of sources
When specifying a list of sources to algorithm.py:run in a unit test,
specify overwrite_sim_params=False to suppress the unnessary
UserWarning.
2015-04-30 15:30:19 -04:00
Brian Fink
8baf52fe01 ENH: Add max leverage account guard 2015-04-10 15:19:54 -04:00
Eddie Hebert
314b22656f MAINT: Remove left over simple transform code.
Remove pieces that are no longer used now that the simple transforms are
wrappers around history via the SIDData object.

Move window length related pieces into batch_transform, since the rest
of the utils module is no longer used.
2015-03-30 14:18:39 -04:00
Jonathan Kamens
e942275108 STY: Flake8
Upgrade the version of the flake8, pep8, and mccabe PyPI packages, and
make the code changes necessary for compatibility with the updated
packages.
2015-03-19 17:21:25 -04:00
Thomas Wiecki
760bbced73 Revert "ENH Allow order_percent to work with various market values"
This reverts commit dd37a49f2f as it lead to different algo behavior we have to investigate first.
2015-02-17 20:27:59 +01:00
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
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
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
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
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
Scott Sanderson
affeb2afbc DEV: Add tz kwarg to get_datetime. 2014-10-23 00:59:50 -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
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
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
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
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
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
Scott Sanderson
e3faf10dee MAINT: Add tests for UnsupportedOrderParameters.
Add a test case in test_algorithms to verify that appropriate exceptions are
thrown if an algorithm makes a call to the order api with a stop/limit price
and a style.
2014-04-22 23:22:21 -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
574415f434 MAINT: Adding tests for Blotter handling of limit and stop orders.
Adds a test algorithm that tries to buy with very high limit prices/very low
stop prices and tries to sell with very low limit prices/very high stop prices.
2014-04-21 16:34:59 -04:00
Scott Sanderson
6412742799 MAINT: Clean up unused data in test. 2014-04-21 16:32:54 -04:00
twiecki
e261438d01 ENH: Adapt history() to work on zipline. 2014-04-10 15:59:26 -04:00
twiecki
3eb810ad97 ENH: Add simulated random trade source.
This adds a new data source that emits events
with certain user-specified frequency (minute
or daily).

This allows users to backtest and debug an
algorithm in minute mode to provide a cleaner
path towards Quantopian.
2014-03-22 21:22:22 -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
twiecki
eccaf8d53d ENH: Add symbol api function
A symbol() lookup feature was added to Quantopian.
By adding the same API function to zipline we can
make copy&pasting of a zipline algo to Quantopian
easier.
2014-03-05 17:15:44 -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
51e8b3244e ENH: Filter out empty positions from portfolio container.
To help prevent algorithms from operating on positions that are
not in the existing universe of stocks.

Formerly, iterating over positions would return positions for stocks
which had zero shares held. (Where an explicit check in algorithm
code for `pos.amount != 0` could prevent from using a non-existent
position.)
2014-01-10 14:30:29 -05:00
Thomas Wiecki
65637b9430 ENH: Add option of instantly filling orders. 2013-10-01 20:30:01 -04:00
Thomas Wiecki
b1fdebfb7c TST: Added tests for new order methods. 2013-08-08 15:55:08 -04:00
Thomas Wiecki
940ddd22d3 TST: Added testing of order timings and price. 2013-07-17 19:56:55 -04:00
Eddie Hebert
c6cbc9f8e2 TST: Explicitly define the data frequency of record incr test. 2013-04-25 01:12:58 -04:00
Eddie Hebert
ccc6cd892b BUG: Ensure algorithm tests use test simulation parameters.
To pass sim_params to TradingAlgorithm using kwargs is required.
When just passing sim_params as an arg, it was ignored.
2013-04-09 16:47:25 -04:00
Eddie Hebert
8997b4f68c MAINT: Remove parameters from test that tests lack of parameters.
The `test_multi_source_as_input_no_start_end` test is designed
to test for a lack of simulation parameters, so make that they are
not passed.

Was unnoticed because sim_params passed as an arg are dropped.
2013-04-09 16:46:55 -04:00
Eddie Hebert
57db5bc17c BUG: Fix start and end dates of simulation parameters used in tests.
The start and end of the simulation parameters should be 'normalized'
i.e. midnight timestamped.
However, the algorithm tests were using the timestamp of the
first and last trade, which were in market times,
i.e. 9:30 AM and 4:00 PM EST.

Fix passing the sim_params that is used to create the trade_history,
instead of having the sim_params inferred from the source.

(Also may want to consider fixing the logic that infers the date
range from the sources provided.)

Also, add a `num_days` option to `factory.create_simulation_parameters`
so that the a date range that covers the desired number of days is covered.
Since the default sim_params were covering a year, while the test only
supplies 4 values, causing an alignment issue with the record test,
since a years worth of results were returned, but there were only 4 events.
2013-04-09 15:11:43 -04:00
Eddie Hebert
58af62f18d REL: Update copyright on all files touched since end of 2012.
s/Copyright 2012/Copyright 2013/
2013-04-05 14:28:15 -04:00
fawce
1a85781170 updated run method to use sim_params. 2013-02-18 10:24:32 -05:00
fawce
2c7355a0dc Refactoring of TradingEnvironment to isolate the global state: index symbol and exchange timezone. Parameters that define the simulation (start, end, and capital base) were put in a new class, SimulationParameters.
Global state for the financial simulation environment is accessed through the
zipline.finance.trading module, which now contains a module variable:
environment.

Parameters are passed into an algorithm as a keyword argument, sim_params.
SimulationParameters creates a trading day index for the test period that
can be used to find trading days, calculate distance between trading days,
and other common operations. The sim params index is just selected from the
global state.

================

Details:

    - adding delorean to the requirements.
    - made index symbol a parameter for loading the benchmark data. changed
    messagepack storage to be symbol specific.
    - ported risk, performance, algorithm, transforms, batch transforms
    and associated tests to use simulation parameters and global environment
    - factory and sim factory use global state and sim params
    - factory method parameter names now reflect the class expected
2013-02-18 10:24:32 -05:00
Eddie Hebert
81337d1306 Adds the ability to record variables.
Takes the value set for a variable on handle_data and records it,
e.g.:
```
    def initialize(self):
        self.incr = 0
        self.record_variables(['incr'])

    def handle_data(self, data):
        self.incr += 1
```

Would record a variable of `incr`.

Emits the recorded variables as part of the daily performance.

This batch combins work from:
Thomas Wiecki <thomas.wiecki@gmail.com> (@twiecki)
fawce <fawce@quantopian.com> (@fawce)
2013-01-31 08:16:54 -05:00
Thomas Wiecki
4615b29713 REF: Renamed granularity to data_frequency. 2012-12-30 11:50:46 -05:00
Thomas Wiecki
8346155f0e MIN: Override annualizer if set. New handling of granularity (no default arg anymore). Renamed minutely to minute. 2012-12-24 12:55:52 -05:00
Thomas Wiecki
daf29c2d39 ENH: Add granularity and annualizer arguments to TradingAlgorithm. Accompanying doc string and unittest. 2012-12-20 12:49:24 -05:00
Thomas Wiecki
775c564ea1 ENH: Added DataPanelSource. 2012-12-13 12:55:05 -05:00
Richard Frank
095f2dd65b Date bookkeeping fixes in perf and risk
Issues appeared when we were close to the end of our
historical data.

Yielding DONE event with both perf and risk messages now
2012-12-12 15:23:26 -05:00
Eddie Hebert
ab6b754922 Changes EventWindow parameter of days to window length.
The days parameter was causing confusion when explaining the
usage of the batch_transform decorator.
2012-11-20 11:52:27 -05:00
Tobias Brandt
cf4d7ca353 Fixed unittest2 import error on Python 2.7
Changed all unittest2 imports to unittest
2012-11-12 10:49:14 -05:00
Thomas Wiecki
15ac658024 Restructured file hierarchy. Transforms now live in transforms (transform.py is now transforms/utils.py). Sources are in sources.py. VWAP is now MovingVWAP. 2012-10-19 18:10:51 -04:00
Thomas Wiecki
92f1dbef0c Fixes bug that .run() could not be called twice on an algorithm. Added unittest to check. 2012-10-19 11:47:59 -05:00
fawce
16b0d71506 refactoring of algorithm to make it work for both batch style run method, and generator style consumption. removed the portfolio property from the data parameter. added set_slippage and set_commission methods to algorithm. removed timeout tracking. 2012-10-10 16:06:32 -04:00
Eddie Hebert
bbf2317c57 Saving point for adding license files. 2012-10-08 17:32:40 -04:00