-
Notifications
You must be signed in to change notification settings - Fork 102
/
portfolio_utils.py
83 lines (60 loc) · 1.76 KB
/
portfolio_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import numpy as np
import pandas as pd
def last_trade(context, data, sid):
"""
Returns the last price for a given asset.
This method is robust to times when the
asset is not in the data object because it did
not trade during the period
parameters
----------
context:
TradingAlgorithm context object
passed to handle_data
data : zipline.protocol.BarData
data object passed to handle_data
sid : zipline Asset
the sid price
"""
try:
return data[sid].price
except KeyError:
return context.portfolio.positions[sid].last_sale_price
def get_current_holdings(context, data):
"""
Returns current portfolio holdings
i.e. number of shares/contracts held of
each asset.
parameters
----------
context :
TradingAlgorithm context object
passed to handle_data
data : zipline.protocol.BarData
data object passed to handle_data
returns
-------
pandas.Series
contracts held of each asset
"""
positions = context.portfolio.positions
return pd.Series({stock: pos.amount
for stock, pos in positions.iteritems()})
def get_current_allocations(context, data):
"""
parameters
----------
context :
TradingAlgorithm context object
passed to handle_data
data : zipline.protocol.BarData
data object passed to handle_data
returns
-------
pandas.Series
current allocations as a percent of total liquidity
"""
holdings = get_current_holdings(context, data)
prices = pd.Series({sid: last_trade(context, data, sid)
for sid in holdings.index})
return prices * holdings / context.portfolio.portfolio_value