Commit Graph

90 Commits

Author SHA1 Message Date
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
Scott Sanderson 1039919340 STY: In test_perf_tracking, import datetime/timedelta via from-import. 2014-07-18 15:04:20 -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 a8431944aa MAINT: Add comments and rename methods in PerformanceTracker.
The function that handles a market close for daily frequency changed from
`handle_market_close` to `handle_market_close_daily`.

The function that is called at on the closing minute each day when running
minutely changed from `handle_intraday_close` to
`handle_intraday_market_close`.
2014-07-18 15:04:20 -04:00
Eddie Hebert 2debde31ba BLD/STY: Upgrade to latest versions of lint checkers.
Upgrade pep8 1.4.6 -> 1.5.7
Upgrade pyflakes 0.7.3 -> 0.8.1

Also, tweak some line indentations which now show up as errors,
because of the fixes/changes to visual indent detection between
pep8 versions.
2014-05-30 12:44:10 -04:00
Richard Frank f21bbe58fc ENH: Allow for stock dividends, and in particular, Google's
recent 2 for 1 stock split, where 1 class C share was distributed
for each share of class A held.

Now a dividend can specify a sid and ratio of stock that will be paid
to owners of the original security.  If the ratio is 2.0, then for every
existing share, two shares will be paid.
2014-04-24 14:00:39 -04:00
twiecki 7517032e8d STY: More pep8 fixes. 2014-04-10 13:01:44 -04:00
twiecki 5cb2919b10 STY: pep8 fixes. 2014-04-10 10:57:12 -04:00
Richard Frank 54ad18e2ff MAINT: Simplified event stream creation for tests 2014-03-11 19:08:22 -04:00
Richard Frank 7a3f73cf1d BUG: Update perf period state when positions are changed by splits
Otherwise, self._position_amounts will be out of sync with position.amount, etc.
That value is used to calculate pnl and returns, so test for them.
2014-03-11 19:08:22 -04:00
Richard Frank 5020c36f8d BUG: Fix cost basis calculation
Cost basis calculation now takes direction of txn into account.

Closing a long position or covering a short shouldn't affect the cost basis.
2014-03-05 14:48:58 -05:00
Richard Frank e459c2729c MAINT: Refactored unit tests to remove duplication
of arguments to factory.create methods.

Also added checking of the perf period cost basis results after each txn.
2014-03-05 14:48:42 -05:00
Colin Alexander 011ed09dc2 ENH: Extended commission PerShare method to allow a minimum cost per trade.
Also added unit tests (test_perf_tracking.TestCommissionEvents) to test
all commission models.
2014-02-25 14:37:08 -05:00
Eddie Hebert 7274748275 STY: Remove unused import.
Remove unused heapq from test perf tracking.

Mea culpa.
2014-01-07 16:42:21 -05:00
Eddie Hebert f093b2fb59 MAINT: Adjust for comparison changes in Python 3.
Use date sorted sources instead, instead of sorting with second
argument of Event, etc. since the `heapq.merge` behavior is using
the second part of the tuple, thus requiring a richer set of comparison
methods, which would only be used in the test context.

Use `date_sorted_sources` instead, so that sorting is done on algo time
and source id.
2014-01-07 11:57:52 -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
Eddie Hebert 54ddd1c109 MAINT: print function clean up in preparation for Python 3
- Use `print()` function for all print calls
- Fix strip and format calls that were on the outside of the
  print function for some reason.
  (Which were breaking in Python 3 because of print returning None.)
- Remove commented out print calls.
2014-01-04 20:55:43 -05:00
Eddie Hebert 6f3a3dab04 TST: Defend against non-trading days as period start in commission test.
A bug in the create_random_simulation_parameters allows the period
start to be a non-trading day.

That bug was causing the commission tests to randomly fail, e.g.
when the period start was on Good Friday, because the commission was
created on hour three of Good Friday, instead of the next Monday.
When it hit that case, the test commission is never processed.

Defend against that bug by using the first open of the simulation
parameters which is more guaranteed to be during market hours,
when creating the test commission.

This is in place of fixing the bug in the random parameters function
or making the parameters non-random, which are other potential fixes.
2013-12-10 13:07:25 -05:00
Richard Frank 2492feb938 ENH: Keep track of total commissions as attribute on Order
Value is summed from TRANSACTION and COMMISSION events.
Defaults to None, meaning unset.
2013-11-01 17:23:50 -04:00
Eddie Hebert a192ba01a2 STY: Used named args in hardcoded test objects.
Instead of unrolling a dictionary, use named args.
2013-11-01 15:28:35 -04: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
Eddie Hebert 37e1e74391 TST: Add logging of sim params for perf tracker tests.
These tests use the random simulation parameters, which is leading
to an intermittent failure.

We may want to consider removing the randomness, but in the meantime
the randomness is exposing a case where the cost basis is not the value
expected, so logging the sim parameter values to help track down what
parameters cause the failure.
2013-10-16 12:07:14 -04:00
Eddie Hebert 1bad245675 ENH: Use annualized returns for beta and alpha.
So that the units match the other risk calculations, also
use annualized returns for beat and alpha.

Update answer key to match values calculated on the first day.

Also, update performance tracker test so that the returns used
are fractional instead of > 1, so that the annualized numbers are
more in line with real world values.
2013-10-11 00:27:03 -04:00
Eddie Hebert bfa94e9c91 ENH: Approximate stats for the first day of minute emission.
Volatility needs mulitple values to calculate the stddev,
so provide a day with zero returns to base the first day against.
2013-10-10 18:37:53 -04:00
John Ricklefs 7b8769b3e7 BUG: Fix div-by-zero error in cost_basis adjustment. 2013-08-27 13:24:06 -04:00
John Ricklefs 191715a148 ENH: Add support for asynchronous commission events. 2013-08-26 14:18:32 -04:00
Thomas Wiecki b89886297f STY: autopep8 codebase. 2013-08-08 16:46:44 -04:00
Jean Bredeche 8f1d599fc6 fixing some bugs with splits (ratios and empty positions) 2013-07-24 15:26:15 -07:00
Jean Bredeche 6fc077a573 ENH: Add support for splits in zipline.
When a split is encountered, open positions and open orders
are updated accordingly.
2013-07-23 16:22:58 -04:00
Jonathan Kamens d833503e50 BUG: Use context in lieu of "use_environment" decorator
The "use_environment" decorator is too side-effectful (e.g.,
connecting to Yahoo! Finance or another data source) to be used as a
decorator to a function that gets evaluated during module load. This
causes problems, e.g., if Zipline is being used in a gevent
environment, when the trading environment created by the decorator
argument tries to use greenlets when gevent hasn't been fully
initialized.

Since the decorator is nothing more than a context-manager wrapper,
this commit removes the decorator and replaces its use with contexts,
i.e., "with" statements.
2013-06-24 17:13:14 -04:00
Eddie Hebert 2b5b670493 MAINT: Change signature of create_transaction.
- Change the expected type for order information from the string
  of the order id to an `Order` object, so that it matches the same
  abstraction level as passing in an event.
- Change the order (not to be confused with the parameter named `order`)
  of the parameters so that they go from left to right in order of
  static -> dynamic, i.e. the parameters most likely to change within
  each invoration are the amount and price, with amount more likely
  to change than price.
2013-06-10 17:10:48 -04:00
Eddie Hebert 7d26168359 MAINT: Reduce number of parameters for create_transaction.
create_transaction accepted both sid and order, which in all cases
was derived from the current event, so remove `sid` and `order`,
replacing them with event

If there is a scenario where sid and order need to be set independently
of each other, then the underlying Transaction object can be called
directly.

Looking towards making writing custom slippage models slightly easier
by removing the redundancy.
2013-06-10 15:36:58 -04:00
Eddie Hebert 32835b87f3 MAINT: Rename perfomances intraday_perf to minute_perf.
minute_perf is more precise than intraday_perf as a naming scheme
for the performance packet type.
2013-05-07 19:21:20 -04:00
fawce 9062b9636a MAINT: refactoring for orders api
- moved Order and Blotter to zipline.finance.blotter
- moved order method from AlgoSimulator to Blotter
- eliminated the set_order method in algorithm
- moved blotter to the algorithm
2013-04-26 19:45:59 -04:00
Eddie Hebert d4a8878c6e TST: Ensure holiday edge case is covered in dividend performance test.
Add a test suite of dividend performance that ensures a holiday
is covered, needed because tests usually go over a random test range,
so holiday coverage isn't covered in basic test.

From @fawce.
2013-04-26 10:56:54 -04:00
fawce 427ea8d4ca ENH: Change simulation loop to use benchmarks as simulation 'clock'.
Refactor PerformanceTracker, Blotter, and AlgorithmSimulator to
work with handling the end of a bar at the AlgorithmSimulator level
instead of within PerformanceTracker.

- PerforamnceTracker and Blotter are longer generators,
  both provide functions to process events instead.
- AlgorithmSimulator calls each from within the loop running
  over the data generator.
- Change test_perf_tracker utility to be compatible with change
  away from PerformanceTracker as a generator.

Has the effect of:
- Fixing the timing of order emission.
- Allow minutely emission of benchmarks, which was prevented
  by the extra grouping previously caused by Blotter.

Minutely emission also depends on work for streaming benchmarks
through performance and risk at a minute granularity.
2013-04-25 17:16:35 -04:00
Eddie Hebert d31303b86c ENH: Add basis for minute rate emission of performance.
- Create different benchmark containers in performance
  depending on emission rate.
- Add a minute close method which updates algorithm and
  benchmark returns, and calculates the risk metrics
  depending on those methods.
- Provide fake 0.0 values for annualized metrics like
  sharpe, sortino, and information, until we figure out
  how they should be treated in the context of minutely
  calculation.

*NOTE* This does not fully work without the changes to the
simulation loop by @fawce
2013-04-25 16:49:38 -04:00
Eddie Hebert 2cc6764b90 TST: Factor out the running events through a test performance tracker.
Based on @fawce's work for changing the simulate loop.
2013-04-25 16:33:01 -04:00
Eddie Hebert d0651706ac TST: Prevent dividend test from using non-trading day.
Use the next events' datetime for the transaction instead of
incrementing by a calendar day.
2013-04-25 15:41:26 -04:00
Eddie Hebert 4b33d6ea4b TST: Ensure that create_trade_history uses midnight for daily trades.
Prepare for implementation of backtest loop that depends on daily
trades being grouped by midnight.
2013-04-25 13:25:50 -04:00
Eddie Hebert 9f0500aa33 TST: Use 9:31 AM EST for first minute of minute performance tests. 2013-04-16 12:23:09 -04:00
Eddie Hebert e7d64fa2e5 STY: Move import in test to top of file. 2013-04-16 12:23:06 -04:00
Eddie Hebert 4ff49749d7 BUG: Fix environment minute date range start and volume.
The bar timestamps for day start and finish, for NYSE traded stocks,
should be 9:31 AM EST to 4:00 PM EST, for a total of 390 minutes.

Fix starting at 9:30 AM and the creation of 391 bars.
2013-04-15 16:35:41 -04:00
Eddie Hebert 9099d301f3 ENH: Stream benchmark returns as events.
Instead of creating a list of benchmarks in the risk module,
stream benchmarks through the system as events, starting from the
algorithm generator.

Works towards more easily setting arbritrary pricing data as
a a benchmark, as well as working towards live minutely benchmarks.
2013-04-15 11:43:13 -04:00
Eddie Hebert 6210467bec MAINT: Use pd.Series for benchmarks and algorithm returns in risk.
Instead of lists, use pd.Series, so that memory is preallocated.
2013-04-15 11:37:21 -04:00
Eddie Hebert cc322af498 TST: Removes unused members in set up from TestPerformanceTracker. 2013-04-15 10:31:19 -04:00
Eddie Hebert 35f57ada3e ENH: Send transactions and orders as standalone events.
- Add transaction and order types
- Move TransactionSimulator from trading.py to tradesimulation.py
  (only used by other members of the tradesimulation module)
- Make Transaction an independent event, like dividend
- Add Blotter class.
- Flatten the transaction events to be independent of trade bar events
- Make orders into events that reach performance (need to add
handling)
- Issue IDs to orders and tracking each transaction's order id.
- Make volume share slippage fill orders independently, rather than
  aggregating them into a single transaction.
- Perf tracker holds orders, serializes them with transactions.
- Order state defined and maintained by order class.
- Minutely emission of orders based on last_modified date.
2013-04-14 18:59:57 -04:00
Eddie Hebert 6a3c35c0fd BUG: Ensure that correct dates are emitted during entire minute rate.
Also, fix double emission of performance results with the last minute.

Change the perf tracker unit tests so that it doesn't rely on an
'extra' event triggering emission.
Unlike daily, minute emission now emits at the end of the bar in
the PerformanceTracker.transform instead of waiting for the next event.
2013-04-11 15:42:07 -04:00
Eddie Hebert 575d68a4e5 DEV: Allow test_minute_tracker to run by itself.
TradingEnvironment was not set, so this test could not be
run in isolation.
2013-04-11 14:24:42 -04:00