How to Automatically Update Your IBridgePy Portfolio Every Day with Python
Automate Daily Updates to Your Live IBridgePy Portfolio
Publish end-of-day cash, holdings, and Net Asset Value (NAV) to your public IBridgePy Portfolio page—like the live DigitalShare LAB (DLAB) strategy—with a single Python HTTP call scheduled after US market close.
Every strategy hosted on IBridgePy Portfolio tracks its daily equity curve, cash balance, positions, and cumulative return compared against the SPY benchmark. Instead of manually sending CSV files or spreadsheets, you can update your strategy automatically every trading day with a 30-line Python script.
What You Need Before You Start
- Your IBridgePy API Key: Log in at ibridgepy.com/home/ and click Show / Copy inside the API Key card. Your key can update any strategy owned by your account.
- Your Strategy Slug: Copy the final segment of your portfolio URL:
https://ibridgepy.com/portfolio/<username>/<strategy-slug>/
For DigitalShare LAB (DLAB), the strategy slug isdigitalshare-lab-dlab. (Strategy UUIDs are also accepted.) - Python 3.9+ and
requests: Install withpip install requests(andpip install tzdataon Windows if needed for US Eastern time).
Step 1: Understand the Portfolio Snapshot API
To publish or update a trading day's snapshot, send an authenticated HTTP POST request with a JSON body to:
POST https://ibridgepy.com/portfolio/snapshot/
Headers:
Content-Type: application/json
X-API-Key: <YOUR_IBRIDGEPY_API_KEY>
| Field | Type | Required | Description & Example |
|---|---|---|---|
| strategy | string | Yes | Your strategy slug (e.g., "digitalshare-lab-dlab") or strategy UUID. |
| date | string | Yes | Trading date in ISO format YYYY-MM-DD (e.g., "2026-12-01"). |
| cash | float | Yes | End-of-day cash balance in USD (e.g., 1007445.87). |
| positions | list of strings | Optional | Holdings list such as ["Stocks:1@21793.20", "Options:1@40217.01"] or ["SPY:56"]. Use [] for 100% cash. Serialized JSON string must be ≤ 500 characters. |
| action | string | Optional | Human-readable note shown in the Daily History table (max 500 chars), e.g., "Equities: $66,332.21 | Cash: $1,007,445.87". |
| total_value | float | Optional | Automatically calculated on the server as round(cash + sum(position_values), 2) and returned in the JSON response. |
Step 2: Choose the Right positions Format
Each entry in positions follows either TICKER:QTY or LABEL:QTY@PRICE. Pick the style that best matches your portfolio:
Option A: Asset-Class Buckets (Best for Multi-Asset & Options)
Used by portfolios like DigitalShare LAB (DLAB) that hold stocks, ETFs, and options. Set quantity to 1 and put each bucket's exact market value after @:
"positions": [
"Stocks:1@21793.20",
"Options:1@40217.01",
"ETFs:1@4322.00"
]
Option B: US Stock / ETF Tickers (Auto-Priced)
For standard US equities and ETFs, send just TICKER:QTY. IBridgePy automatically looks up the official daily closing price and computes your total NAV:
"positions": [
"SPY:56",
"TLT:120",
"SMH:35"
]
@PRICE):
- The server computes each holding's market value as
quantity × price. For US equity option contracts (which represent 100 shares per contract), either multiply the option quote by 100 (for example, 7 contracts quoted at $2.51 ="SOXL 105C 20NOV26:7@251.00") or report total option market value as"Options:1@1757.00". - For standard US stock tickers tracked in IBridgePy's daily market database, the server prioritizes the official market closing price and falls back to your inline
@PRICEif a ticker is not in the database. - If your portfolio is 100% cash on a given day, pass
"positions": []and yourtotal_valuewill equalcash.
Step 3: Complete Python Script (update_portfolio.py)
Save the script below as update_portfolio.py. It skips weekends automatically, uses US Eastern time for the trading date, retries transient network hiccups, and prints the verified total NAV returned by the server.
from __future__ import annotations
import datetime as dt
import os
import time
from zoneinfo import ZoneInfo
import requests
API_URL = "https://ibridgepy.com/portfolio/snapshot/"
STRATEGY_SLUG = "digitalshare-lab-dlab" # Replace with your own strategy slug
EASTERN = ZoneInfo("America/New_York")
def upload_daily_snapshot(
strategy: str,
cash: float,
positions: list[str],
action: str = "",
trading_date: str | None = None,
api_key: str | None = None,
max_retries: int = 3,
) -> dict:
"""Publish or update a single day's portfolio snapshot on IBridgePy."""
api_key = api_key or os.environ.get("IBRIDGEPY_API_KEY")
if not api_key:
raise RuntimeError(
"Missing IBRIDGEPY_API_KEY. Set it as an environment variable "
"using the API Key from https://ibridgepy.com/home/."
)
if trading_date is None:
now_et = dt.datetime.now(EASTERN)
if now_et.weekday() >= 5:
print(f"Skipping weekend date {now_et.date()} (market closed).")
return {}
trading_date = now_et.date().isoformat()
payload = {
"strategy": strategy,
"date": trading_date,
"cash": round(float(cash), 2),
"positions": positions,
"action": action[:500],
}
headers = {
"Content-Type": "application/json",
"X-API-Key": api_key,
}
for attempt in range(1, max_retries + 1):
try:
resp = requests.post(API_URL, json=payload, headers=headers, timeout=20)
if resp.status_code in (200, 201):
result = resp.json()
verb = "Created" if resp.status_code == 201 else "Updated"
print(
f"[{verb}] {strategy} | {result['date']} | "
f"NAV: ${result['total_value']:,.2f} | Cash: ${result['cash']:,.2f}"
)
return result
if resp.status_code in (400, 401, 403):
# Client/auth errors will not succeed on retry
raise RuntimeError(f"API error {resp.status_code}: {resp.text}")
resp.raise_for_status()
except requests.RequestException as exc:
if attempt == max_retries:
raise
wait_sec = 2 ** attempt
print(f"Attempt {attempt} failed ({exc}); retrying in {wait_sec}s...")
time.sleep(wait_sec)
def get_todays_portfolio_numbers() -> tuple[float, list[str], str]:
"""Replace this function with your broker API, CSV parser, or database query."""
cash = 1007445.87
stocks_value = 21793.20
options_value = 40217.01
etfs_value = 4322.00
positions = []
if stocks_value:
positions.append(f"Stocks:1@{stocks_value:.2f}")
if options_value:
positions.append(f"Options:1@{options_value:.2f}")
if etfs_value:
positions.append(f"ETFs:1@{etfs_value:.2f}")
equities_total = stocks_value + options_value + etfs_value
action = f"Equities: ${equities_total:,.2f} | Cash: ${cash:,.2f}"
return cash, positions, action
if __name__ == "__main__":
cash, positions, action = get_todays_portfolio_numbers()
upload_daily_snapshot(
strategy=STRATEGY_SLUG,
cash=cash,
positions=positions,
action=action,
)
Test Your Script Locally First
Set your API key in your terminal (never hardcode it inside a committed script) and run it once:
# Linux / macOS
export IBRIDGEPY_API_KEY="your-api-key-from-ibridgepy-home"
python3 update_portfolio.py
# Windows PowerShell
$env:IBRIDGEPY_API_KEY="your-api-key-from-ibridgepy-home"
python update_portfolio.py
You should see output confirming the upload:
[Created] digitalshare-lab-dlab | 2026-12-01 | NAV: $1,073,778.08 | Cash: $1,007,445.87
Step 4 (Optional): Push Directly from Your Live IBridgePy / Interactive Brokers Strategy
If your strategy already runs in IBridgePy connected to Interactive Brokers (TWS or IB Gateway), you can schedule the upload right inside initialize(context) to run automatically every day right before or at market close:
import os
import requests
def initialize(context):
context.strategy_slug = "digitalshare-lab-dlab"
# Upload portfolio snapshot every trading day 1 minute before market close
schedule_function(
push_daily_snapshot,
date_rules.every_day(),
time_rules.market_close(minutes=1),
)
def push_daily_snapshot(context, data):
cash = float(context.portfolio.cash)
positions_list = []
holdings_value = 0.0
for security, pos in get_all_positions().items():
if pos.amount == 0:
continue
# For stocks/ETFs, IBridgePy server can auto-price TICKER:QTY,
# or include @PRICE for exact broker mark-to-market valuation.
price = float(data.current(security, "price"))
qty = int(pos.amount)
multiplier = 100.0 if security.secType == "OPT" else 1.0
unit_value = round(price * multiplier, 2)
positions_list.append(f"{security.symbol}:{qty}@{unit_value:.2f}")
holdings_value += qty * unit_value
payload = {
"strategy": context.strategy_slug,
"date": get_datetime("US/Eastern").strftime("%Y-%m-%d"),
"cash": round(cash, 2),
"positions": positions_list,
"action": f"Holdings: ${holdings_value:,.2f} | Cash: ${cash:,.2f}",
}
resp = requests.post(
"https://ibridgepy.com/portfolio/snapshot/",
json=payload,
headers={"X-API-Key": os.environ["IBRIDGEPY_API_KEY"]},
timeout=20,
)
resp.raise_for_status()
print("IBridgePy Portfolio updated:", resp.json())
Step 5: Run It Automatically Every Trading Day
Schedule your script to run Monday through Friday between 4:15 PM and 5:00 PM US Eastern Time, once your broker's end-of-day balances have settled. Choose whichever scheduler fits your setup:
Step 6: Verify Your Update Programmatically
You can confirm your latest snapshot is live either by refreshing your portfolio page in a browser or by querying your strategy's public JSON data endpoint:
import requests
url = "https://ibridgepy.com/portfolio/wtxrc21m/digitalshare-lab-dlab/data/"
snapshots = requests.get(url, timeout=15).json()
print("Total trading days recorded:", len(snapshots))
print("Latest snapshot:", snapshots[-1])
Frequently Asked Questions & Troubleshooting
Want to Track Your Own Strategy on IBridgePy Portfolio?
Explore live community strategies, grab your personal API key, or reach out to IBridgePy@gmail.com to onboard your strategy page.