Total Complexity | 54 |
Total Lines | 347 |
Duplicated Lines | 0 % |
Complex classes like zipline.finance.performance.PositionTracker often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
1 | # |
||
170 | class PositionTracker(object): |
||
171 | |||
172 | def __init__(self, asset_finder, data_portal, data_frequency): |
||
173 | self.asset_finder = asset_finder |
||
174 | |||
175 | # FIXME really want to avoid storing a data portal here, |
||
176 | # but the path to get to maybe_create_close_position_transaction |
||
177 | # is long and tortuous |
||
178 | self._data_portal = data_portal |
||
179 | |||
180 | # sid => position object |
||
181 | self.positions = positiondict() |
||
182 | |||
183 | # Arrays for quick calculations of positions value |
||
184 | self._position_value_multipliers = OrderedDict() |
||
185 | self._position_exposure_multipliers = OrderedDict() |
||
186 | self._position_payout_multipliers = OrderedDict() |
||
187 | self._unpaid_dividends = {} |
||
188 | self._unpaid_stock_dividends = {} |
||
189 | self._positions_store = zp.Positions() |
||
190 | |||
191 | # Dict, keyed on dates, that contains lists of close position events |
||
192 | # for any Assets in this tracker's positions |
||
193 | self._auto_close_position_sids = {} |
||
194 | |||
195 | self.data_frequency = data_frequency |
||
196 | |||
197 | def _update_asset(self, sid): |
||
198 | try: |
||
199 | self._position_value_multipliers[sid] |
||
200 | self._position_exposure_multipliers[sid] |
||
201 | self._position_payout_multipliers[sid] |
||
202 | except KeyError: |
||
203 | # Check if there is an AssetFinder |
||
204 | if self.asset_finder is None: |
||
205 | raise PositionTrackerMissingAssetFinder() |
||
206 | |||
207 | # Collect the value multipliers from applicable sids |
||
208 | asset = self.asset_finder.retrieve_asset(sid) |
||
209 | if isinstance(asset, Equity): |
||
210 | self._position_value_multipliers[sid] = 1 |
||
211 | self._position_exposure_multipliers[sid] = 1 |
||
212 | self._position_payout_multipliers[sid] = 0 |
||
213 | if isinstance(asset, Future): |
||
214 | self._position_value_multipliers[sid] = 0 |
||
215 | self._position_exposure_multipliers[sid] = \ |
||
216 | asset.contract_multiplier |
||
217 | self._position_payout_multipliers[sid] = \ |
||
218 | asset.contract_multiplier |
||
219 | # Futures auto-close timing is controlled by the Future's |
||
220 | # auto_close_date property |
||
221 | self._insert_auto_close_position_date( |
||
222 | dt=asset.auto_close_date, |
||
223 | sid=sid |
||
224 | ) |
||
225 | |||
226 | def _insert_auto_close_position_date(self, dt, sid): |
||
227 | """ |
||
228 | Inserts the given SID in to the list of positions to be auto-closed by |
||
229 | the given dt. |
||
230 | |||
231 | Parameters |
||
232 | ---------- |
||
233 | dt : pandas.Timestamp |
||
234 | The date before-which the given SID will be auto-closed |
||
235 | sid : int |
||
236 | The SID of the Asset to be auto-closed |
||
237 | """ |
||
238 | if dt is not None: |
||
239 | self._auto_close_position_sids.setdefault(dt, set()).add(sid) |
||
240 | |||
241 | def auto_close_position_events(self, next_trading_day): |
||
242 | """ |
||
243 | Generates CLOSE_POSITION events for any SIDs whose auto-close date is |
||
244 | before or equal to the given date. |
||
245 | |||
246 | Parameters |
||
247 | ---------- |
||
248 | next_trading_day : pandas.Timestamp |
||
249 | The time before-which certain Assets need to be closed |
||
250 | |||
251 | Yields |
||
252 | ------ |
||
253 | Event |
||
254 | A close position event for any sids that should be closed before |
||
255 | the next_trading_day parameter |
||
256 | """ |
||
257 | past_asset_end_dates = set() |
||
258 | |||
259 | # Check the auto_close_position_dates dict for SIDs to close |
||
260 | for date, sids in self._auto_close_position_sids.items(): |
||
261 | if date > next_trading_day: |
||
262 | continue |
||
263 | past_asset_end_dates.add(date) |
||
264 | |||
265 | for sid in sids: |
||
266 | # Yield a CLOSE_POSITION event |
||
267 | event = Event({ |
||
268 | 'dt': date, |
||
269 | 'type': DATASOURCE_TYPE.CLOSE_POSITION, |
||
270 | 'sid': sid, |
||
271 | }) |
||
272 | yield event |
||
273 | |||
274 | # Clear out past dates |
||
275 | while past_asset_end_dates: |
||
276 | self._auto_close_position_sids.pop(past_asset_end_dates.pop()) |
||
277 | |||
278 | def update_positions(self, positions): |
||
279 | # update positions in batch |
||
280 | self.positions.update(positions) |
||
281 | for sid, pos in iteritems(positions): |
||
282 | self._update_asset(sid) |
||
283 | |||
284 | def update_position(self, sid, amount=None, last_sale_price=None, |
||
285 | last_sale_date=None, cost_basis=None): |
||
286 | if sid not in self.positions: |
||
287 | position = Position(sid) |
||
288 | self.positions[sid] = position |
||
289 | else: |
||
290 | position = self.positions[sid] |
||
291 | |||
292 | if amount is not None: |
||
293 | position.amount = amount |
||
294 | self._update_asset(sid=sid) |
||
295 | if last_sale_price is not None: |
||
296 | position.last_sale_price = last_sale_price |
||
297 | if last_sale_date is not None: |
||
298 | position.last_sale_date = last_sale_date |
||
299 | if cost_basis is not None: |
||
300 | position.cost_basis = cost_basis |
||
301 | |||
302 | def execute_transaction(self, txn): |
||
303 | # Update Position |
||
304 | # ---------------- |
||
305 | sid = txn.sid |
||
306 | |||
307 | if sid not in self.positions: |
||
308 | position = Position(sid) |
||
309 | self.positions[sid] = position |
||
310 | else: |
||
311 | position = self.positions[sid] |
||
312 | |||
313 | position.update(txn) |
||
314 | self._update_asset(sid) |
||
315 | |||
316 | def handle_commission(self, sid, cost): |
||
317 | # Adjust the cost basis of the stock if we own it |
||
318 | if sid in self.positions: |
||
319 | self.positions[sid].\ |
||
320 | adjust_commission_cost_basis(sid, cost) |
||
321 | |||
322 | def handle_splits(self, splits): |
||
323 | """ |
||
324 | Processes a list of splits by modifying any positions as needed. |
||
325 | |||
326 | Parameters |
||
327 | ---------- |
||
328 | splits: list |
||
329 | A list of splits. Each split is a tuple of (sid, ratio). |
||
330 | |||
331 | Returns |
||
332 | ------- |
||
333 | None |
||
334 | """ |
||
335 | for split in splits: |
||
336 | sid = split[0] |
||
337 | if sid in self.positions: |
||
338 | # Make the position object handle the split. It returns the |
||
339 | # leftover cash from a fractional share, if there is any. |
||
340 | position = self.positions[sid] |
||
341 | leftover_cash = position.handle_split(sid, split[1]) |
||
342 | self._update_asset(split[0]) |
||
343 | return leftover_cash |
||
344 | |||
345 | def earn_dividends(self, dividends, stock_dividends): |
||
346 | """ |
||
347 | Given a list of dividends whose ex_dates are all the next trading day, |
||
348 | calculate and store the cash and/or stock payments to be paid on each |
||
349 | dividend's pay date. |
||
350 | """ |
||
351 | for dividend in dividends: |
||
352 | # Store the earned dividends so that they can be paid on the |
||
353 | # dividends' pay_dates. |
||
354 | div_owed = self.positions[dividend.sid].earn_dividend(dividend) |
||
355 | try: |
||
356 | self._unpaid_dividends[dividend.pay_date].append( |
||
357 | div_owed) |
||
358 | except KeyError: |
||
359 | self._unpaid_dividends[dividend.pay_date] = [div_owed] |
||
360 | |||
361 | for stock_dividend in stock_dividends: |
||
362 | div_owed = self.positions[stock_dividend.sid].earn_stock_dividend( |
||
363 | stock_dividend) |
||
364 | try: |
||
365 | self._unpaid_stock_dividends[stock_dividend.pay_date].\ |
||
366 | append(div_owed) |
||
367 | except KeyError: |
||
368 | self._unpaid_stock_dividends[stock_dividend.pay_date] = \ |
||
369 | [div_owed] |
||
370 | |||
371 | def pay_dividends(self, next_trading_day): |
||
372 | """ |
||
373 | Returns a cash payment based on the dividends that should be paid out |
||
374 | according to the accumulated bookkeeping of earned, unpaid, and stock |
||
375 | dividends. |
||
376 | """ |
||
377 | net_cash_payment = 0.0 |
||
378 | |||
379 | try: |
||
380 | payments = self._unpaid_dividends[next_trading_day] |
||
381 | # Mark these dividends as paid by dropping them from our unpaid |
||
382 | del self._unpaid_dividends[next_trading_day] |
||
383 | except KeyError: |
||
384 | payments = [] |
||
385 | |||
386 | # representing the fact that we're required to reimburse the owner of |
||
387 | # the stock for any dividends paid while borrowing. |
||
388 | for payment in payments: |
||
389 | net_cash_payment += payment['amount'] |
||
390 | |||
391 | # Add stock for any stock dividends paid. Again, the values here may |
||
392 | # be negative in the case of short positions. |
||
393 | |||
394 | try: |
||
395 | stock_payments = self._unpaid_stock_dividends[next_trading_day] |
||
396 | except: |
||
397 | stock_payments = [] |
||
398 | |||
399 | for stock_payment in stock_payments: |
||
400 | stock = stock_payment['payment_sid'] |
||
401 | share_count = stock_payment['share_count'] |
||
402 | # note we create a Position for stock dividend if we don't |
||
403 | # already own the asset |
||
404 | if stock in self.positions: |
||
405 | position = self.positions[stock] |
||
406 | else: |
||
407 | position = self.positions[stock] = Position(stock) |
||
408 | |||
409 | position.amount += share_count |
||
410 | self._update_asset(stock) |
||
411 | |||
412 | return net_cash_payment |
||
413 | |||
414 | def maybe_create_close_position_transaction(self, event): |
||
415 | if not self.positions.get(event.sid): |
||
416 | return None |
||
417 | |||
418 | amount = self.positions.get(event.sid).amount |
||
419 | price = self._data_portal.get_spot_value( |
||
420 | event.sid, 'close', event.dt, self.data_frequency) |
||
421 | |||
422 | txn = Transaction( |
||
423 | sid=event.sid, |
||
424 | amount=(-1 * amount), |
||
425 | dt=event.dt, |
||
426 | price=price, |
||
427 | commission=0, |
||
428 | order_id=0 |
||
429 | ) |
||
430 | return txn |
||
431 | |||
432 | def get_positions(self): |
||
433 | positions = self._positions_store |
||
434 | |||
435 | for sid, pos in iteritems(self.positions): |
||
436 | if pos.amount == 0: |
||
437 | # Clear out the position if it has become empty since the last |
||
438 | # time get_positions was called. Catching the KeyError is |
||
439 | # faster than checking `if sid in positions`, and this can be |
||
440 | # potentially called in a tight inner loop. |
||
441 | try: |
||
442 | del positions[sid] |
||
443 | except KeyError: |
||
444 | pass |
||
445 | continue |
||
446 | |||
447 | # Note that this will create a position if we don't currently have |
||
448 | # an entry |
||
449 | position = positions[sid] |
||
450 | position.amount = pos.amount |
||
451 | position.cost_basis = pos.cost_basis |
||
452 | position.last_sale_price = pos.last_sale_price |
||
453 | position.last_sale_date = pos.last_sale_date |
||
454 | |||
455 | return positions |
||
456 | |||
457 | def get_positions_list(self): |
||
458 | positions = [] |
||
459 | for sid, pos in iteritems(self.positions): |
||
460 | if pos.amount != 0: |
||
461 | positions.append(pos.to_dict()) |
||
462 | return positions |
||
463 | |||
464 | def sync_last_sale_prices(self, dt): |
||
465 | data_portal = self._data_portal |
||
466 | for sid, position in iteritems(self.positions): |
||
467 | position.last_sale_price = data_portal.get_spot_value( |
||
468 | sid, 'close', dt, self.data_frequency) |
||
469 | |||
470 | def stats(self): |
||
471 | return calc_position_stats(self.positions, |
||
472 | self._position_value_multipliers, |
||
473 | self._position_exposure_multipliers) |
||
474 | |||
475 | def __getstate__(self): |
||
476 | state_dict = {} |
||
477 | |||
478 | state_dict['asset_finder'] = self.asset_finder |
||
479 | state_dict['positions'] = dict(self.positions) |
||
480 | state_dict['unpaid_dividends'] = self._unpaid_dividends |
||
481 | state_dict['unpaid_stock_dividends'] = self._unpaid_stock_dividends |
||
482 | state_dict['auto_close_position_sids'] = self._auto_close_position_sids |
||
483 | state_dict['data_frequency'] = self.data_frequency |
||
484 | |||
485 | STATE_VERSION = 3 |
||
486 | state_dict[VERSION_LABEL] = STATE_VERSION |
||
487 | return state_dict |
||
488 | |||
489 | def __setstate__(self, state): |
||
490 | OLDEST_SUPPORTED_STATE = 3 |
||
491 | version = state.pop(VERSION_LABEL) |
||
492 | |||
493 | if version < OLDEST_SUPPORTED_STATE: |
||
494 | raise BaseException("PositionTracker saved state is too old.") |
||
495 | |||
496 | self.asset_finder = state['asset_finder'] |
||
497 | self.positions = positiondict() |
||
498 | self.data_frequency = state['data_frequency'] |
||
499 | # note that positions_store is temporary and gets regened from |
||
500 | # .positions |
||
501 | self._positions_store = zp.Positions() |
||
502 | |||
503 | self._unpaid_dividends = state['unpaid_dividends'] |
||
504 | self._unpaid_stock_dividends = state['unpaid_stock_dividends'] |
||
505 | self._auto_close_position_sids = state['auto_close_position_sids'] |
||
506 | |||
507 | # Arrays for quick calculations of positions value |
||
508 | self._position_value_multipliers = OrderedDict() |
||
509 | self._position_exposure_multipliers = OrderedDict() |
||
510 | self._position_payout_multipliers = OrderedDict() |
||
511 | |||
512 | # Update positions is called without a finder |
||
513 | self.update_positions(state['positions']) |
||
514 | |||
515 | # FIXME |
||
516 | self._data_portal = None |
||
517 |