06/03 Optimize codes, Schwab account
This commit is contained in:
@@ -6,6 +6,9 @@ class Investment(db.Model):
|
||||
__tablename__ = 'investments'
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
# Optional link to a PFM account (e.g. Schwab Individual, Schwab Roth IRA).
|
||||
# NULL means the holding is not tied to a specific account.
|
||||
account_id = db.Column(db.Integer, db.ForeignKey('accounts.id'), nullable=True, index=True)
|
||||
asset_name = db.Column(db.String(100), nullable=False)
|
||||
ticker = db.Column(db.String(20), nullable=True)
|
||||
asset_type = db.Column(
|
||||
@@ -22,6 +25,7 @@ class Investment(db.Model):
|
||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
account = db.relationship('Account', foreign_keys=[account_id])
|
||||
inv_transactions = db.relationship('InvestmentTransaction', back_populates='investment',
|
||||
lazy='dynamic', cascade='all, delete-orphan')
|
||||
|
||||
|
||||
@@ -324,8 +324,16 @@ def update_prices(investment_ids=None):
|
||||
|
||||
|
||||
def get_portfolio_summary():
|
||||
"""Return portfolio-level aggregates across all active investments."""
|
||||
investments = Investment.query.filter_by(is_active=True).all()
|
||||
"""
|
||||
Return portfolio-level aggregates across all active investments.
|
||||
Also returns per-account groups for investments that are linked to an account
|
||||
(e.g. separate Schwab Individual vs Roth IRA views).
|
||||
"""
|
||||
investments = Investment.query.filter_by(is_active=True).order_by(
|
||||
Investment.account_id.asc().nullslast(),
|
||||
Investment.asset_type,
|
||||
Investment.asset_name,
|
||||
).all()
|
||||
|
||||
total_cost = sum(i.total_cost for i in investments)
|
||||
total_value = sum(i.current_value for i in investments)
|
||||
@@ -348,6 +356,31 @@ def get_portfolio_summary():
|
||||
'color': ASSET_COLORS.get(asset_type, '#94a3b8'),
|
||||
})
|
||||
|
||||
# Build per-account groups (only for investments with account_id set)
|
||||
account_groups = {} # account_id (or None) → {'account': Account|None, 'investments': [...]}
|
||||
for inv in investments:
|
||||
key = inv.account_id
|
||||
if key not in account_groups:
|
||||
account_groups[key] = {
|
||||
'account': inv.account, # Account object or None
|
||||
'investments': [],
|
||||
'total_value': 0,
|
||||
'total_cost': 0,
|
||||
}
|
||||
account_groups[key]['investments'].append(inv)
|
||||
account_groups[key]['total_value'] += inv.current_value
|
||||
account_groups[key]['total_cost'] += inv.total_cost
|
||||
|
||||
# Sort: named accounts first (sorted by name), then unlinked holdings last
|
||||
sorted_groups = sorted(
|
||||
account_groups.values(),
|
||||
key=lambda g: (g['account'] is None, g['account'].name if g['account'] else ''),
|
||||
)
|
||||
|
||||
# Only return groups if there's more than one distinct account present
|
||||
multi_account = len([g for g in sorted_groups if g['account'] is not None]) > 1 or \
|
||||
(len(sorted_groups) > 1)
|
||||
|
||||
return {
|
||||
'investments': investments,
|
||||
'total_cost': total_cost,
|
||||
@@ -356,4 +389,5 @@ def get_portfolio_summary():
|
||||
'total_gain_pct': total_gain_pct,
|
||||
'allocation': allocation,
|
||||
'count': len(investments),
|
||||
'account_groups': sorted_groups if multi_account else [],
|
||||
}
|
||||
|
||||
@@ -264,7 +264,13 @@ def sync_account_snapshot(schwab_account):
|
||||
market_value = float(pos.get('marketValue') or 0)
|
||||
cur_price = round(market_value / long_qty, 4) if long_qty > 0 else avg_price
|
||||
|
||||
inv = Investment.query.filter_by(ticker=symbol, is_active=True).first()
|
||||
pfm_acct_id = schwab_account.pfm_account_id
|
||||
|
||||
# Match on (ticker, account_id) so the same ticker in different accounts
|
||||
# (e.g. AAPL in Individual vs Roth IRA) remains separate.
|
||||
inv = Investment.query.filter_by(
|
||||
ticker=symbol, account_id=pfm_acct_id, is_active=True
|
||||
).first()
|
||||
if inv:
|
||||
inv.shares = long_qty
|
||||
if avg_price > 0:
|
||||
@@ -274,6 +280,7 @@ def sync_account_snapshot(schwab_account):
|
||||
else:
|
||||
name = (instrument.get('description') or symbol).strip()
|
||||
inv = Investment(
|
||||
account_id = pfm_acct_id,
|
||||
asset_name = name,
|
||||
ticker = symbol,
|
||||
asset_type = pfm_type,
|
||||
|
||||
@@ -132,6 +132,95 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{# ── Reusable holdings table macro ──────────────────────────────────────── #}
|
||||
{% macro holdings_table(inv_list) %}
|
||||
<table class="pfm-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="padding-left:20px;">Asset</th>
|
||||
<th class="text-end">Price</th>
|
||||
<th class="text-end d-mob-none">1D Chg</th>
|
||||
<th class="text-end">Value</th>
|
||||
<th class="text-end" style="padding-right:8px;">P&L</th>
|
||||
<th style="width:36px;"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for inv in inv_list %}
|
||||
<tr id="row-{{ inv.id }}" style="cursor:pointer;"
|
||||
onclick="location.href='{{ url_for('investments.detail', id=inv.id) }}'">
|
||||
<td style="padding-left:20px;">
|
||||
<div class="d-flex align-items-center gap-2">
|
||||
<div style="width:28px;height:28px;border-radius:7px;background:{{ asset_colors.get(inv.asset_type,'#94a3b8') }}22;color:{{ asset_colors.get(inv.asset_type,'#94a3b8') }};display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:700;">
|
||||
{{ (inv.ticker or inv.asset_name[:2]).upper()[:2] }}
|
||||
</div>
|
||||
<div>
|
||||
<div style="font-size:13px;font-weight:500;">{{ inv.asset_name }}</div>
|
||||
<div style="font-size:11px;color:var(--muted);">
|
||||
{% if inv.ticker %}<span class="mono">{{ inv.ticker }}</span> · {% endif %}
|
||||
{{ asset_labels.get(inv.asset_type, inv.asset_type) }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td class="text-end">
|
||||
{% if inv.current_price %}
|
||||
<span class="mono" style="font-size:12px;">{{ inv.current_price | currency }}</span>
|
||||
{% else %}
|
||||
<span class="text-muted" style="font-size:12px;">—</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td class="text-end d-mob-none" id="chg-{{ inv.id }}">
|
||||
{% if inv.ticker %}<span class="chg-badge chg-loading">…</span>
|
||||
{% else %}<span class="text-muted" style="font-size:12px;">—</span>{% endif %}
|
||||
</td>
|
||||
<td class="text-end mono" style="font-size:13px;font-weight:600;">{{ inv.current_value | currency }}</td>
|
||||
<td class="text-end" style="padding-right:8px;">
|
||||
<div class="mono {% if inv.unrealized_gain >= 0 %}text-income{% else %}text-expense{% endif %}" style="font-size:12px;font-weight:600;">
|
||||
{% if inv.unrealized_gain >= 0 %}+{% endif %}{{ inv.unrealized_gain | currency }}
|
||||
</div>
|
||||
<div style="font-size:10px;color:var(--muted);">
|
||||
{% if inv.unrealized_gain_pct >= 0 %}+{% endif %}{{ inv.unrealized_gain_pct }}%
|
||||
</div>
|
||||
</td>
|
||||
<td onclick="event.stopPropagation();" style="padding:0 8px;">
|
||||
{% if inv.ticker %}
|
||||
<button class="expand-btn" id="expand-{{ inv.id }}"
|
||||
onclick="toggleChart({{ inv.id }}, '{{ inv.ticker }}', '{{ asset_colors.get(inv.asset_type,'#3b82f6') }}')"
|
||||
title="Show price chart">
|
||||
<i class="bi bi-bar-chart-line" style="font-size:14px;"></i>
|
||||
</button>
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
{% if inv.ticker %}
|
||||
<tr class="chart-row" id="chart-row-{{ inv.id }}" style="display:none;">
|
||||
<td colspan="6">
|
||||
<div class="chart-panel" id="chart-panel-{{ inv.id }}">
|
||||
<div class="d-flex align-items-center gap-2 flex-wrap">
|
||||
<span style="font-size:13px;font-weight:600;color:var(--text);">{{ inv.asset_name }}</span>
|
||||
<span class="mono text-muted" style="font-size:11px;">{{ inv.ticker }}</span>
|
||||
<span id="chart-chg-{{ inv.id }}" class="chg-badge chg-flat" style="display:none;"></span>
|
||||
<div class="ms-auto d-flex gap-1 flex-wrap">
|
||||
{% for tf in ['1W','1M','3M','6M','1Y'] %}
|
||||
<button class="tf-btn{% if tf == '1M' %} active{% endif %}"
|
||||
onclick="loadChart({{ inv.id }}, '{{ inv.ticker }}', '{{ tf }}', '{{ asset_colors.get(inv.asset_type,'#3b82f6') }}')">
|
||||
{{ tf }}
|
||||
</button>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-meta mt-1" id="chart-info-{{ inv.id }}">Loading…</div>
|
||||
<div class="chart-wrap"><canvas id="canvas-{{ inv.id }}"></canvas></div>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
{% endmacro %}
|
||||
|
||||
<!-- Chart + Allocation -->
|
||||
<div class="row g-3 mb-4">
|
||||
<div class="col-12 col-lg-4">
|
||||
@@ -154,110 +243,45 @@
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{# Per-account balance breakdown #}
|
||||
{% if portfolio.account_groups %}
|
||||
<div class="mt-3 pt-2" style="border-top:1px solid var(--border);">
|
||||
<div style="font-size:11px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.05em;margin-bottom:6px;">By Account</div>
|
||||
{% for grp in portfolio.account_groups %}
|
||||
<div class="d-flex justify-content-between py-1">
|
||||
<span style="font-size:12px;">{{ grp.account.name if grp.account else 'Unlinked' }}</span>
|
||||
<span class="mono text-invest" style="font-size:12px;font-weight:600;">{{ grp.total_value | currency }}</span>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Holdings table -->
|
||||
<!-- Holdings: one section per account when multi-account, single table otherwise -->
|
||||
<div class="col-12 col-lg-8">
|
||||
{% if portfolio.account_groups %}
|
||||
{% for grp in portfolio.account_groups %}
|
||||
<div class="pcard p-0 {% if not loop.last %}mb-3{% endif %}">
|
||||
<div class="d-flex justify-content-between align-items-center px-4 py-3" style="border-bottom:1px solid var(--border);">
|
||||
<div class="d-flex align-items-center gap-3">
|
||||
<span class="pcard-title mb-0">{{ grp.account.name if grp.account else 'Unlinked Holdings' }}</span>
|
||||
<span class="mono text-invest" style="font-size:14px;font-weight:700;">{{ grp.total_value | currency }}</span>
|
||||
</div>
|
||||
<span class="text-muted" style="font-size:11px;">{{ grp.investments | length }} holding(s)</span>
|
||||
</div>
|
||||
{{ holdings_table(grp.investments) }}
|
||||
</div>
|
||||
{% endfor %}
|
||||
{% else %}
|
||||
<div class="pcard p-0 h-100">
|
||||
<div class="d-flex justify-content-between align-items-center px-4 py-3" style="border-bottom:1px solid var(--border);">
|
||||
<span class="pcard-title mb-0">Holdings</span>
|
||||
<span class="text-muted" style="font-size:11px;">Click <i class="bi bi-bar-chart-line"></i> to expand price chart</span>
|
||||
</div>
|
||||
<table class="pfm-table" id="holdingsTable">
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="padding-left:20px;">Asset</th>
|
||||
<th class="text-end">Price</th>
|
||||
<th class="text-end d-mob-none">1D Chg</th>
|
||||
<th class="text-end">Value</th>
|
||||
<th class="text-end" style="padding-right:8px;">P&L</th>
|
||||
<th style="width:36px;"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for inv in portfolio.investments %}
|
||||
{# Main holding row #}
|
||||
<tr id="row-{{ inv.id }}" style="cursor:pointer;"
|
||||
onclick="location.href='{{ url_for('investments.detail', id=inv.id) }}'">
|
||||
<td style="padding-left:20px;">
|
||||
<div class="d-flex align-items-center gap-2">
|
||||
<div style="width:28px;height:28px;border-radius:7px;background:{{ asset_colors.get(inv.asset_type,'#94a3b8') }}22;color:{{ asset_colors.get(inv.asset_type,'#94a3b8') }};display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:700;">
|
||||
{{ (inv.ticker or inv.asset_name[:2]).upper()[:2] }}
|
||||
</div>
|
||||
<div>
|
||||
<div style="font-size:13px;font-weight:500;">{{ inv.asset_name }}</div>
|
||||
<div style="font-size:11px;color:var(--muted);">
|
||||
{% if inv.ticker %}<span class="mono">{{ inv.ticker }}</span> · {% endif %}
|
||||
{{ asset_labels.get(inv.asset_type, inv.asset_type) }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td class="text-end">
|
||||
{% if inv.current_price %}
|
||||
<span class="mono" style="font-size:12px;">{{ inv.current_price | currency }}</span>
|
||||
{% else %}
|
||||
<span class="text-muted" style="font-size:12px;">—</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td class="text-end d-mob-none" id="chg-{{ inv.id }}">
|
||||
{% if inv.ticker %}
|
||||
<span class="chg-badge chg-loading">…</span>
|
||||
{% else %}
|
||||
<span class="text-muted" style="font-size:12px;">—</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td class="text-end mono" style="font-size:13px;font-weight:600;">{{ inv.current_value | currency }}</td>
|
||||
<td class="text-end" style="padding-right:8px;">
|
||||
<div class="mono {% if inv.unrealized_gain >= 0 %}text-income{% else %}text-expense{% endif %}" style="font-size:12px;font-weight:600;">
|
||||
{% if inv.unrealized_gain >= 0 %}+{% endif %}{{ inv.unrealized_gain | currency }}
|
||||
</div>
|
||||
<div style="font-size:10px;color:var(--muted);">
|
||||
{% if inv.unrealized_gain_pct >= 0 %}+{% endif %}{{ inv.unrealized_gain_pct }}%
|
||||
</div>
|
||||
</td>
|
||||
<td onclick="event.stopPropagation();" style="padding:0 8px;">
|
||||
{% if inv.ticker %}
|
||||
<button class="expand-btn" id="expand-{{ inv.id }}"
|
||||
onclick="toggleChart({{ inv.id }}, '{{ inv.ticker }}', '{{ asset_colors.get(inv.asset_type,'#3b82f6') }}')"
|
||||
title="Show price chart">
|
||||
<i class="bi bi-bar-chart-line" style="font-size:14px;"></i>
|
||||
</button>
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
{# Hidden chart row for this holding #}
|
||||
{% if inv.ticker %}
|
||||
<tr class="chart-row" id="chart-row-{{ inv.id }}" style="display:none;">
|
||||
<td colspan="6">
|
||||
<div class="chart-panel" id="chart-panel-{{ inv.id }}">
|
||||
<div class="d-flex align-items-center gap-2 flex-wrap">
|
||||
<span style="font-size:13px;font-weight:600;color:var(--text);">{{ inv.asset_name }}</span>
|
||||
<span class="mono text-muted" style="font-size:11px;">{{ inv.ticker }}</span>
|
||||
<span id="chart-chg-{{ inv.id }}" class="chg-badge chg-flat" style="display:none;"></span>
|
||||
<div class="ms-auto d-flex gap-1 flex-wrap">
|
||||
{% for tf in ['1W','1M','3M','6M','1Y'] %}
|
||||
<button class="tf-btn{% if tf == '1M' %} active{% endif %}"
|
||||
onclick="loadChart({{ inv.id }}, '{{ inv.ticker }}', '{{ tf }}', '{{ asset_colors.get(inv.asset_type,'#3b82f6') }}')">
|
||||
{{ tf }}
|
||||
</button>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-meta mt-1" id="chart-info-{{ inv.id }}">Loading…</div>
|
||||
<div class="chart-wrap">
|
||||
<canvas id="canvas-{{ inv.id }}"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
{{ holdings_table(portfolio.investments) }}
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Migration: add account_id to investments table.
|
||||
Run once: python scripts/add_investment_account.py
|
||||
Safe to re-run — skips if the column already exists.
|
||||
"""
|
||||
import sys, os
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from app import create_app
|
||||
from app.extensions import db
|
||||
|
||||
app = create_app()
|
||||
|
||||
with app.app_context():
|
||||
with db.engine.connect() as conn:
|
||||
# Check if column already exists
|
||||
result = conn.execute(db.text(
|
||||
"SELECT COUNT(*) FROM information_schema.columns "
|
||||
"WHERE table_schema = DATABASE() "
|
||||
"AND table_name = 'investments' "
|
||||
"AND column_name = 'account_id'"
|
||||
))
|
||||
exists = result.scalar()
|
||||
|
||||
if exists:
|
||||
print("Column investments.account_id already exists — nothing to do.")
|
||||
else:
|
||||
conn.execute(db.text(
|
||||
"ALTER TABLE investments "
|
||||
"ADD COLUMN account_id INT NULL DEFAULT NULL, "
|
||||
"ADD INDEX ix_investments_account_id (account_id), "
|
||||
"ADD CONSTRAINT fk_investments_account_id "
|
||||
" FOREIGN KEY (account_id) REFERENCES accounts(id) "
|
||||
" ON DELETE SET NULL"
|
||||
))
|
||||
conn.commit()
|
||||
print("Added investments.account_id column successfully.")
|
||||
Reference in New Issue
Block a user