CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-webull

The unofficial python interface for the WeBull API

Overview
Eval results
Files

portfolio.mddocs/

Portfolio & Account Management

Complete portfolio management including positions tracking, account activities, order history, dividend information, and account details retrieval.

Prerequisites

All portfolio operations require:

  1. Successful login with valid session
  2. Account access permissions

Capabilities

Account Information

Get basic account details and identification information.

def get_account(self):
    """
    Get complete account information and summary.
    
    Returns:
    dict: Account details including buying power, cash balance, total value, margin info
    """

def get_account_id(self, id=0):
    """
    Get account ID for the user.
    
    Parameters:
    - id (int, optional): Account index if multiple accounts (default 0)
    
    Returns:
    str: Account ID string
    """

def get_detail(self):
    """
    Get detailed user profile and account information.
    
    Returns:
    dict: Detailed user information including profile, preferences, settings
    """

Usage examples:

# Get account summary
account = wb.get_account()
print(f"Total Value: ${account['totalValue']}")
print(f"Cash Balance: ${account['cashBalance']}")
print(f"Buying Power: ${account['buyingPower']}")

# Get account ID
account_id = wb.get_account_id()
print(f"Account ID: {account_id}")

# Get detailed profile
details = wb.get_detail()
print(f"User: {details['userName']}")

Current Positions

Get all current stock, options, and crypto positions.

def get_positions(self):
    """
    Get all current positions in the account.
    
    Returns:
    list: List of position objects containing:
        - ticker: Stock symbol
        - position: Number of shares (positive for long, negative for short)
        - cost: Average cost basis per share
        - marketValue: Current market value of position
        - unrealizedProfitLoss: Unrealized gain/loss
        - unrealizedProfitLossRate: Unrealized gain/loss percentage
        - lastPrice: Last traded price
    """

Usage example:

# Get all positions
positions = wb.get_positions()

print("Current Positions:")
for position in positions:
    symbol = position['ticker']['symbol']
    shares = position['position']
    market_value = position['marketValue']
    pnl = position['unrealizedProfitLoss']
    pnl_pct = position['unrealizedProfitLossRate']
    
    print(f"{symbol}: {shares} shares, Value: ${market_value}, P&L: ${pnl} ({pnl_pct}%)")

Portfolio Overview

Get comprehensive portfolio summary and performance metrics.

def get_portfolio(self):
    """
    Get portfolio overview with performance metrics.
    
    Returns:
    dict: Portfolio summary including:
        - totalValue: Total portfolio value
        - dayChange: Daily change in value
        - dayChangeRate: Daily change percentage
        - totalCost: Total cost basis
        - totalProfitLoss: Total unrealized P&L
        - totalProfitLossRate: Total P&L percentage
        - positions: Summary of position counts
    """

Usage example:

# Get portfolio overview
portfolio = wb.get_portfolio()

print(f"Portfolio Value: ${portfolio['totalValue']}")
print(f"Total Cost: ${portfolio['totalCost']}")
print(f"Total P&L: ${portfolio['totalProfitLoss']} ({portfolio['totalProfitLossRate']}%)")
print(f"Day Change: ${portfolio['dayChange']} ({portfolio['dayChangeRate']}%)")

Account Activities

Get transaction history and account activities.

def get_activities(self, index=1, size=500):
    """
    Get account activities and transaction history.
    
    Parameters:
    - index (int): Page index for pagination (starts at 1)
    - size (int): Number of activities per page (max 500)
    
    Returns:
    list: List of activity objects containing:
        - type: Activity type (BUY, SELL, DIVIDEND, etc.)
        - symbol: Stock symbol if applicable
        - quantity: Number of shares
        - price: Execution price
        - amount: Total amount
        - time: Transaction timestamp
        - status: Transaction status
    """

Usage example:

# Get recent activities
activities = wb.get_activities(size=50)

print("Recent Account Activities:")
for activity in activities:
    activity_type = activity['type']
    symbol = activity.get('symbol', 'N/A')
    amount = activity['amount']
    time = activity['time']
    
    print(f"{time}: {activity_type} {symbol} - ${amount}")

Order Management

Get current and historical orders with detailed status information.

def get_current_orders(self):
    """
    Get all current active/pending orders.
    
    Returns:
    list: List of active order objects containing:
        - orderId: Unique order identifier
        - symbol: Stock symbol
        - action: BUY or SELL
        - orderType: Order type (LMT, MKT, etc.)
        - quantity: Order quantity
        - filledQuantity: Quantity already filled
        - price: Order price
        - status: Order status (PENDING, PARTIAL, etc.)
        - createTime: Order creation timestamp
    """

def get_history_orders(self, status='All', count=20):
    """
    Get historical order data.
    
    Parameters:
    - status (str): Filter by order status - 'All', 'Filled', 'Cancelled', 'Working'
    - count (int): Number of orders to retrieve
    
    Returns:
    list: List of historical order objects
    """

Usage examples:

# Get current active orders
current_orders = wb.get_current_orders()

print("Active Orders:")
for order in current_orders:
    print(f"Order {order['orderId']}: {order['action']} {order['quantity']} {order['symbol']} @ ${order['price']}")
    print(f"  Status: {order['status']}, Filled: {order['filledQuantity']}")

# Get order history
history = wb.get_history_orders(status='Filled', count=10)

print("\nRecent Filled Orders:")
for order in history:
    print(f"{order['symbol']}: {order['action']} {order['quantity']} @ ${order['avgFilledPrice']}")

Dividend Information

Get dividend payments and dividend-related activities.

def get_dividends(self):
    """
    Get dividend payment history and upcoming dividends.
    
    Returns:
    list: List of dividend objects containing:
        - symbol: Stock symbol paying dividend
        - amount: Dividend amount per share
        - payDate: Payment date
        - exDate: Ex-dividend date
        - recordDate: Record date
        - shares: Number of shares owned on record date
        - totalAmount: Total dividend payment
    """

Usage example:

# Get dividend history
dividends = wb.get_dividends()

print("Dividend Payments:")
total_dividends = 0
for dividend in dividends:
    symbol = dividend['symbol']
    amount = dividend['totalAmount']
    pay_date = dividend['payDate']
    total_dividends += amount
    
    print(f"{symbol}: ${amount} on {pay_date}")

print(f"Total Dividends: ${total_dividends}")

Watchlists

Get user's watchlists and tracked securities.

def get_watchlists(self, as_list_symbols=False):
    """
    Get user's watchlists.
    
    Parameters:
    - as_list_symbols (bool): Return as simple list of symbols if True, full objects if False
    
    Returns:
    list: Watchlist data - either simple symbols list or full watchlist objects
    """

Usage example:

# Get full watchlist objects
watchlists = wb.get_watchlists()
for watchlist in watchlists:
    print(f"Watchlist: {watchlist['name']}")
    for item in watchlist['items']:
        print(f"  - {item['symbol']}")

# Get simple symbols list
symbols = wb.get_watchlists(as_list_symbols=True)
print(f"Watched symbols: {', '.join(symbols)}")

Portfolio Analysis Example

Complete portfolio analysis and reporting:

from webull import webull
import datetime

wb = webull()
wb.login('your_email@example.com', 'your_password')

try:
    # Get account overview
    account = wb.get_account()
    portfolio = wb.get_portfolio()
    
    print("=== PORTFOLIO SUMMARY ===")
    print(f"Account Value: ${account['totalValue']:,.2f}")
    print(f"Cash Balance: ${account['cashBalance']:,.2f}")
    print(f"Buying Power: ${account['buyingPower']:,.2f}")
    print(f"Day Change: ${portfolio['dayChange']:,.2f} ({portfolio['dayChangeRate']:.2f}%)")
    print(f"Total P&L: ${portfolio['totalProfitLoss']:,.2f} ({portfolio['totalProfitLossRate']:.2f}%)")
    
    # Analyze positions
    positions = wb.get_positions()
    print(f"\n=== POSITIONS ({len(positions)} holdings) ===")
    
    total_value = 0
    winners = 0
    losers = 0
    
    for position in positions:
        symbol = position['ticker']['symbol']
        shares = position['position']
        cost = position['cost']
        market_value = position['marketValue']
        pnl = position['unrealizedProfitLoss']
        pnl_pct = position['unrealizedProfitLossRate']
        
        total_value += market_value
        if pnl > 0:
            winners += 1
        elif pnl < 0:
            losers += 1
        
        status = "🟢" if pnl > 0 else "🔴" if pnl < 0 else "⚪"
        print(f"{status} {symbol}: {shares} shares @ ${cost:.2f} = ${market_value:,.2f}")
        print(f"    P&L: ${pnl:,.2f} ({pnl_pct:.2f}%)")
    
    print(f"\nWinners: {winners}, Losers: {losers}, Breakeven: {len(positions) - winners - losers}")
    
    # Check active orders
    orders = wb.get_current_orders()
    if orders:
        print(f"\n=== ACTIVE ORDERS ({len(orders)}) ===")
        for order in orders:
            print(f"{order['symbol']}: {order['action']} {order['quantity']} @ ${order['price']}")
            print(f"  Status: {order['status']}, Type: {order['orderType']}")
    
    # Recent activity summary
    activities = wb.get_activities(size=10)
    print(f"\n=== RECENT ACTIVITY ===")
    for activity in activities[:5]:  # Show last 5 activities
        activity_type = activity['type']
        symbol = activity.get('symbol', '')
        amount = activity['amount']
        print(f"{activity_type} {symbol}: ${amount}")
    
    # Dividend summary
    dividends = wb.get_dividends()
    if dividends:
        total_div = sum(d['totalAmount'] for d in dividends)
        print(f"\n=== DIVIDENDS ===")
        print(f"Total Dividend Income: ${total_div:,.2f}")
        recent_div = [d for d in dividends if d['payDate'] > '2024-01-01']
        print(f"Dividends This Year: ${sum(d['totalAmount'] for d in recent_div):,.2f}")

except ValueError as e:
    print(f"Error accessing portfolio data: {e}")

Risk Management Functions

Monitor portfolio risk and performance metrics:

def calculate_portfolio_metrics(wb):
    """Calculate basic portfolio performance metrics."""
    
    account = wb.get_account()
    positions = wb.get_positions()
    
    # Calculate position concentration
    total_value = account['totalValue']
    position_weights = {}
    
    for position in positions:
        symbol = position['ticker']['symbol']
        weight = position['marketValue'] / total_value * 100
        position_weights[symbol] = weight
    
    # Find largest positions
    largest_positions = sorted(position_weights.items(), key=lambda x: x[1], reverse=True)[:5]
    
    print("Portfolio Concentration (Top 5):")
    for symbol, weight in largest_positions:
        print(f"{symbol}: {weight:.1f}%")
        if weight > 20:
            print(f"  ⚠️  High concentration risk")
    
    # Calculate sector diversity (simplified)
    cash_percentage = account['cashBalance'] / total_value * 100
    print(f"\nCash Allocation: {cash_percentage:.1f}%")
    
    if cash_percentage < 5:
        print("  ⚠️  Low cash reserves")
    elif cash_percentage > 30:
        print("  ℹ️  High cash allocation - consider deployment")

# Usage
calculate_portfolio_metrics(wb)

Install with Tessl CLI

npx tessl i tessl/pypi-webull

docs

alerts-screening.md

authentication.md

index.md

market-data.md

options.md

paper-trading.md

portfolio.md

streaming.md

trading.md

tile.json