SuperAPI AI Directory

stock-portfolio

Data & analytics

View repository

Updated 10-15 20:04

About this skill

Portfolio Management Skill

Parse $ARGUMENTS to determine the command, and execute the following command.

Executable Commands

python3 /Users/kikuchihiroyuki/stock-skills/.claude/skills/stock-portfolio/scripts/run_portfolio.py <command> [args]

Command List

snapshot -- PF Snapshot

Generate a snapshot of the portfolio including current prices, profit/loss, and currency conversion.

python3 .../run_portfolio.py snapshot

buy -- Add Purchase Record

python3 .../run_portfolio.py buy --symbol <sym> --shares <n> --price <p> [--currency JPY] [--date YYYY-MM-DD] [--memo テキスト] [--yes]

--yes (-y) is omitted, a confirmation preview of the purchase details is displayed and the process ends.--yes is specified, the confirmation is skipped and the record is saved directly (KIK-444).

sell -- Sale Record

python3 .../run_portfolio.py sell --symbol <sym> --shares <n> [--price <売却単価>] [--date YYYY-MM-DD] [--yes]

--yes (-y) is omitted, a confirmation preview of the sale details (acquisition price, estimated realized profit/loss) is displayed and the process ends.--yes is specified, the confirmation is skipped and the record is saved directly (KIK-444).

--price is specified, the realized profit/loss, return rate, and after-tax estimate are calculated and displayed, and saved todata/history/trade/*.json (KIK-441).

review -- Trading Performance Review (KIK-441)

Aggregate and display profit/loss statistics from past sale records (those recorded with--price attached).

python3 .../run_portfolio.py review [--year 2026] [--symbol NVDA]

Output Contents:

  • Transaction history table (ticker, sale date, number of shares, acquisition price, sale price, holding days, realized profit/loss, return rate)
  • Statistics (number of transactions, win rate, average return, average holding period, total realized profit/loss)

analyze -- Structural Analysis

Calculate the HHI (Herfindahl-Hirschman Index) for region/sector/currency/size, and analyze portfolio bias. Four-axis analysis including a size breakdown table (large/mid/small/ETF/unknown) (KIK-438, KIK-469 P2: ETF classification). ETFs are independently classified with sector "ETF" and size "ETF".

python3 .../run_portfolio.py analyze

health -- Health Check

Check whether the investment thesis for held tickers is still valid. Outputs three-tier alerts across multiple axes: technical (SMA50/200, RSI, golden cross/death cross detection) and fundamental (change score,shareholder return stability).Small-cap stocks automatically have their sensitivity raised(KIK-438)。

python3 .../run_portfolio.py health

Technical Analysis (KIK-356/374/438):

  • SMA50/200 trend determination (rising/flat/falling)
  • Golden cross/death cross detection: Detect cross events with a 60-day lookback, and display the occurrence date and elapsed days
  • Shortened cross lookback for small-cap stocks (KIK-438): For small-cap stocks, use lookback=30 days to detect recent movements early

Shareholder Return Stability (KIK-403):

  • Evaluate stability from the total payout ratio of dividends + share buybacks (✅ Stable high return/📈 Increasing trend/⚠️ Temporary high return/📉 Decreasing trend)
  • Temporary high return (temporary) → Promoted to early warning
  • Decreasing trend (decreasing) → Add reason to alert details
  • Use total return rate (dividends + buybacks) for long-term suitability assessment

Small-cap allocation (KIK-438):

  • Classify each stock by market cap into size categories (large/mid/small/unknown) and [小型] display a badge
  • Small caps automatically escalate from EARLY_WARNING → CAUTION
  • Calculate the small-cap ratio for the entire PF; show a warning if >25%, and danger if >35%

ETF health check (KIK-469 Phase 2):

  • Display individual stocks and ETFs in separate tables
  • ETF table: ticker/P&L/trend/expense ratio/AUM/ETF score/alerts
  • Individual stock table: as before (quality of change/long-term suitability/dividend stability)

Alert levels:

  • Early warning: SMA50 break / sharp RSI drop / deterioration in one change score indicator / Temporary high payout
  • Caution: SMA50 approaching SMA200 + indicator deterioration / deterioration in multiple change score indicators / Promotion of small caps to EARLY_WARNING
  • Exit: Death cross detected / trend collapse + change score deterioration

adjust -- portfolio adjustment advisor (KIK-496)

Based on health check results + market regime determination, generate specific adjustment actions (SELL/SWAP/ADD/TRIM_CLASS/FLAG) using 17 rules (P1-P10: per position, F1-F7: entire PF).

python3 .../run_portfolio.py adjust [--full]

CLI options:

  • --full : full analysis mode (includes concentration and correlation analysis; high API load)

Output:

  • Market regime (bull/bear/crash/neutral) — determined from SMA50/200, RSI, and drawdown
  • Action table by HIGH/MEDIUM/LOW priority (action type/target/reason/rule ID)
  • Summary (number of actions)

Regime adjustment: During crash, raise urgency by one level. During bear, raise small-cap and downtrend-related rules.

rebalance -- rebalancing proposal

Analyze the current portfolio structure and present proposals for reducing concentration risk and adjusting toward target allocations.

python3 .../run_portfolio.py rebalance [options]

CLI options:

  • --strategy defensive|balanced|aggressive (default: balanced)
  • --reduce-sector SECTOR (e.g.: Technology)
  • --reduce-currency CURRENCY (e.g.: USD)
  • --max-single-ratio RATIO (e.g.: 0.15)
  • --max-sector-hhi HHI (e.g.: 0.25)
  • --max-region-hhi HHI (e.g.: 0.30)
  • --additional-cash AMOUNT (JPY, e.g.: 1000000)
  • --min-dividend-yield YIELD (e.g.: 0.03)

forecast -- estimated yield

For each held stock, estimate the 12-month expected return in 3 scenarios (optimistic/base/pessimistic) from analyst target prices or past return distributions. Includes value trap warnings and TOP/BOTTOM rankings.

python3 .../run_portfolio.py forecast

Estimation methods:

  • Analyst method: analyst target price + dividend yield + buyback yield (including shareholder returns)
  • Past return method: For stocks without analyst coverage such as ETFs, estimate using past CAGR + standard deviation (KIK-469 P2: ETFs show annualized volatility + [ETF] with badge)
  • Industry catalyst adjustment(KIK-433, when Neo4j is connected): same sector's most recent growth_driver catalyst count × 1.7% added to the optimistic scenario,risk catalyst count × 1.7% subtracted from the pessimistic scenario (each capped at 10%)

Output structure (KIK-390):

  1. Three-scenario yield/profit-loss amount table for the entire portfolio
  2. Caution stock section (aggregates stocks with value trap warnings)
  3. Expected return TOP 3 / BOTTOM 3 ranking
  4. Per-stock details (analyst target/Forward PER/news count/X sentiment/3 scenarios)

what-if -- What-If simulation (KIK-376 / KIK-451)

Simulate adding, selling, or swapping stocks, and display the impact on the portfolio with a Before/After comparison.

# 追加のみ(従来)
python3 .../run_portfolio.py what-if --add "SYMBOL:SHARES:PRICE[,...]"

# スワップ(売却して購入)(KIK-451)
python3 .../run_portfolio.py what-if --remove "SYMBOL:SHARES[,...]" --add "SYMBOL:SHARES:PRICE[,...]"

# 売却のみシミュレーション (KIK-451)
python3 .../run_portfolio.py what-if --remove "SYMBOL:SHARES[,...]"

CLI options:

  • --add : List of stocks to add (optional). Format: SYMBOL:SHARES:PRICE separated by commas
  • --remove : List of stocks to sell (optional). Format: SYMBOL:SHARES separated by commas (no price needed; estimated at market value)
  • --add と --remove At least one of these is required

Output:

  • [When selling] Context of sell candidates (KIK-470): --remove When specified, automatically displays screening appearance count, investment notes, and research history before simulation (when Neo4j is connected)
  • Before/After sector HHI, region HHI, currency HHI comparison
  • Basic information of added stocks (PER/PBR/dividend yield/ROE)
  • [When swapping] Sell stock table(stock, shares, estimated sale proceeds)
  • [When swapping] Cash flow(funds required for purchase / estimated sale proceeds / difference)
  • [When swapping] Sell stock health check(alert status of sell targets)
  • Judgment label: Recommended / Consider with caution / Not recommended (when swapping, e.g. "This swap is recommended")
  • ETF quality evaluation (KIK-469 P2): Reflect ETF score in judgment when adding ETFs (warning when quality good ≥75, quality low <40)

backtest -- Backtest

Verify returns from accumulated screening results and compare with benchmarks (Nikkei 225/S&P 500).

python3 .../run_portfolio.py backtest [options]

CLI options:

  • --preset PRESET : Screening preset to verify (e.g. alpha, value)
  • --region REGION : Region to verify (e.g. jp, us)
  • --days N : Verify returns for N days after acquisition (default: 90)

Output:

  • Average return by screening date
  • Benchmark comparison (excess return)
  • Win rate, average return, maximum return/maximum loss

simulate -- Compound simulation

Based on the current portfolio, simulate the future asset trajectory with compound interest calculation. Calculate the expected return from forecast + dividend reinvestment + monthly contributions with compound interest, and display in 3 scenarios: optimistic/base/pessimistic.

python3 .../run_portfolio.py simulate [options]

CLI options:

  • --years N (simulation years, default: 10)
  • --monthly-add AMOUNT (monthly contribution amount, yen, default: 0)
  • --target AMOUNT (target amount, yen, example: 15000000)
  • --reinvest-dividends (reinvest dividends, default: ON)
  • --no-reinvest-dividends (do not reinvest dividends)

list -- list of holdings

Display the contents of portfolio.csv as is.

python3 .../run_portfolio.py list

Natural language routing

For natural language → skill determination, refer to .claude/rules/intent-routing.md .

Constraints

  • Japanese stocks: 100-share units (trading units)
  • ASEAN stocks: 100-share units (minimum commission 3,300 yen)
  • Rakuten Securities support (commission structure)
  • Path of portfolio.csv: .claude/skills/stock-portfolio/data/portfolio.csv

Output

Display results in Markdown format.

snapshot output items

  • Ticker / Name / Shares held / Acquisition price / Current price / Market value / Profit/Loss / Profit/Loss ratio / Currency

analyze output items

  • Sector HHI / Region HHI / Currency HHI / Size HHI (KIK-438)
  • Composition ratio of each axis (Size composition table: Large/Mid/Small/ETF/Unknown)
  • ETF annotation (note that look-through is not supported)
  • Risk level assessment

health output items

  • Individual stock table: Ticker (Small-cap stocks have a [小型] badge) / Profit/Loss ratio / Trend / Cross event / Quality of change / Alert / Long-term suitability / Return stability
  • ETF table (KIK-469 P2): Ticker / Profit/Loss / Trend / Expense ratio / AUM / ETF score / Alert
  • Details of stocks with alerts (reason, SMA/RSI values, cross occurrence date/days elapsed, change score, shareholder return stability, recommended action)
  • Small-cap allocation: Summary of small-cap ratio in the overall PF (✅Normal/⚠️Warning/🔴Danger)

forecast output items

  • Overall portfolio: 3-scenario yield (optimistic/base/pessimistic) + profit/loss amount + total market value
  • Caution stocks section: List of stocks with value trap warnings
  • TOP 3 / BOTTOM 3: Expected return ranking (with number of analysts)
  • By stock: Analyst target price / Forward PER / Number of news items / X sentiment / 3 scenarios / For ETFs, annualized volatility + [ETF] badge

what-if output items

  • [When selling] Context of sell candidates (KIK-470): Screening appearance count, investment notes, research history
  • Before/After HHI comparison (sector/region/currency)
  • Fundamentals of additional holdings
  • Determination of concentration changes
  • [At swap] Sell holdings table (estimated sale proceeds)
  • [At swap] Cash flow (funds required for purchase / sale proceeds / difference)
  • [At swap] Sell holdings health check
  • [At swap] "This swap is recommended / consider with caution / not recommended"

backtest output items

  • Returns by screening date
  • Benchmark comparison (excess return)
  • Win rate and statistics

adjust output items

  • Market regime (regime name/SMA50 vs SMA200/RSI/drawdown)
  • HIGH Priority table: SELL/SWAP/TRIM_CLASS actions
  • MEDIUM Priority table: FLAG/SELL actions
  • LOW Priority table: FLAG actions
  • Summary (HIGH/MEDIUM/LOW counts, regime)

rebalance output items

  • Current HHI (sector/region/currency) and target HHI
  • Sell candidates (ticker, shares, reason)
  • Buy candidates (ticker, shares, reason, dividend yield)
  • Projected HHI after rebalancing

simulate output items

  • Annual trend table (year/valuation amount/cumulative contributions/investment gains/cumulative dividends)
  • 3-scenario comparison (optimistic/base/pessimistic final year)
  • Goal achievement analysis (year reached/required contribution amount)
  • Compounding effect of dividend reinvestment

Execution example

# スナップショット
python3 .../run_portfolio.py snapshot

# 購入記録
python3 .../run_portfolio.py buy --symbol 7203.T --shares 100 --price 2850 --currency JPY --date 2025-06-15 --memo トヨタ

# 売却記録
python3 .../run_portfolio.py sell --symbol AAPL --shares 5

# 構造分析
python3 .../run_portfolio.py analyze

# 一覧表示
python3 .../run_portfolio.py list

# ヘルスチェック
python3 .../run_portfolio.py health

# 推定利回り
python3 .../run_portfolio.py forecast

# リバランス提案
python3 .../run_portfolio.py rebalance
python3 .../run_portfolio.py rebalance --strategy defensive
python3 .../run_portfolio.py rebalance --reduce-sector Technology --additional-cash 1000000

# What-Ifシミュレーション(追加のみ)
python3 .../run_portfolio.py what-if --add "7203.T:100:2850,AAPL:10:250"

# What-Ifシミュレーション(スワップ: 7203.T売却 → 9984.T購入)(KIK-451)
python3 .../run_portfolio.py what-if --remove "7203.T:100" --add "9984.T:50:7500"

# What-Ifシミュレーション(純売却)(KIK-451)
python3 .../run_portfolio.py what-if --remove "7203.T:50"

# 調整アドバイザー (KIK-496)
python3 .../run_portfolio.py adjust
python3 .../run_portfolio.py adjust --full

# バックテスト
python3 .../run_portfolio.py backtest --preset alpha --region jp --days 90

Prior knowledge integration rules (KIK-466)

health command

If the output of get_context.py contains the following, respond by integrating it with the health check results:

  • Trade history (BOUGHT/SOLD): Refer to purchase price and date, and add context on unrealized gains/losses. If a sold holding appears in a warning, explicitly state "No issue since it has been sold"
  • Investment notes (Note): If there are thesis or concern notes, cross-check them with the health check results. E.g., "Value trap concern note present → BT score high again this time → truly requires caution"
  • Previous health check (HealthCheck): Show the difference from the previous time. "Previous HOLD → current EXIT: situation worsening" "Previous EXIT → current HOLD: improvement"
  • Screening history (SURFACED): If a warned holding was previously ranked high in screening, e.g., "Attention level is high (ranked high 3 times) but currently requires caution"
  • Thesis progress: If the thesis note is 90 days or older, prompt "Time to review the thesis"

snapshot / forecast

  • If there is a previous snapshot or forecast, add a difference comment
  • E.g., "vs. previous: valuation +5.2%, yield improved"

Prompt to record analysis conclusions

When a response includes a specific judgment (such as "recommend selling" or "continue holding") in response to EXIT/warning:

💡 Would you like to record this judgment as an investment memo?