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