0
# Portfolio & Account Management
1
2
Complete portfolio management including positions tracking, account activities, order history, dividend information, and account details retrieval.
3
4
## Prerequisites
5
6
All portfolio operations require:
7
1. Successful login with valid session
8
2. Account access permissions
9
10
## Capabilities
11
12
### Account Information
13
14
Get basic account details and identification information.
15
16
```python { .api }
17
def get_account(self):
18
"""
19
Get complete account information and summary.
20
21
Returns:
22
dict: Account details including buying power, cash balance, total value, margin info
23
"""
24
25
def get_account_id(self, id=0):
26
"""
27
Get account ID for the user.
28
29
Parameters:
30
- id (int, optional): Account index if multiple accounts (default 0)
31
32
Returns:
33
str: Account ID string
34
"""
35
36
def get_detail(self):
37
"""
38
Get detailed user profile and account information.
39
40
Returns:
41
dict: Detailed user information including profile, preferences, settings
42
"""
43
```
44
45
Usage examples:
46
47
```python
48
# Get account summary
49
account = wb.get_account()
50
print(f"Total Value: ${account['totalValue']}")
51
print(f"Cash Balance: ${account['cashBalance']}")
52
print(f"Buying Power: ${account['buyingPower']}")
53
54
# Get account ID
55
account_id = wb.get_account_id()
56
print(f"Account ID: {account_id}")
57
58
# Get detailed profile
59
details = wb.get_detail()
60
print(f"User: {details['userName']}")
61
```
62
63
### Current Positions
64
65
Get all current stock, options, and crypto positions.
66
67
```python { .api }
68
def get_positions(self):
69
"""
70
Get all current positions in the account.
71
72
Returns:
73
list: List of position objects containing:
74
- ticker: Stock symbol
75
- position: Number of shares (positive for long, negative for short)
76
- cost: Average cost basis per share
77
- marketValue: Current market value of position
78
- unrealizedProfitLoss: Unrealized gain/loss
79
- unrealizedProfitLossRate: Unrealized gain/loss percentage
80
- lastPrice: Last traded price
81
"""
82
```
83
84
Usage example:
85
86
```python
87
# Get all positions
88
positions = wb.get_positions()
89
90
print("Current Positions:")
91
for position in positions:
92
symbol = position['ticker']['symbol']
93
shares = position['position']
94
market_value = position['marketValue']
95
pnl = position['unrealizedProfitLoss']
96
pnl_pct = position['unrealizedProfitLossRate']
97
98
print(f"{symbol}: {shares} shares, Value: ${market_value}, P&L: ${pnl} ({pnl_pct}%)")
99
```
100
101
### Portfolio Overview
102
103
Get comprehensive portfolio summary and performance metrics.
104
105
```python { .api }
106
def get_portfolio(self):
107
"""
108
Get portfolio overview with performance metrics.
109
110
Returns:
111
dict: Portfolio summary including:
112
- totalValue: Total portfolio value
113
- dayChange: Daily change in value
114
- dayChangeRate: Daily change percentage
115
- totalCost: Total cost basis
116
- totalProfitLoss: Total unrealized P&L
117
- totalProfitLossRate: Total P&L percentage
118
- positions: Summary of position counts
119
"""
120
```
121
122
Usage example:
123
124
```python
125
# Get portfolio overview
126
portfolio = wb.get_portfolio()
127
128
print(f"Portfolio Value: ${portfolio['totalValue']}")
129
print(f"Total Cost: ${portfolio['totalCost']}")
130
print(f"Total P&L: ${portfolio['totalProfitLoss']} ({portfolio['totalProfitLossRate']}%)")
131
print(f"Day Change: ${portfolio['dayChange']} ({portfolio['dayChangeRate']}%)")
132
```
133
134
### Account Activities
135
136
Get transaction history and account activities.
137
138
```python { .api }
139
def get_activities(self, index=1, size=500):
140
"""
141
Get account activities and transaction history.
142
143
Parameters:
144
- index (int): Page index for pagination (starts at 1)
145
- size (int): Number of activities per page (max 500)
146
147
Returns:
148
list: List of activity objects containing:
149
- type: Activity type (BUY, SELL, DIVIDEND, etc.)
150
- symbol: Stock symbol if applicable
151
- quantity: Number of shares
152
- price: Execution price
153
- amount: Total amount
154
- time: Transaction timestamp
155
- status: Transaction status
156
"""
157
```
158
159
Usage example:
160
161
```python
162
# Get recent activities
163
activities = wb.get_activities(size=50)
164
165
print("Recent Account Activities:")
166
for activity in activities:
167
activity_type = activity['type']
168
symbol = activity.get('symbol', 'N/A')
169
amount = activity['amount']
170
time = activity['time']
171
172
print(f"{time}: {activity_type} {symbol} - ${amount}")
173
```
174
175
### Order Management
176
177
Get current and historical orders with detailed status information.
178
179
```python { .api }
180
def get_current_orders(self):
181
"""
182
Get all current active/pending orders.
183
184
Returns:
185
list: List of active order objects containing:
186
- orderId: Unique order identifier
187
- symbol: Stock symbol
188
- action: BUY or SELL
189
- orderType: Order type (LMT, MKT, etc.)
190
- quantity: Order quantity
191
- filledQuantity: Quantity already filled
192
- price: Order price
193
- status: Order status (PENDING, PARTIAL, etc.)
194
- createTime: Order creation timestamp
195
"""
196
197
def get_history_orders(self, status='All', count=20):
198
"""
199
Get historical order data.
200
201
Parameters:
202
- status (str): Filter by order status - 'All', 'Filled', 'Cancelled', 'Working'
203
- count (int): Number of orders to retrieve
204
205
Returns:
206
list: List of historical order objects
207
"""
208
```
209
210
Usage examples:
211
212
```python
213
# Get current active orders
214
current_orders = wb.get_current_orders()
215
216
print("Active Orders:")
217
for order in current_orders:
218
print(f"Order {order['orderId']}: {order['action']} {order['quantity']} {order['symbol']} @ ${order['price']}")
219
print(f" Status: {order['status']}, Filled: {order['filledQuantity']}")
220
221
# Get order history
222
history = wb.get_history_orders(status='Filled', count=10)
223
224
print("\nRecent Filled Orders:")
225
for order in history:
226
print(f"{order['symbol']}: {order['action']} {order['quantity']} @ ${order['avgFilledPrice']}")
227
```
228
229
### Dividend Information
230
231
Get dividend payments and dividend-related activities.
232
233
```python { .api }
234
def get_dividends(self):
235
"""
236
Get dividend payment history and upcoming dividends.
237
238
Returns:
239
list: List of dividend objects containing:
240
- symbol: Stock symbol paying dividend
241
- amount: Dividend amount per share
242
- payDate: Payment date
243
- exDate: Ex-dividend date
244
- recordDate: Record date
245
- shares: Number of shares owned on record date
246
- totalAmount: Total dividend payment
247
"""
248
```
249
250
Usage example:
251
252
```python
253
# Get dividend history
254
dividends = wb.get_dividends()
255
256
print("Dividend Payments:")
257
total_dividends = 0
258
for dividend in dividends:
259
symbol = dividend['symbol']
260
amount = dividend['totalAmount']
261
pay_date = dividend['payDate']
262
total_dividends += amount
263
264
print(f"{symbol}: ${amount} on {pay_date}")
265
266
print(f"Total Dividends: ${total_dividends}")
267
```
268
269
### Watchlists
270
271
Get user's watchlists and tracked securities.
272
273
```python { .api }
274
def get_watchlists(self, as_list_symbols=False):
275
"""
276
Get user's watchlists.
277
278
Parameters:
279
- as_list_symbols (bool): Return as simple list of symbols if True, full objects if False
280
281
Returns:
282
list: Watchlist data - either simple symbols list or full watchlist objects
283
"""
284
```
285
286
Usage example:
287
288
```python
289
# Get full watchlist objects
290
watchlists = wb.get_watchlists()
291
for watchlist in watchlists:
292
print(f"Watchlist: {watchlist['name']}")
293
for item in watchlist['items']:
294
print(f" - {item['symbol']}")
295
296
# Get simple symbols list
297
symbols = wb.get_watchlists(as_list_symbols=True)
298
print(f"Watched symbols: {', '.join(symbols)}")
299
```
300
301
## Portfolio Analysis Example
302
303
Complete portfolio analysis and reporting:
304
305
```python
306
from webull import webull
307
import datetime
308
309
wb = webull()
310
wb.login('your_email@example.com', 'your_password')
311
312
try:
313
# Get account overview
314
account = wb.get_account()
315
portfolio = wb.get_portfolio()
316
317
print("=== PORTFOLIO SUMMARY ===")
318
print(f"Account Value: ${account['totalValue']:,.2f}")
319
print(f"Cash Balance: ${account['cashBalance']:,.2f}")
320
print(f"Buying Power: ${account['buyingPower']:,.2f}")
321
print(f"Day Change: ${portfolio['dayChange']:,.2f} ({portfolio['dayChangeRate']:.2f}%)")
322
print(f"Total P&L: ${portfolio['totalProfitLoss']:,.2f} ({portfolio['totalProfitLossRate']:.2f}%)")
323
324
# Analyze positions
325
positions = wb.get_positions()
326
print(f"\n=== POSITIONS ({len(positions)} holdings) ===")
327
328
total_value = 0
329
winners = 0
330
losers = 0
331
332
for position in positions:
333
symbol = position['ticker']['symbol']
334
shares = position['position']
335
cost = position['cost']
336
market_value = position['marketValue']
337
pnl = position['unrealizedProfitLoss']
338
pnl_pct = position['unrealizedProfitLossRate']
339
340
total_value += market_value
341
if pnl > 0:
342
winners += 1
343
elif pnl < 0:
344
losers += 1
345
346
status = "🟢" if pnl > 0 else "🔴" if pnl < 0 else "⚪"
347
print(f"{status} {symbol}: {shares} shares @ ${cost:.2f} = ${market_value:,.2f}")
348
print(f" P&L: ${pnl:,.2f} ({pnl_pct:.2f}%)")
349
350
print(f"\nWinners: {winners}, Losers: {losers}, Breakeven: {len(positions) - winners - losers}")
351
352
# Check active orders
353
orders = wb.get_current_orders()
354
if orders:
355
print(f"\n=== ACTIVE ORDERS ({len(orders)}) ===")
356
for order in orders:
357
print(f"{order['symbol']}: {order['action']} {order['quantity']} @ ${order['price']}")
358
print(f" Status: {order['status']}, Type: {order['orderType']}")
359
360
# Recent activity summary
361
activities = wb.get_activities(size=10)
362
print(f"\n=== RECENT ACTIVITY ===")
363
for activity in activities[:5]: # Show last 5 activities
364
activity_type = activity['type']
365
symbol = activity.get('symbol', '')
366
amount = activity['amount']
367
print(f"{activity_type} {symbol}: ${amount}")
368
369
# Dividend summary
370
dividends = wb.get_dividends()
371
if dividends:
372
total_div = sum(d['totalAmount'] for d in dividends)
373
print(f"\n=== DIVIDENDS ===")
374
print(f"Total Dividend Income: ${total_div:,.2f}")
375
recent_div = [d for d in dividends if d['payDate'] > '2024-01-01']
376
print(f"Dividends This Year: ${sum(d['totalAmount'] for d in recent_div):,.2f}")
377
378
except ValueError as e:
379
print(f"Error accessing portfolio data: {e}")
380
```
381
382
## Risk Management Functions
383
384
Monitor portfolio risk and performance metrics:
385
386
```python
387
def calculate_portfolio_metrics(wb):
388
"""Calculate basic portfolio performance metrics."""
389
390
account = wb.get_account()
391
positions = wb.get_positions()
392
393
# Calculate position concentration
394
total_value = account['totalValue']
395
position_weights = {}
396
397
for position in positions:
398
symbol = position['ticker']['symbol']
399
weight = position['marketValue'] / total_value * 100
400
position_weights[symbol] = weight
401
402
# Find largest positions
403
largest_positions = sorted(position_weights.items(), key=lambda x: x[1], reverse=True)[:5]
404
405
print("Portfolio Concentration (Top 5):")
406
for symbol, weight in largest_positions:
407
print(f"{symbol}: {weight:.1f}%")
408
if weight > 20:
409
print(f" ⚠️ High concentration risk")
410
411
# Calculate sector diversity (simplified)
412
cash_percentage = account['cashBalance'] / total_value * 100
413
print(f"\nCash Allocation: {cash_percentage:.1f}%")
414
415
if cash_percentage < 5:
416
print(" ⚠️ Low cash reserves")
417
elif cash_percentage > 30:
418
print(" ℹ️ High cash allocation - consider deployment")
419
420
# Usage
421
calculate_portfolio_metrics(wb)
422
```