phoenixclaw-ledger
Passive financial tracking plugin for PhoenixClaw. Automatically detects expenses and income from conversations and payment screenshots. Use when: - User mentions money/spending (any language) - User shares payment screenshots (WeChat Pay, Alipay, etc.) - User asks about finances ("How much did I spend?", "My budget") - User wants expense reports ("Monthly summary", "Spending analysis")
Packaged view
This page reorganizes the original catalog entry around fit, installability, and workflow context first. The original raw source lives below.
Install command
npx @skill-hub/cli install openclaw-skills-phoenixclaw-ledger
Repository
Skill path: skills/goforu/phoenixclaw-ledger
Passive financial tracking plugin for PhoenixClaw. Automatically detects expenses and income from conversations and payment screenshots. Use when: - User mentions money/spending (any language) - User shares payment screenshots (WeChat Pay, Alipay, etc.) - User asks about finances ("How much did I spend?", "My budget") - User wants expense reports ("Monthly summary", "Spending analysis")
Open repositoryBest for
Primary workflow: Ship Full Stack.
Technical facets: Full Stack, Integration.
Target audience: everyone.
License: Unknown.
Original source
Catalog source: SkillHub Club.
Repository owner: openclaw.
This is still a mirrored public skill entry. Review the repository before installing into production workflows.
What it helps with
- Install phoenixclaw-ledger into Claude Code, Codex CLI, Gemini CLI, or OpenCode workflows
- Review https://github.com/openclaw/skills before adding phoenixclaw-ledger to shared team environments
- Use phoenixclaw-ledger for development workflows
Works across
Favorites: 0.
Sub-skills: 0.
Aggregator: No.
Original source / Raw SKILL.md
---
name: phoenixclaw-ledger
description: |
Passive financial tracking plugin for PhoenixClaw.
Automatically detects expenses and income from conversations and payment screenshots.
Use when:
- User mentions money/spending (any language)
- User shares payment screenshots (WeChat Pay, Alipay, etc.)
- User asks about finances ("How much did I spend?", "My budget")
- User wants expense reports ("Monthly summary", "Spending analysis")
metadata:
version: 0.1.0
depends: phoenixclaw
protocol_version: 1
min_core_version: 0.0.3
hook_point: post-moment-analysis
data_access:
- moments
- user_config
- memory
export_to_journal: true
---
# PhoenixClaw Ledger: Zero-Effort Financial Tracking
PhoenixClaw Ledger automatically extracts financial transactions from your daily conversations and payment screenshots, requiring zero manual input.
## Core Capabilities
| Feature | Description |
|---------|-------------|
| **Semantic Expense Detection** | AI identifies spending mentions in natural conversation |
| **Screenshot Recognition** | Extracts transaction data from payment app screenshots |
| **Smart Categorization** | Auto-categorizes based on merchant and context |
| **Budget Tracking** | Monthly budget alerts and progress visualization |
| **Financial Insights** | Pattern analysis integrated into journal Growth Notes |
| **Goal Management** | Savings, budget control, habit, and wishlist goals |
| **Weekly Reports** | Automated Sunday 9 PM spending recap |
| **Query Support** | Real-time natural language financial inquiries |
| **Spending Trends** | Multi-month analytical spending visualization |
| **Transaction Browser** | Interactive complete transaction history view |
## Workflow
As a PhoenixClaw plugin, Ledger hooks into the `post-moment-analysis` phase:
1. **Receive Moments**: Get identified moments from PhoenixClaw Core
2. **Detect Finances**: Scan for expense/income signals in text and media
- Text: Semantic patterns (see `references/expense-detection.md`)
- Media: Payment screenshots (see `references/payment-screenshot.md`)
3. **Extract Data**: Parse amount, merchant, category, timestamp
4. **Categorize**: Apply rules from `references/merchant-category-map.md`
5. **Deduplicate**: Prevent double-counting same transaction
6. **Store**: Write to `~/PhoenixClaw/Finance/ledger.yaml`
7. **Export**: Generate journal section using `assets/daily-finance-section.md`
## Explicit Triggers
While passive by design, users can interact directly:
- *"How much did I spend today/this week/this month?"*
- *"Show my expense breakdown"*
- *"Set my monthly budget to [amount]"*
- *"What are my top spending categories?"*
- *"Generate financial report for [period]"*
- *"Set a savings goal for [amount] by [date]"*
- *"Show my spending trends"*
- *"Browse all my transactions"*
- *"How am I doing on my goals?"*
## Output Structure
```
~/PhoenixClaw/
├── Journal/
│ ├── daily/2026-02-02.md # Contains 💰 Finance section
│ └── weekly/2026-W05.md # Weekly financial recaps
│
└── Finance/ # Ledger-specific directory
├── ledger.yaml # Structured transaction data
├── budget.yaml # Budget configuration
├── goals.yaml # Financial goals tracking
├── transactions.md # Transaction browser view
├── monthly/
│ └── 2026-02.md # Monthly financial reports
└── yearly/
└── 2026.md # Annual summaries
```
## Configuration
Ledger-specific settings in `~/.phoenixclaw/config.yaml`:
```yaml
plugins:
phoenixclaw-ledger:
enabled: true
default_currency: CNY # or USD, EUR, etc.
budget_monthly: 5000 # Monthly budget amount
categories_custom: [] # User-defined categories
screenshot_confidence: 0.7 # Min confidence for auto-record
```
## Cron & Scheduled Reports
Ledger uses PhoenixClaw Core's cron infrastructure plus additional scheduled tasks:
| Task | Schedule | Description |
|------|----------|-------------|
| **Daily Processing** | 10 PM (via Core) | Extracts transactions, generates daily section |
| **Monthly Report** | 1st of month, 8 AM | Comprehensive monthly financial summary |
| **Weekly Summary** | Sunday 9 PM (optional) | Weekly spending recap |
### Daily Processing (Automatic)
No separate setup required. Ledger hooks into Core's nightly cron:
- Core runs at 10 PM → triggers `post-moment-analysis`
- Ledger activates, extracts finances, exports to journal
### Monthly Report Setup
```bash
openclaw cron add \
--name "PhoenixClaw Ledger monthly report" \
--cron "0 8 1 * *" \
--tz "auto" \
--session isolated \
--message "Generate monthly financial report for the previous month."
```
See `references/cron-setup.md` for full configuration details.
## Documentation Reference
### References (`references/`)
- `expense-detection.md`: Semantic patterns for conversation parsing
- `payment-screenshot.md`: Screenshot recognition and OCR extraction
- `merchant-category-map.md`: Merchant to category mapping rules
- `category-rules.md`: Category definitions and hierarchy
- `budget-tracking.md`: Budget alerts and progress calculation
- `financial-insights.md`: Pattern analysis for Growth Notes
- `cron-setup.md`: Scheduled tasks and report automation
- `goal-management.md`: Financial goals and progress tracking
- `query-patterns.md`: Natural language query templates and logic
### Assets (`assets/`)
- `expense-callout.md`: Template for conversation-detected expenses
- `receipt-callout.md`: Template for screenshot-detected expenses
- `daily-finance-section.md`: Journal integration template
- `monthly-report.md`: Monthly summary template
- `yearly-report.md`: Annual summary template
---
---
## Referenced Files
> The following files are referenced in this skill and included for context.
### references/expense-detection.md
```markdown
# Expense Detection from Conversations
This document defines how PhoenixClaw Ledger identifies financial transactions from natural conversation text.
## Detection Philosophy
Ledger uses **semantic understanding** rather than keyword matching. The AI considers context, intent, and linguistic patterns to identify genuine financial events while ignoring false positives.
## Supported Languages
Ledger supports multi-language expense detection:
| Language | Example Patterns |
|----------|------------------|
| Chinese | "花了150块", "买了个新耳机", "人均80" |
| English | "spent $50", "cost me about 30 bucks", "paid for dinner" |
| Mixed | "今天lunch花了20刀" |
## Semantic Patterns
### Expense Signals
| Pattern Type | Examples | Extracted Data |
|--------------|----------|----------------|
| **Direct Amount** | "spent ¥150", "花了150" | amount: 150 |
| **Per-Person** | "人均80,4个人", "$20 each, 5 people" | amount: 320 / 100 |
| **Purchase** | "bought a keyboard for 599", "买了个键盘599" | amount: 599, category: shopping |
| **Service** | "haircut was 80", "理发80" | amount: 80, category: personal |
| **Subscription** | "renewed Netflix", "续费了会员" | amount: inferred, category: subscription |
| **Transport** | "Uber cost 35", "打车35" | amount: 35, category: transport |
### Income Signals
| Pattern Type | Examples | Extracted Data |
|--------------|----------|----------------|
| **Salary** | "工资到账15k", "got paid $5000" | amount: +15000/+5000, type: income |
| **Reimbursement** | "报销到了800", "expense reimbursed" | amount: +800, type: income |
| **Transfer Received** | "他还了我200", "got 50 back from John" | amount: +200/+50, type: income |
### Transfer/Debt Signals
| Pattern Type | Examples | Extracted Data |
|--------------|----------|----------------|
| **Lent Money** | "借给他500", "lent him 100" | amount: 500, type: receivable |
| **Borrowed** | "问他借了1000", "borrowed 200" | amount: 1000, type: payable |
| **Split Bill** | "我先垫了400", "I covered the bill" | amount: 400, type: receivable |
## Extraction Schema
```yaml
detected_expense:
amount: float # Absolute value
type: expense|income|transfer
currency: string # CNY, USD, EUR, etc.
category_hint: string # AI-inferred category
description: string # Brief description
timestamp: ISO8601 # When mentioned (conversation time)
confidence: float # 0-1 detection confidence
source: conversation
context: string # Surrounding text for verification
people: string[] # People involved (if mentioned)
```
## Confidence Scoring
| Confidence | Criteria | Action |
|------------|----------|--------|
| **High (≥0.85)** | Explicit amount + clear verb (spent, bought, paid) | Auto-record |
| **Medium (0.7-0.85)** | Amount present, context suggests transaction | Auto-record with review flag |
| **Low (<0.7)** | Ambiguous context or hypothetical | Do not record |
### Negative Signals (Reduce Confidence)
- Hypothetical language: "would cost", "might spend", "planning to buy"
- Questions: "how much is...?", "多少钱?"
- Past reference: "last year I spent...", "以前花过..."
- Quotes/Stories: "he told me it cost...", "他说花了..."
## Currency Detection
Priority order for currency inference:
1. **Explicit Symbol**: ¥, $, €, £
2. **Explicit Word**: "dollars", "块/元", "euros"
3. **User Config**: `default_currency` in settings
4. **Locale Inference**: Based on `user_config.language`
## Amount Parsing
| Format | Parsed As |
|--------|-----------|
| "150" | 150.00 |
| "150块" | 150.00 CNY |
| "$19.99" | 19.99 USD |
| "1.5k" / "1500" | 1500.00 |
| "15k" | 15000.00 |
| "人均80,3人" | 240.00 (calculated) |
| "about 50" | 50.00 (flagged as estimate) |
## False Positive Prevention
### Ignore These Contexts
- **Prices Without Purchase**: "The new iPhone costs $999" (just info, not a purchase)
- **Hypotheticals**: "If I bought it, I'd spend..."
- **Game/Virtual Currency**: "spent 1000 gold coins"
- **Historical Data**: "Back in 2020 I spent..."
- **Other People's Finances**: "My friend spent $500" (unless split/shared)
### Validation Rules
1. Transaction should relate to the user directly
2. Amount should be realistic for the category
3. Timestamp should be recent (today or explicitly stated)
4. Avoid duplicate detection from repeated mentions
## Integration with Screenshots
When both conversation and screenshot mention the same transaction:
1. **Screenshot takes priority** (more accurate data)
2. **Deduplicate by**: amount + approximate time (±30 min) + similar merchant
3. **Merge context**: Use conversation description + screenshot details
---
```
### references/payment-screenshot.md
```markdown
# Payment Screenshot Recognition
This document defines how PhoenixClaw Ledger extracts transaction data from payment app screenshots.
## Supported Platforms
| Platform | Region | Visual Identifiers |
|----------|--------|-------------------|
| **WeChat Pay** | China | Green checkmark, WeChat logo, "支付成功" |
| **Alipay** | China | Blue interface, Alipay logo, "付款成功" |
| **Apple Pay** | Global | Wallet app UI, card imagery |
| **Google Pay** | Global | Google Pay branding, checkmark |
| **Bank Apps** | Various | Bank logos, transaction confirmations |
| **UnionPay** | China | UnionPay logo, "交易成功" |
| **PayPal** | Global | PayPal logo, confirmation screen |
| **Venmo** | US | Venmo UI, social payment style |
## Detection Workflow
```
Photo Received
│
▼
┌─────────────────────────────────┐
│ Step 1: Screenshot Detection │
│ Is this a payment screenshot? │
└─────────────────────────────────┘
│
├── NO → Standard photo processing (PhoenixClaw Core)
│
▼ YES
┌─────────────────────────────────┐
│ Step 2: Platform Identification│
│ Which payment app/service? │
└─────────────────────────────────┘
│
▼
┌─────────────────────────────────┐
│ Step 3: Data Extraction │
│ OCR + Structured parsing │
└─────────────────────────────────┘
│
▼
┌─────────────────────────────────┐
│ Step 4: Validation │
│ Confidence check, dedup │
└─────────────────────────────────┘
│
├── High Confidence → Auto-record
│
└── Low Confidence → Flag for review
```
## Visual Detection Criteria
### WeChat Pay (微信支付)
| Element | Expected |
|---------|----------|
| Color Scheme | Green primary (#07C160) |
| Success Icon | Green checkmark circle |
| Key Text | "支付成功", "已支付", "付款成功" |
| Amount Position | Large, centered, ¥XX.XX format |
| Merchant | Below amount, smaller text |
| Timestamp | "支付时间" + datetime |
| Order ID | "订单号" or "商户单号" |
### Alipay (支付宝)
| Element | Expected |
|---------|----------|
| Color Scheme | Blue primary (#1677FF) |
| Success Icon | Blue checkmark or tick animation |
| Key Text | "付款成功", "交易成功" |
| Amount Position | Large, centered |
| Merchant | Merchant name prominently displayed |
| Payment Method | Card/balance indicator |
### Generic Bank Apps
| Element | Expected |
|---------|----------|
| Bank Logo | Institution branding |
| Transaction Type | "转账成功", "Transfer Complete" |
| Amount | Currency symbol + amount |
| Recipient/Merchant | Account info or name |
| Reference Number | Transaction ID |
## Data Extraction Schema
```yaml
payment_screenshot:
# Required fields
platform: wechat|alipay|apple_pay|google_pay|bank|unionpay|paypal|venmo|unknown
type: expense|income|transfer
amount: float
currency: string
# Common fields
merchant: string # Merchant/recipient name
timestamp: ISO8601 # Transaction time from screenshot
category_hint: string # AI-inferred category
# Optional fields
order_id: string # Order/transaction number
payment_method: string # Card, balance, etc.
original_amount: float # Pre-discount amount
discount: float # Discount/coupon amount
# Metadata
confidence: float # 0-1 extraction confidence
screenshot_path: string # Path to stored image
needs_review: boolean # Flag for low confidence
```
## OCR Best Practices
### Pre-processing
1. **Crop to Content**: Remove status bar, navigation
2. **Enhance Contrast**: Improve text readability
3. **Correct Orientation**: Ensure upright orientation
### Extraction Priority
Extract fields in this order (most reliable first):
1. **Amount**: Usually largest, most prominent text
2. **Platform**: Logo/branding detection
3. **Merchant**: Secondary text near amount
4. **Timestamp**: Standardized format
5. **Other Details**: Payment method, order ID
### Common OCR Challenges
| Challenge | Solution |
|-----------|----------|
| Stylized fonts | Use multiple OCR passes |
| Low resolution | Request higher quality image |
| Partial screenshot | Extract available data, flag incomplete |
| Non-standard layout | Platform-specific parsing rules |
## Confidence Scoring
| Score | Criteria | Action |
|-------|----------|--------|
| **≥0.9** | All key fields extracted, platform identified | Auto-record |
| **0.7-0.9** | Amount + merchant extracted, some uncertainty | Auto-record, flag for review |
| **0.5-0.7** | Partial extraction, likely payment screenshot | Store, ask for confirmation |
| **<0.5** | Uncertain if payment screenshot | Treat as regular photo |
### Confidence Factors
| Factor | Weight | Notes |
|--------|--------|-------|
| Platform identified | +0.2 | Known UI patterns |
| Amount extracted | +0.3 | Most critical field |
| Merchant extracted | +0.2 | Important for categorization |
| Timestamp found | +0.1 | Helps with deduplication |
| Order ID found | +0.1 | Confirms transaction record |
| Success indicator | +0.1 | Confirms completed payment |
## Deduplication
Prevent recording the same transaction multiple times:
### Match Criteria
Two records are considered duplicates if:
```
same_amount AND
same_merchant (fuzzy match) AND
timestamp_diff < 30 minutes
```
### Resolution Strategy
1. **Screenshot Priority**: Screenshot data is more accurate than conversation
2. **Merge Context**: Combine conversation description with screenshot details
3. **Keep Latest**: If multiple screenshots, keep the most detailed one
## Storage
### Screenshot Files
```
~/PhoenixClaw/Journal/assets/YYYY-MM-DD/
├── img_001.jpg # Regular photos
├── receipt_001.jpg # Payment screenshots
├── receipt_002.jpg
└── receipt_001.json # Extracted metadata (optional)
```
### Naming Convention
- Format: `receipt_XXX.{ext}`
- Preserve original extension (jpg, png, heic)
- Zero-padded sequence number
- Optional: `receipt_001_wechat.jpg` for platform suffix
## Privacy Considerations
### Sensitive Data Handling
1. **Mask Account Numbers**: Store only last 4 digits if visible
2. **No Full Names**: Use merchant name, not personal recipient names
3. **Local Storage Only**: Screenshots never uploaded to external services
4. **User Control**: Ability to delete specific receipts
### What NOT to Extract
- Full bank account numbers
- Personal ID numbers
- Detailed recipient information (for transfers)
- Authentication/security codes
---
```
### references/merchant-category-map.md
```markdown
# Merchant to Category Mapping
This document defines the rules for automatically categorizing transactions based on merchant names and contextual signals.
## Category Hierarchy
### Primary Categories
| Category ID | Display Name | Icon | Description |
|-------------|--------------|------|-------------|
| `food` | Food & Dining | 🍜 | Restaurants, groceries, delivery |
| `transport` | Transportation | 🚗 | Rides, fuel, public transit |
| `shopping` | Shopping | 🛒 | Retail, online purchases |
| `entertainment` | Entertainment | 🎬 | Movies, games, events |
| `utilities` | Bills & Utilities | 📱 | Phone, internet, electricity |
| `housing` | Housing | 🏠 | Rent, property fees |
| `health` | Health | 💊 | Medical, pharmacy, fitness |
| `education` | Education | 📚 | Courses, books, training |
| `personal` | Personal Care | 💈 | Haircuts, beauty, clothing |
| `subscription` | Subscriptions | 🔄 | Digital services, memberships |
| `transfer` | Transfers | 💸 | P2P, bank transfers |
| `income` | Income | 💰 | Salary, reimbursements |
| `other` | Other | 📦 | Uncategorized |
### Subcategories (Optional)
```yaml
food:
- restaurant
- delivery
- groceries
- coffee
- snacks
transport:
- rideshare
- public
- fuel
- parking
- flights
shopping:
- electronics
- clothing
- home
- gifts
```
## Merchant Pattern Matching
### High-Confidence Mappings
These merchants are mapped with high certainty:
#### Food & Dining
```yaml
food:
exact_match:
- "Starbucks"
- "星巴克"
- "McDonald's"
- "麦当劳"
- "KFC"
- "肯德基"
- "Luckin Coffee"
- "瑞幸咖啡"
- "海底捞"
- "Haidilao"
contains:
- "餐厅"
- "饭店"
- "Restaurant"
- "Cafe"
- "咖啡"
- "奶茶"
- "烘焙"
- "Bakery"
- "Pizza"
- "外卖"
platforms:
- "美团"
- "Meituan"
- "饿了么"
- "Ele.me"
- "DoorDash"
- "Uber Eats"
```
#### Transportation
```yaml
transport:
exact_match:
- "滴滴出行"
- "DiDi"
- "Uber"
- "Lyft"
- "高德打车"
- "花小猪"
- "12306"
- "中国铁路"
contains:
- "出租"
- "Taxi"
- "地铁"
- "Metro"
- "公交"
- "Bus"
- "加油"
- "Gas"
- "Fuel"
- "停车"
- "Parking"
- "航空"
- "Airlines"
```
#### Shopping
```yaml
shopping:
platforms:
- "淘宝"
- "Taobao"
- "天猫"
- "Tmall"
- "京东"
- "JD.com"
- "拼多多"
- "Pinduoduo"
- "Amazon"
- "亚马逊"
contains:
- "超市"
- "Supermarket"
- "便利店"
- "Convenience"
- "商城"
- "Mall"
- "Store"
```
#### Entertainment
```yaml
entertainment:
exact_match:
- "猫眼电影"
- "淘票票"
- "大麦"
contains:
- "电影"
- "Cinema"
- "KTV"
- "游戏"
- "Game"
- "票务"
- "Tickets"
```
#### Subscriptions
```yaml
subscription:
exact_match:
- "Netflix"
- "Spotify"
- "Apple"
- "iCloud"
- "Google One"
- "ChatGPT"
- "OpenAI"
- "GitHub"
- "腾讯视频"
- "爱奇艺"
- "优酷"
- "网易云音乐"
- "QQ音乐"
contains:
- "会员"
- "Membership"
- "订阅"
- "Subscription"
- "月费"
- "年费"
- "Premium"
- "Plus"
- "Pro"
```
## Matching Algorithm
### Priority Order
1. **User Custom Rules** (highest priority)
2. **Exact Match** on merchant name
3. **Platform Match** for known services
4. **Contains Match** for keywords
5. **AI Inference** based on context
6. **Default to `other`** if no match
### Matching Process
```python
def categorize(merchant: str, context: str) -> Category:
# 1. Check user custom rules
if match := user_rules.match(merchant):
return match
# 2. Exact match
if match := exact_mappings.get(normalize(merchant)):
return match
# 3. Platform match
for platform, category in platform_mappings.items():
if platform in merchant:
return category
# 4. Contains match
for keyword, category in keyword_mappings.items():
if keyword in merchant.lower():
return category
# 5. AI inference
if context:
return ai_infer_category(merchant, context)
# 6. Default
return Category.OTHER
```
## User Custom Rules
Users can define custom mappings in their config:
```yaml
# ~/.phoenixclaw/config.yaml
plugins:
phoenixclaw-ledger:
custom_categories:
"公司食堂": food
"Company Cafeteria": food
"物业费": housing
"Property Fee": housing
"健身房月卡": health
"Gym Membership": health
```
### Rule Format
```yaml
custom_categories:
"[Merchant Name]": [category_id]
# With regex support
custom_patterns:
- pattern: ".*健身.*"
category: health
- pattern: ".*Gym.*"
category: health
```
## Ambiguous Cases
### Context-Dependent Categorization
Some merchants require context:
| Merchant | Possible Categories | Resolution |
|----------|---------------------|------------|
| Amazon | shopping, subscription | Check amount pattern |
| 美团 | food, entertainment | Check specific service |
| Apple | electronics, subscription | Check amount (small = sub) |
### Amount-Based Hints
| Amount Pattern | Likely Category |
|----------------|-----------------|
| < $5 regular | food (coffee, snacks) |
| ~$10-15 monthly | subscription |
| Round numbers | transfers |
## Category Statistics
Track category usage for personalization:
```yaml
category_stats:
food:
count: 45
total: 3500.00
average: 77.78
last_used: 2026-02-02
transport:
count: 12
total: 580.00
average: 48.33
last_used: 2026-02-01
```
Use statistics for:
- Suggesting likely categories for ambiguous merchants
- Detecting unusual spending patterns
- Generating insights
---
```
### assets/daily-finance-section.md
```markdown
# Daily Finance Section Template
Template for the finance section integrated into PhoenixClaw daily journals.
## Section Structure
```markdown
## 💰 Financial Summary
{{TRANSACTIONS}}
---
{{DAILY_SUMMARY}}
{{BUDGET_STATUS}}
{{INSIGHTS}}
```
## Full Template
```markdown
## 💰 Financial Summary
{{#each EXPENSES}}
> [!expense] {{icon}} {{time}} {{description}}
> {{details}} | **{{currency}}{{amount}}** | {{category}}
> *Source: {{source}}*
{{/each}}
{{#each RECEIPTS}}
> [!receipt] 💳 {{time}} {{platform}}
> ![[{{screenshot_path}}|300]]
> {{merchant}} | **{{currency}}{{amount}}** | {{category}}
> *Source: Screenshot*
{{/each}}
---
**Today:** {{CURRENCY}}{{DAILY_TOTAL}} spent
**This {{PERIOD}}:** {{CURRENCY}}{{PERIOD_TOTAL}} / {{CURRENCY}}{{BUDGET}} ({{PERCENT}}%)
{{#if BUDGET_ALERT}}
> [!warning] {{BUDGET_ALERT}}
{{/if}}
{{#if INSIGHT}}
> [!insight] 💡 {{INSIGHT}}
{{/if}}
```
## Variables
### Transaction Variables
| Variable | Description |
|----------|-------------|
| `{{EXPENSES}}` | Array of conversation-detected expenses |
| `{{RECEIPTS}}` | Array of screenshot-detected expenses |
### Summary Variables
| Variable | Description | Example |
|----------|-------------|---------|
| `{{CURRENCY}}` | Currency symbol | ¥ |
| `{{DAILY_TOTAL}}` | Total spent today | 449.00 |
| `{{PERIOD}}` | Budget period name | month |
| `{{PERIOD_TOTAL}}` | Total spent in period | 3,280.00 |
| `{{BUDGET}}` | Budget limit | 5,000.00 |
| `{{PERCENT}}` | Percentage used | 66 |
| `{{BUDGET_ALERT}}` | Alert message (if any) | Budget at 80% |
| `{{INSIGHT}}` | Daily insight (if any) | Weekend spending up |
## Example Output
### Normal Day
```markdown
## 💰 Financial Summary
> [!expense] 🍜 12:30 Lunch
> Hotpot with colleagues | **¥150.00** | Food & Dining
> *Source: Conversation*
> [!receipt] 💳 14:32 WeChat Pay
> ![[assets/2026-02-02/receipt_001.jpg|300]]
> Luckin Coffee | **¥19.90** | Food & Dining
> *Source: Screenshot*
> [!expense] 🛒 18:00 Shopping
> New earbuds | **¥299.00** | Electronics
> *Source: Conversation*
---
**Today:** ¥468.90 spent
**This month:** ¥3,748.90 / ¥5,000.00 (75%)
```
### With Budget Warning
```markdown
## 💰 Financial Summary
> [!expense] 🍜 12:30 Lunch
> Restaurant | **¥85.00** | Food & Dining
> *Source: Conversation*
> [!expense] 🛒 15:00 Shopping
> Clothing | **¥450.00** | Shopping
> *Source: Conversation*
---
**Today:** ¥535.00 spent
**This month:** ¥4,283.00 / ¥5,000.00 (86%)
> [!warning] ⚠️ Budget at 86% with 8 days remaining
> Daily allowance: ¥89.63
```
### With Insight
```markdown
## 💰 Financial Summary
> [!receipt] 💳 19:30 Alipay
> ![[assets/2026-02-02/receipt_001.jpg|300]]
> Restaurant | **¥320.00** | Food & Dining
> *Source: Screenshot*
---
**Today:** ¥320.00 spent
**This month:** ¥2,100.00 / ¥5,000.00 (42%)
> [!insight] 💡 Weekend dining averages ¥280 vs ¥65 on weekdays
```
### No Spending Day
```markdown
## 💰 Financial Summary
*No expenses recorded today* ✨
---
**This month:** ¥2,100.00 / ¥5,000.00 (42%)
**Streak:** 2 no-spend days 🎉
```
### Income Day
```markdown
## 💰 Financial Summary
> [!income] 💰 10:00 Salary
> Monthly salary | **+¥15,000.00** | Income
> *Source: Conversation*
> [!expense] 🍜 12:30 Lunch
> Celebration lunch | **¥280.00** | Food & Dining
> *Source: Conversation*
---
**Today:** ¥280.00 spent | ¥15,000.00 received
**This month:** ¥2,380.00 / ¥5,000.00 (48%)
**Net:** +¥12,620.00
```
## Conditional Display
### Show Section If
- Any transactions today (expense or income)
- Budget alert is active
- Insight available
### Hide Section If
- No financial activity AND no alerts
- User has disabled finance section
### Collapse by Default If
- Only small transactions (total < daily average)
- All within normal range
## Section Order
In the journal, Financial Summary appears at order 45:
```
0-19: Highlights
20-39: Moments
40-59: 💰 Financial Summary ← HERE
60-79: Reflections
80-89: Other plugins
90-100: Growth Notes
```
## Integration Notes
- Section uses PhoenixClaw Core's callout styling
- Images use Obsidian embed syntax
- Currency and language follow user config
- Amounts formatted with thousands separators
- Percentages rounded to whole numbers
```
### references/cron-setup.md
```markdown
# Cron Setup for PhoenixClaw Ledger
PhoenixClaw Ledger leverages the same cron infrastructure as PhoenixClaw Core, with additional scheduled tasks for financial reporting.
## Cron Jobs Overview
| Job | Schedule | Purpose |
|-----|----------|---------|
| Daily Processing | 10:00 PM | Extract transactions, update ledger |
| Monthly Report | 1st of month, 8:00 AM | Generate monthly financial summary |
| Weekly Report | Sunday, 9:00 PM | Generate weekly report & browser update |
## Daily Processing (Automatic)
Ledger hooks into PhoenixClaw Core's nightly cron. No separate setup required if Core is already configured.
When Core runs at 10 PM:
1. Core identifies moments from the day's conversations
2. **Ledger plugin activates** at `post-moment-analysis` hook
3. Ledger extracts financial data from moments and screenshots
4. Ledger generates the `💰 Financial Summary` section
5. Core includes it in the daily journal
## Monthly Report Setup
Register a monthly cron job to generate comprehensive financial reports:
```bash
openclaw cron add \
--name "PhoenixClaw Ledger monthly report" \
--cron "0 8 1 * *" \
--tz "auto" \
--session isolated \
--message "Generate monthly financial report for the previous month. Analyze spending patterns, compare to budget, identify trends, and create actionable insights. Save to ~/PhoenixClaw/Finance/monthly/."
```
### Cron Expression Breakdown
```
0 8 1 * *
│ │ │ │ │
│ │ │ │ └── Any day of week
│ │ │ └──── Any month
│ │ └────── 1st day of month
│ └──────── 8:00 AM
└────────── 0 minutes
```
### Why 8 AM on the 1st?
- Runs after all previous month's transactions are captured
- Morning timing ensures report is ready for monthly review
- Avoids conflict with nightly journal generation
## Weekly Report Setup
Generate comprehensive weekly financial reports every Sunday evening. This report provides a detailed breakdown of the week's spending, income, and budget utilization using the [weekly-report.md](../assets/weekly-report.md) template.
```bash
openclaw cron add \
--name "PhoenixClaw Ledger weekly report" \
--cron "0 21 * * 0" \
--tz "auto" \
--session isolated \
--message "Generate weekly financial report. Analyze spending vs budget, identify top expenses, and prepare summary for Sunday's journal. Save to ~/PhoenixClaw/Finance/weekly/."
```
### Output Path
Reports are saved to: `~/PhoenixClaw/Finance/weekly/YYYY-WNN.md` (where `WNN` is the week number).
### Sunday Journal Integration
The weekly report is also automatically embedded in Sunday's daily journal entry for quick review.
## Transaction Browser Regeneration (Optional)
The Transaction Browser is a searchable Markdown index of all financial activity. You can schedule it to regenerate periodically (e.g., nightly) to ensure the index stays up-to-date.
```bash
openclaw cron add \
--name "PhoenixClaw Ledger browser refresh" \
--cron "0 23 * * *" \
--tz "auto" \
--session isolated \
--message "Regenerate the transaction browser index to include today's new entries."
```
Note: Regeneration can also be triggered manually using `openclaw run "Refresh transaction browser"`.
## Verification
Check all Ledger-related cron jobs:
```bash
openclaw cron list | grep -i ledger
```
Expected output:
```
PhoenixClaw Ledger monthly report 0 8 1 * * active
PhoenixClaw Ledger weekly report 0 21 * * 0 active
PhoenixClaw Ledger browser refresh 0 23 * * * active
```
## Manual Triggers
Generate reports on-demand without waiting for cron:
```bash
# Generate current month's report (in progress)
openclaw run "Generate financial report for this month so far"
# Generate specific month's report
openclaw run "Generate financial report for January 2026"
# Quick spending check
openclaw run "How much have I spent this week?"
```
## Report Storage
| Report Type | Path | Generated |
|-------------|------|-----------|
| Daily section | `Journal/daily/YYYY-MM-DD.md` | Nightly |
| Monthly report | `Finance/monthly/YYYY-MM.md` | 1st of month |
| Weekly report | `Finance/weekly/YYYY-WNN.md` | Sundays |
| Transaction Browser | `Finance/transactions.md` | Scheduled/Manual |
| Annual report | `Finance/yearly/YYYY.md` | Jan 1st |
## Dependency on Core
Ledger requires PhoenixClaw Core to be installed and its cron configured:
```bash
# Verify Core cron is active
openclaw cron list | grep "PhoenixClaw nightly"
```
If Core cron is not set up, Ledger's daily processing won't trigger automatically. See Core's `references/cron-setup.md` for initial setup.
## Timezone Considerations
- All cron jobs should use consistent timezone
- `--tz "auto"` inherits from Core's configuration
- For explicit timezone: `--tz "Asia/Shanghai"` or `--tz "America/New_York"`
## Troubleshooting
### Monthly report not generating
1. Check cron registration:
```bash
openclaw cron list
```
2. Check execution history:
```bash
openclaw cron history "PhoenixClaw Ledger monthly report"
```
3. Verify ledger.yaml exists:
```bash
ls ~/PhoenixClaw/Finance/ledger.yaml
```
### Missing transactions in report
1. Ensure daily cron ran successfully for all days
2. Check for gaps in ledger.yaml
3. Manual backfill if needed:
```bash
openclaw run "Scan memory for 2026-01-15 and extract any financial transactions"
```
### Budget alerts not appearing
1. Verify budget.yaml configuration exists
2. Check budget thresholds in config:
```bash
cat ~/.phoenixclaw/config.yaml | grep -A 10 budget
```
```
---
## Skill Companion Files
> Additional files collected from the skill directory layout.
### _meta.json
```json
{
"owner": "goforu",
"slug": "phoenixclaw-ledger",
"displayName": "phoenixclaw-ledger",
"latest": {
"version": "0.0.2",
"publishedAt": 1770092813253,
"commit": "https://github.com/clawdbot/skills/commit/64d59ac66b58caf66263ba61f0d49c45207baf6f"
},
"history": [
{
"version": "0.0.1",
"publishedAt": 1770005618046,
"commit": "https://github.com/clawdbot/skills/commit/d0b50035452b8da09dd4c0146b3e2fe2542a2648"
}
]
}
```
### assets/expense-callout.md
```markdown
# Expense Callout Template
Template for displaying expenses detected from conversation text.
## Template
```markdown
> [!expense] {{ICON}} {{TIME}} {{DESCRIPTION}}
> {{DETAILS}} | **{{CURRENCY}}{{AMOUNT}}** | {{CATEGORY}}
> *Source: Conversation*
```
## Variables
| Variable | Description | Example |
|----------|-------------|---------|
| `{{ICON}}` | Category emoji | 🍜, 🚗, 🛒 |
| `{{TIME}}` | Transaction time (HH:MM) | 12:30 |
| `{{DESCRIPTION}}` | Brief description | Lunch |
| `{{DETAILS}}` | Additional context | "With colleagues at hotpot restaurant" |
| `{{CURRENCY}}` | Currency symbol | ¥, $, € |
| `{{AMOUNT}}` | Transaction amount | 150.00 |
| `{{CATEGORY}}` | Category name | Food & Dining |
## Icon Mapping
| Category | Icon |
|----------|------|
| Food & Dining | 🍜 |
| Transportation | 🚗 |
| Shopping | 🛒 |
| Entertainment | 🎬 |
| Utilities | 📱 |
| Housing | 🏠 |
| Health | 💊 |
| Education | 📚 |
| Personal | 💈 |
| Subscription | 🔄 |
| Income | 💰 |
| Transfer | 💸 |
| Other | 📦 |
## Examples
### Basic Expense
```markdown
> [!expense] 🍜 12:30 Lunch
> Hotpot with colleagues | **¥150.00** | Food & Dining
> *Source: Conversation*
```
### With People
```markdown
> [!expense] 🍜 19:00 Dinner
> Birthday celebration with Alice and Bob | **¥320.00** | Food & Dining
> *Source: Conversation*
```
### Transport
```markdown
> [!expense] 🚗 08:15 Commute
> Rideshare to office | **¥35.00** | Transportation
> *Source: Conversation*
```
### Shopping
```markdown
> [!expense] 🛒 15:30 Electronics
> New wireless earbuds | **¥299.00** | Shopping
> *Source: Conversation*
```
### Income
```markdown
> [!income] 💰 10:00 Salary
> Monthly salary deposited | **+¥15,000.00** | Income
> *Source: Conversation*
```
## Styling Notes
- Use `>` for Obsidian callout syntax
- Category icon provides quick visual identification
- Amount is bold for emphasis
- Positive amounts (income) prefixed with `+`
- Source line italicized for de-emphasis
- Keep description concise (under 50 characters)
## Confidence Indicator (Optional)
For medium-confidence detections:
```markdown
> [!expense] 🛒 14:00 Purchase
> Online shopping | **¥199.00** | Shopping
> *Source: Conversation • ⚠️ Verify amount*
```
```
### assets/monthly-report.md
```markdown
---
type: monthly-finance
period: {{PERIOD}}
total_income: {{TOTAL_INCOME}}
total_expense: {{TOTAL_EXPENSE}}
net: {{NET}}
budget: {{BUDGET}}
currency: {{CURRENCY}}
generated: {{GENERATED_DATE}}
---
# 💰 {{PERIOD_DISPLAY}} Financial Report
## 📊 Overview
| Metric | Amount |
|--------|--------|
| Total Income | {{CURRENCY}}{{TOTAL_INCOME}} |
| Total Expenses | {{CURRENCY}}{{TOTAL_EXPENSE}} |
| **Net** | **{{CURRENCY}}{{NET}}** |
| Budget | {{CURRENCY}}{{BUDGET}} |
| Budget Used | {{BUDGET_PERCENT}}% |
## 📈 Expense Breakdown
### By Category
| Category | Amount | % of Total | vs Last Month |
|----------|--------|------------|---------------|
{{#each CATEGORIES}}
| {{icon}} {{name}} | {{currency}}{{amount}} | {{percent}}% | {{trend}} |
{{/each}}
### Visualization
```
{{CATEGORY_CHART}}
```
## 📅 Daily Spending Pattern
| Week | Mon | Tue | Wed | Thu | Fri | Sat | Sun | Total |
|------|-----|-----|-----|-----|-----|-----|-----|-------|
{{#each WEEKS}}
| W{{week}} | {{mon}} | {{tue}} | {{wed}} | {{thu}} | {{fri}} | {{sat}} | {{sun}} | {{total}} |
{{/each}}
**Average daily:** {{CURRENCY}}{{DAILY_AVERAGE}}
**Highest day:** {{HIGHEST_DAY}} ({{CURRENCY}}{{HIGHEST_AMOUNT}})
**No-spend days:** {{NO_SPEND_DAYS}}
## 💳 Top Transactions
### Largest Expenses
| Date | Description | Category | Amount |
|------|-------------|----------|--------|
{{#each TOP_EXPENSES}}
| {{date}} | {{description}} | {{category}} | {{currency}}{{amount}} |
{{/each}}
### Income Sources
| Date | Description | Amount |
|------|-------------|--------|
{{#each INCOME_ENTRIES}}
| {{date}} | {{description}} | +{{currency}}{{amount}} |
{{/each}}
## 🔄 Recurring Expenses
| Item | Frequency | Amount | Annual Cost |
|------|-----------|--------|-------------|
{{#each RECURRING}}
| {{name}} | {{frequency}} | {{currency}}{{amount}} | {{currency}}{{annual}} |
{{/each}}
**Total subscriptions:** {{CURRENCY}}{{SUBSCRIPTION_TOTAL}}/month
## 📊 Trends & Comparisons
### Month-over-Month
| Category | This Month | Last Month | Change |
|----------|------------|------------|--------|
{{#each MOM_COMPARISON}}
| {{category}} | {{current}} | {{previous}} | {{change}} |
{{/each}}
### Year-to-Date
- **Total spent:** {{CURRENCY}}{{YTD_TOTAL}}
- **Monthly average:** {{CURRENCY}}{{YTD_AVERAGE}}
- **Highest month:** {{HIGHEST_MONTH}} ({{CURRENCY}}{{HIGHEST_MONTH_AMOUNT}})
- **Lowest month:** {{LOWEST_MONTH}} ({{CURRENCY}}{{LOWEST_MONTH_AMOUNT}})
## 💡 Insights
{{#each INSIGHTS}}
> [!{{type}}] {{title}}
> {{content}}
{{/each}}
## 🎯 Budget Performance
### Category Budgets
| Category | Budget | Actual | Status |
|----------|--------|--------|--------|
{{#each BUDGET_PERFORMANCE}}
| {{category}} | {{budget}} | {{actual}} | {{status_icon}} {{status}} |
{{/each}}
### Recommendations
{{#each RECOMMENDATIONS}}
- {{content}}
{{/each}}
## 📎 Attachments
- **Receipts:** {{RECEIPT_COUNT}} screenshots stored
- **Data file:** [[Finance/ledger.yaml|View raw data]]
---
*Generated by PhoenixClaw Ledger 💰*
*Report date: {{GENERATED_DATE}}*
---
## Template Variables Reference
### Header Variables
| Variable | Description | Example |
|----------|-------------|---------|
| `{{PERIOD}}` | Period identifier | 2026-02 |
| `{{PERIOD_DISPLAY}}` | Display format | February 2026 |
| `{{CURRENCY}}` | Currency symbol | ¥ |
| `{{TOTAL_INCOME}}` | Total income | 15,000.00 |
| `{{TOTAL_EXPENSE}}` | Total expenses | 8,234.00 |
| `{{NET}}` | Net (income - expense) | 6,766.00 |
| `{{BUDGET}}` | Budget amount | 5,000.00 |
| `{{BUDGET_PERCENT}}` | Budget utilization | 165 |
| `{{GENERATED_DATE}}` | Report generation date | 2026-02-28 |
### Category Entry
```yaml
category:
icon: 🍜
name: Food & Dining
amount: 2,340.00
percent: 28
trend: ↑15% # or ↓8%, →
```
### Insight Entry
```yaml
insight:
type: insight|warning|success|tip
title: Spending Pattern
content: Weekend dining accounts for 60% of food expenses
```
### Status Icons
| Status | Icon |
|--------|------|
| Under budget | ✅ |
| Near limit (80-100%) | ⚠️ |
| Over budget | ❌ |
| No budget set | ➖ |
## Example Output
```markdown
---
type: monthly-finance
period: 2026-02
total_income: 15000.00
total_expense: 8234.00
net: 6766.00
budget: 5000.00
currency: CNY
generated: 2026-02-28
---
# 💰 February 2026 Financial Report
## 📊 Overview
| Metric | Amount |
|--------|--------|
| Total Income | ¥15,000.00 |
| Total Expenses | ¥8,234.00 |
| **Net** | **¥6,766.00** |
| Budget | ¥5,000.00 |
| Budget Used | 165% |
## 📈 Expense Breakdown
### By Category
| Category | Amount | % of Total | vs Last Month |
|----------|--------|------------|---------------|
| 🍜 Food & Dining | ¥2,340.00 | 28% | ↑15% |
| 🛒 Shopping | ¥1,890.00 | 23% | ↓8% |
| 🚗 Transportation | ¥580.00 | 7% | → |
| 🎬 Entertainment | ¥450.00 | 5% | ↑25% |
| 🔄 Subscriptions | ¥200.00 | 2% | → |
| 📦 Other | ¥2,774.00 | 34% | ↑5% |
## 💡 Insights
> [!insight] Spending Pattern
> Weekend spending accounts for 45% of total expenses
> [!warning] Budget Alert
> Exceeded monthly budget by ¥3,234
> [!tip] Suggestion
> Consider meal prepping to reduce food delivery costs
---
*Generated by PhoenixClaw Ledger 💰*
*Report date: 2026-02-28*
```
```
### assets/receipt-callout.md
```markdown
# Receipt Callout Template
Template for displaying expenses extracted from payment screenshots.
## Template
```markdown
> [!receipt] 💳 {{TIME}} {{PLATFORM}}
> ![[{{SCREENSHOT_PATH}}|300]]
>
> | Field | Value |
> |-------|-------|
> | Merchant | {{MERCHANT}} |
> | Amount | **{{CURRENCY}}{{AMOUNT}}** |
> | Method | {{PAYMENT_METHOD}} |
> {{#if DISCOUNT}}
> | Discount | -{{CURRENCY}}{{DISCOUNT}} |
> {{/if}}
> {{#if ORIGINAL_AMOUNT}}
> | Original | ~~{{CURRENCY}}{{ORIGINAL_AMOUNT}}~~ |
> {{/if}}
>
> *Source: {{PLATFORM}} screenshot*
```
## Variables
| Variable | Description | Example |
|----------|-------------|---------|
| `{{TIME}}` | Transaction time | 14:32 |
| `{{PLATFORM}}` | Payment platform | WeChat Pay |
| `{{SCREENSHOT_PATH}}` | Path to receipt image | assets/2026-02-02/receipt_001.jpg |
| `{{MERCHANT}}` | Merchant/store name | Luckin Coffee (Wangjing) |
| `{{CURRENCY}}` | Currency symbol | ¥ |
| `{{AMOUNT}}` | Final paid amount | 19.90 |
| `{{PAYMENT_METHOD}}` | Payment method used | WeChat Balance |
| `{{DISCOUNT}}` | Discount amount (optional) | 5.00 |
| `{{ORIGINAL_AMOUNT}}` | Pre-discount amount (optional) | 24.90 |
## Platform Names
| Platform Code | Display Name |
|---------------|--------------|
| `wechat` | WeChat Pay |
| `alipay` | Alipay |
| `apple_pay` | Apple Pay |
| `google_pay` | Google Pay |
| `unionpay` | UnionPay |
| `paypal` | PayPal |
| `bank` | Bank Transfer |
| `unknown` | Payment |
## Examples
### Basic Receipt
```markdown
> [!receipt] 💳 14:32 WeChat Pay
> ![[assets/2026-02-02/receipt_001.jpg|300]]
>
> | Field | Value |
> |-------|-------|
> | Merchant | Luckin Coffee |
> | Amount | **¥19.90** |
> | Method | WeChat Balance |
>
> *Source: WeChat Pay screenshot*
```
### With Discount
```markdown
> [!receipt] 💳 12:15 Alipay
> ![[assets/2026-02-02/receipt_002.jpg|300]]
>
> | Field | Value |
> |-------|-------|
> | Merchant | Freshippo (Hema) |
> | Amount | **¥86.50** |
> | Original | ~~¥96.50~~ |
> | Discount | -¥10.00 |
> | Method | Credit Card |
>
> *Source: Alipay screenshot*
```
### Bank Transfer
```markdown
> [!receipt] 💳 10:00 Bank Transfer
> ![[assets/2026-02-02/receipt_003.jpg|300]]
>
> | Field | Value |
> |-------|-------|
> | Type | Incoming Transfer |
> | Amount | **+¥5,000.00** |
> | From | **** 1234 |
> | Method | Bank Account |
>
> *Source: Bank App screenshot*
```
## Compact Format
For multiple receipts, use compact format:
```markdown
> [!receipt] 💳 14:32 WeChat Pay
> ![[assets/2026-02-02/receipt_001.jpg|200]]
> Luckin Coffee | **¥19.90** | Food & Dining
> *Auto-detected from screenshot*
```
## Styling Notes
- Image width: 300px for detailed view, 200px for compact
- Use Obsidian table for structured data
- Strikethrough (~~) for original prices when discounted
- Mask sensitive data (last 4 digits only for cards)
- Bold the final amount paid
- Positive amounts (income) prefixed with `+`
## Low Confidence Indicator
When extraction confidence is below threshold:
```markdown
> [!receipt] 💳 14:32 WeChat Pay
> ![[assets/2026-02-02/receipt_001.jpg|300]]
>
> | Field | Value |
> |-------|-------|
> | Merchant | Luckin Coffee |
> | Amount | **¥19.90** ⚠️ |
> | Method | Unknown |
>
> *Source: WeChat Pay screenshot • Please verify*
```
## Gallery Format
For multiple receipts in one day:
```markdown
> [!receipt-gallery] 💳 Today's Receipts
> ![[assets/2026-02-02/receipt_001.jpg|150]] ![[assets/2026-02-02/receipt_002.jpg|150]] ![[assets/2026-02-02/receipt_003.jpg|150]]
>
> **Total:** ¥256.40 from 3 transactions
```
```
### assets/transaction-browser.md
```markdown
---
date: {{GENERATED_DATE}}
type: transaction-browser
tags: [finance, ledger, transactions]
---
# 🔍 Transaction Browser
> [!info] Regeneration Strategy
> This file is a static snapshot of your financial history. It is regenerated periodically to reflect new transactions.
> Last updated: {{GENERATED_DATE}}
> [!tip] Search & Filter
> Since this is a static Markdown file, use **Ctrl+F** (or **Cmd+F** on Mac) to search for specific merchants, categories, or amounts.
## ⚡ Recent Activity (Last 7 Days)
{{#each RECENT_TRANSACTIONS}}
> [!expense] {{icon}} {{date}} {{description}}
> {{details}} | **{{currency}}{{amount}}** | {{category}}
> *Source: {{source}}*
{{/each}}
## 📅 Browse by Month
{{#each MONTHLY_SUMMARIES}}
- [[{{path}}|{{month_display}}]] — {{currency}}{{total_spending}}
{{/each}}
## 🗂️ Browse by Category
*Grouped by category, sorted by total amount descending*
{{#each CATEGORY_GROUPS}}
### {{icon}} {{category_name}} ({{currency}}{{total_amount}})
| Date | Description | Amount |
| :--- | :--- | :--- |
{{#each transactions}}
| {{date}} | {{description}} | {{currency}}{{amount}} |
{{/each}}
{{/each}}
## 🧾 All Transactions
*Reverse chronological order*
| Date | Description | Category | Amount |
| :--- | :--- | :--- | :--- |
{{#each ALL_TRANSACTIONS}}
| {{date}} | {{description}} | {{category}} | {{currency}}{{amount}} |
{{/each}}
```
### assets/trend-view.md
```markdown
---
date: {{DATE}}
type: trend-analysis
period: {{PERIOD_TYPE}} # 3m | 6m | custom
range: {{START_DATE}} to {{END_DATE}}
tags: [finance, phoenixclaw, trend]
---
# 📊 Spending Trend Analysis ({{PERIOD_TYPE_LABEL}})
**Period:** {{START_DATE}} to {{END_DATE}}
**Total Spending:** {{CURRENCY}}{{TOTAL_SPENT}}
**Avg. per Period:** {{CURRENCY}}{{PERIOD_AVERAGE}}
---
{{#if IS_3M}}
## 🗓️ 3-Month Weekly Trend (12 Weeks)
| Week | Date Range | Total | ASCII Sparkline |
|:-----|:-----------|:------|:----------------|
{{#each WEEKS}}
| W{{index}} | {{label}} | {{CURRENCY}}{{amount}} | `{{sparkline}}` |
{{/each}}
{{/if}}
{{#if IS_6M}}
## 🗓️ 6-Month Monthly Trend
| Month | Total | ASCII Sparkline |
|:------|:------|:----------------|
{{#each MONTHS}}
| {{label}} | {{CURRENCY}}{{amount}} | `{{sparkline}}` |
{{/each}}
{{/if}}
{{#if IS_CUSTOM}}
## 🗓️ Custom Range Analysis
**From:** {{START_DATE}}
**To:** {{END_DATE}}
| Period | Total |
|:-------|:------|
{{#each CUSTOM_PERIODS}}
| {{label}} | {{CURRENCY}}{{amount}} |
{{/each}}
{{/if}}
---
## 🗂️ Category Trend Breakdown
```text
{{CATEGORY_ASCII_CHART}}
```
| Category | Total | % of Total | vs. Previous |
|:---------|:------|:-----------|:-------------|
{{#each CATEGORY_TRENDS}}
| {{name}} | {{CURRENCY}}{{amount}} | {{percent}}% | {{diff_pct}}% {{#if is_up}}🔺{{else}}🔻{{/if}} |
{{/each}}
---
## 💡 Comparative Insights
> [!insight] Performance vs. Previous Period
{{#each COMPARATIVE_INSIGHTS}}
> - **{{type}}**: {{description}}
{{/each}}
## 💭 Observations & Patterns
{{#each OBSERVATIONS}}
- {{this}}
{{/each}}
---
Generated by [[PhoenixClaw Ledger]]
```
### assets/weekly-report.md
```markdown
---
type: weekly-finance
week: {{WEEK}}
total_income: {{TOTAL_INCOME}}
total_expense: {{TOTAL_EXPENSE}}
net: {{NET}}
budget: {{BUDGET}}
currency: {{CURRENCY}}
generated: {{GENERATED_DATE}}
---
# 💰 Week {{WEEK}} Financial Report
*{{WEEK_RANGE}}*
## 📊 Overview
| Metric | Amount |
|--------|--------|
| Total Income | {{CURRENCY}}{{TOTAL_INCOME}} |
| Total Expenses | {{CURRENCY}}{{TOTAL_EXPENSE}} |
| **Net** | **{{CURRENCY}}{{NET}}** |
| Budget | {{CURRENCY}}{{BUDGET}} |
| Budget Used | {{BUDGET_PERCENT}}% |
## 📅 Daily Spending Breakdown
| Day | Date | Income | Expense | Net |
|-----|------|--------|---------|-----|
| Mon | {{MON_DATE}} | {{MON_INCOME}} | {{MON_EXPENSE}} | {{MON_NET}} |
| Tue | {{TUE_DATE}} | {{TUE_INCOME}} | {{TUE_EXPENSE}} | {{TUE_NET}} |
| Wed | {{WED_DATE}} | {{WED_INCOME}} | {{WED_EXPENSE}} | {{WED_NET}} |
| Thu | {{THU_DATE}} | {{THU_INCOME}} | {{THU_EXPENSE}} | {{THU_NET}} |
| Fri | {{FRI_DATE}} | {{FRI_INCOME}} | {{FRI_EXPENSE}} | {{FRI_NET}} |
| Sat | {{SAT_DATE}} | {{SAT_INCOME}} | {{SAT_EXPENSE}} | {{SAT_NET}} |
| Sun | {{SUN_DATE}} | {{SUN_INCOME}} | {{SUN_EXPENSE}} | {{SUN_NET}} |
| **Total** | | **{{TOTAL_INCOME}}** | **{{TOTAL_EXPENSE}}** | **{{NET}}** |
## 📈 Expense Breakdown
### By Category
| Category | Amount | % of Total | vs Last Week |
|----------|--------|------------|--------------|
{{#each CATEGORIES}}
| {{icon}} {{name}} | {{currency}}{{amount}} | {{percent}}% | {{trend}} |
{{/each}}
### Visualization
```
{{CATEGORY_CHART}}
```
## 💳 Top Expenses
| Date | Description | Category | Amount |
|------|-------------|----------|--------|
{{#each TOP_EXPENSES}}
| {{date}} | {{description}} | {{category}} | {{currency}}{{amount}} |
{{/each}}
## 🔄 Week-over-Week Comparison
| Metric | This Week | Last Week | Change |
|--------|-----------|-----------|--------|
| Total Spent | {{CURRENCY}}{{TOTAL_EXPENSE}} | {{CURRENCY}}{{PREV_WEEK_EXPENSE}} | {{EXPENSE_CHANGE}} |
| Daily Average | {{CURRENCY}}{{DAILY_AVERAGE}} | {{CURRENCY}}{{PREV_DAILY_AVERAGE}} | {{AVG_CHANGE}} |
| Largest Category | {{TOP_CATEGORY}} | {{PREV_TOP_CATEGORY}} | - |
## 💡 Insights
{{#each INSIGHTS}}
> [!{{type}}] {{title}}
> {{content}}
{{/each}}
## 📅 Sunday Journal Integration
The following section is embedded in Sunday's daily journal:
```markdown
## 📊 This Week's Summary
> [!summary] Weekly Finance: {{WEEK}}
> - **Total Spent:** {{CURRENCY}}{{TOTAL_EXPENSE}} ({{EXPENSE_CHANGE}} vs last week)
> - **Top Category:** {{TOP_CATEGORY}} ({{CURRENCY}}{{TOP_CATEGORY_AMOUNT}})
> - **Net Balance:** {{CURRENCY}}{{NET}}
>
> [[Finance/weekly/{{WEEK}}.md|View Full Weekly Report →]]
```
---
*Generated by PhoenixClaw Ledger 💰*
*Report date: {{GENERATED_DATE}}*
---
## Template Variables Reference
| Variable | Description | Example |
|----------|-------------|---------|
| `{{WEEK}}` | ISO Week identifier | 2026-W06 |
| `{{WEEK_RANGE}}` | Date range of the week | Feb 2, 2026 - Feb 8, 2026 |
| `{{CURRENCY}}` | Currency symbol | ¥ |
| `{{TOTAL_INCOME}}` | Total income for the week | 1500.00 |
| `{{TOTAL_EXPENSE}}` | Total expenses for the week | 1234.00 |
| `{{NET}}` | Net (income - expense) | 266.00 |
| `{{BUDGET}}` | Weekly budget | 1500.00 |
| `{{BUDGET_PERCENT}}` | Budget utilization percentage | 82 |
| `{{EXPENSE_CHANGE}}` | Week-over-week change in spending | ↑12% |
```
### assets/yearly-report.md
```markdown
---
type: yearly-finance
year: {{YEAR}}
total_income: {{TOTAL_INCOME}}
total_expense: {{TOTAL_EXPENSE}}
net: {{NET}}
currency: {{CURRENCY}}
generated: {{GENERATED_DATE}}
---
# {{YEAR}} Annual Financial Report
## Overview
| Metric | Amount |
|--------|--------|
| Total Income | {{CURRENCY}}{{TOTAL_INCOME}} |
| Total Expenses | {{CURRENCY}}{{TOTAL_EXPENSE}} |
| **Net Savings** | **{{CURRENCY}}{{NET}}** |
| Savings Rate | {{SAVINGS_RATE}}% |
## Monthly Breakdown
| Month | Income | Expenses | Net | Budget Status |
|-------|--------|----------|-----|---------------|
{{#each MONTHS}}
| {{name}} | {{income}} | {{expense}} | {{net}} | {{status}} |
{{/each}}
## Category Summary
### Top Expense Categories
| Category | Annual Total | Monthly Avg | % of Total |
|----------|--------------|-------------|------------|
{{#each TOP_CATEGORIES}}
| {{icon}} {{name}} | {{total}} | {{avg}} | {{percent}}% |
{{/each}}
### Category Trends
```
{{CATEGORY_TREND_CHART}}
```
## Quarterly Analysis
| Quarter | Income | Expenses | Net |
|---------|--------|----------|-----|
| Q1 (Jan-Mar) | {{Q1_INCOME}} | {{Q1_EXPENSE}} | {{Q1_NET}} |
| Q2 (Apr-Jun) | {{Q2_INCOME}} | {{Q2_EXPENSE}} | {{Q2_NET}} |
| Q3 (Jul-Sep) | {{Q3_INCOME}} | {{Q3_EXPENSE}} | {{Q3_NET}} |
| Q4 (Oct-Dec) | {{Q4_INCOME}} | {{Q4_EXPENSE}} | {{Q4_NET}} |
## Key Insights
{{#each INSIGHTS}}
> [!{{type}}] {{title}}
> {{content}}
{{/each}}
## Year-over-Year Comparison
{{#if PREVIOUS_YEAR}}
| Metric | {{PREVIOUS_YEAR}} | {{YEAR}} | Change |
|--------|-------------------|----------|--------|
| Income | {{PREV_INCOME}} | {{CURR_INCOME}} | {{INCOME_CHANGE}} |
| Expenses | {{PREV_EXPENSE}} | {{CURR_EXPENSE}} | {{EXPENSE_CHANGE}} |
| Savings | {{PREV_SAVINGS}} | {{CURR_SAVINGS}} | {{SAVINGS_CHANGE}} |
{{else}}
*First year of tracking - no comparison available*
{{/if}}
## Recurring Expenses Summary
| Item | Monthly | Annual | % of Expenses |
|------|---------|--------|---------------|
{{#each RECURRING}}
| {{name}} | {{monthly}} | {{annual}} | {{percent}}% |
{{/each}}
**Total Recurring:** {{CURRENCY}}{{RECURRING_TOTAL}}/year
## Financial Goals
{{#each GOALS}}
- {{name}}: {{progress}}/{{target}} ({{percent}}%) {{status_icon}}
{{/each}}
## Recommendations for Next Year
{{#each RECOMMENDATIONS}}
1. {{content}}
{{/each}}
---
*Generated by PhoenixClaw Ledger*
*Report date: {{GENERATED_DATE}}*
```
### references/budget-tracking.md
```markdown
# Budget Tracking
This document defines how PhoenixClaw Ledger manages budgets, tracks progress, and generates alerts.
## Budget Configuration
### User Setup
Budgets are configured in `~/.phoenixclaw/config.yaml`:
```yaml
plugins:
phoenixclaw-ledger:
budget:
enabled: true
period: monthly # monthly | weekly | custom
currency: CNY
total: 5000 # Total monthly budget
# Category allocations (optional)
categories:
food: 1500
transport: 500
shopping: 800
entertainment: 400
# Unspecified categories share remaining budget
# Alert thresholds
alerts:
warn_at: 80 # Warn at 80% spent
critical_at: 95 # Critical at 95% spent
daily_limit: 300 # Optional daily spending limit
```
### Storage Location
```
~/PhoenixClaw/Finance/
└── budget.yaml # Budget configuration and state
```
### Budget State Schema
```yaml
# budget.yaml
config:
period: monthly
total: 5000
currency: CNY
categories: {...}
state:
current_period: "2026-02"
period_start: "2026-02-01"
period_end: "2026-02-28"
spent:
total: 3280
by_category:
food: 1200
transport: 380
shopping: 850
entertainment: 250
other: 600
remaining:
total: 1720
days_left: 12
daily_allowance: 143.33
```
## Progress Calculation
### Basic Metrics
```yaml
budget_metrics:
# Absolute values
total_budget: 5000
total_spent: 3280
total_remaining: 1720
# Percentages
percent_spent: 65.6
percent_remaining: 34.4
# Time-based
days_elapsed: 16
days_total: 28
percent_time_elapsed: 57.1
# Pace analysis
expected_spend_by_now: 2857 # Budget * (days_elapsed / days_total)
actual_vs_expected: -423 # Negative = under budget
pace_status: on_track # under | on_track | over
```
### Pace Status Calculation
```
pace_ratio = (percent_spent / percent_time_elapsed)
if pace_ratio < 0.9:
status = "under" # Spending slower than time
elif pace_ratio > 1.1:
status = "over" # Spending faster than time
else:
status = "on_track" # Within 10% of expected
```
## Alert System
### Alert Levels
| Level | Trigger | Icon | Action |
|-------|---------|------|--------|
| **Info** | Daily summary | ℹ️ | Show in journal |
| **Warning** | 80% budget used | ⚠️ | Highlight in journal |
| **Critical** | 95% budget used | 🚨 | Prominent warning |
| **Exceeded** | Over 100% | ❌ | Strong warning |
### Alert Messages
```yaml
alerts:
info:
- "Today's spending: ¥{daily_total}"
- "This week: ¥{weekly_total}"
warning:
threshold: 80
messages:
- "Budget alert: {percent}% spent with {days} days remaining"
- "Consider reducing discretionary spending"
critical:
threshold: 95
messages:
- "⚠️ Budget nearly exhausted: {percent}% spent"
- "Only ¥{remaining} left for {days} days"
exceeded:
messages:
- "❌ Budget exceeded by ¥{overage}"
- "Total spending: ¥{total} / ¥{budget}"
```
### Category-Specific Alerts
```yaml
category_alerts:
- category: food
threshold: 90
message: "Food budget at {percent}%"
- category: shopping
threshold: 75
message: "Shopping nearing limit"
```
## Daily Allowance
### Calculation
```
daily_allowance = remaining_budget / days_remaining
# With buffer for unexpected expenses
safe_daily = daily_allowance * 0.9
```
### Display Format
```markdown
**Daily Budget Guide**
- Remaining: ¥1,720
- Days left: 12
- Daily allowance: ¥143/day
- Safe spending: ¥129/day
```
## Period Management
### Monthly Reset
```yaml
monthly_reset:
trigger: first_day_of_month
actions:
- archive_previous_period
- reset_spent_totals
- recalculate_allowances
- generate_monthly_report
```
### Rollover Options
```yaml
rollover:
enabled: false # Whether unused budget rolls over
max_rollover: 500 # Maximum rollover amount
rollover_to: savings # savings | next_month | category
```
## Budget Reports
### Daily Summary (in Journal)
```markdown
## 💰 Financial Summary
**Today:** ¥449 spent
**This Month:** ¥3,280 / ¥5,000 (66%)
> [!budget] 📊 Budget Status
> - Pace: On track ✓
> - Daily allowance: ¥143
> - Remaining: ¥1,720 for 12 days
```
### Weekly Summary
```markdown
## 📊 Weekly Budget Report
| Category | Spent | Budget | Status |
|----------|-------|--------|--------|
| Food | ¥680 | ¥350/week | ⚠️ Over |
| Transport | ¥120 | ¥125/week | ✅ OK |
| Shopping | ¥450 | ¥200/week | ⚠️ Over |
**Weekly Total:** ¥1,250 / ¥1,250 (100%)
```
### Monthly Report
See `assets/monthly-report.md` for full template.
## Smart Insights
### Pattern-Based Recommendations
```yaml
insights:
- pattern: "weekend_spike"
condition: "weekend_spending > weekday_spending * 2"
message: "Weekend spending is significantly higher than weekdays"
suggestion: "Consider setting a separate weekend budget"
- pattern: "early_exhaustion"
condition: "percent_spent > 80 AND percent_time < 60"
message: "Budget depleting faster than expected"
suggestion: "Try to reduce spending in remaining days"
- pattern: "category_imbalance"
condition: "single_category > 50% of total"
message: "{category} dominates your spending"
suggestion: "Review if this aligns with your priorities"
```
### Projections
```yaml
projections:
# End-of-month projection based on current pace
projected_total: 5125
projected_overage: 125
# What-if scenarios
if_reduce_daily_by: 50
then_end_month_at: 4525
# Historical comparison
vs_last_month: +8%
vs_3_month_avg: +12%
```
## Integration with Journal
### Section Output
Ledger exports budget info to PhoenixClaw Core:
```yaml
plugin_output:
section_id: finance
section_title: "💰 Financial Summary"
section_order: 45
budget_summary:
spent_today: 449
spent_month: 3280
budget_total: 5000
percent_used: 65.6
status: on_track
alerts: []
content: |
(Rendered markdown content)
```
### Conditional Display
```yaml
display_rules:
# Always show if there's spending
show_if: daily_spending > 0
# Expand details if notable
expand_if:
- daily_spending > daily_allowance
- budget_percent > 80
- any_alerts_active
```
---
```
### references/category-rules.md
```markdown
# Category Rules and Definitions
This document defines the expense category system, including hierarchy, icons, and behavioral rules.
## Category Schema
```yaml
category:
id: string # Unique identifier (lowercase, no spaces)
name: string # Display name (localized)
icon: string # Emoji icon
color: string # Hex color for charts
parent: string? # Parent category ID (for subcategories)
budget_default: float? # Default budget allocation %
is_essential: boolean # Essential vs discretionary
```
## Default Categories
### Essential Categories
| ID | Name (EN) | Name (ZH) | Icon | Color | Budget % |
|----|-----------|-----------|------|-------|----------|
| `housing` | Housing | 居住 | 🏠 | #4CAF50 | 30% |
| `utilities` | Utilities | 账单 | 📱 | #2196F3 | 10% |
| `food` | Food & Dining | 餐饮 | 🍜 | #FF9800 | 15% |
| `transport` | Transportation | 交通 | 🚗 | #9C27B0 | 10% |
| `health` | Health | 健康 | 💊 | #E91E63 | 5% |
### Discretionary Categories
| ID | Name (EN) | Name (ZH) | Icon | Color | Budget % |
|----|-----------|-----------|------|-------|----------|
| `shopping` | Shopping | 购物 | 🛒 | #F44336 | 10% |
| `entertainment` | Entertainment | 娱乐 | 🎬 | #673AB7 | 5% |
| `personal` | Personal Care | 个护 | 💈 | #00BCD4 | 5% |
| `education` | Education | 教育 | 📚 | #3F51B5 | 5% |
| `subscription` | Subscriptions | 订阅 | 🔄 | #607D8B | 3% |
### Special Categories
| ID | Name (EN) | Name (ZH) | Icon | Notes |
|----|-----------|-----------|------|-------|
| `income` | Income | 收入 | 💰 | Positive amounts |
| `transfer` | Transfers | 转账 | 💸 | Neutral, excludes from totals |
| `other` | Other | 其他 | 📦 | Fallback category |
## Subcategory Definitions
### Food & Dining (`food`)
```yaml
food:
subcategories:
- id: food.restaurant
name: Restaurants
name_zh: 餐厅
icon: 🍽️
- id: food.delivery
name: Delivery
name_zh: 外卖
icon: 🛵
- id: food.groceries
name: Groceries
name_zh: 生鲜
icon: 🥬
- id: food.coffee
name: Coffee & Tea
name_zh: 咖啡茶饮
icon: ☕
- id: food.snacks
name: Snacks
name_zh: 零食
icon: 🍿
```
### Transportation (`transport`)
```yaml
transport:
subcategories:
- id: transport.rideshare
name: Rideshare
name_zh: 打车
icon: 🚕
- id: transport.public
name: Public Transit
name_zh: 公共交通
icon: 🚇
- id: transport.fuel
name: Fuel
name_zh: 加油
icon: ⛽
- id: transport.parking
name: Parking
name_zh: 停车
icon: 🅿️
- id: transport.flights
name: Flights
name_zh: 机票
icon: ✈️
```
### Shopping (`shopping`)
```yaml
shopping:
subcategories:
- id: shopping.electronics
name: Electronics
name_zh: 数码
icon: 📱
- id: shopping.clothing
name: Clothing
name_zh: 服饰
icon: 👕
- id: shopping.home
name: Home & Living
name_zh: 家居
icon: 🛋️
- id: shopping.gifts
name: Gifts
name_zh: 礼物
icon: 🎁
```
## Category Behaviors
### Aggregation Rules
```yaml
aggregation:
# These categories roll up to parent
roll_up:
- food.* → food
- transport.* → transport
# These are counted separately
separate:
- income # Never mixed with expenses
- transfer # Excluded from spending totals
```
### Budget Inheritance
```yaml
budget_rules:
# Subcategories inherit from parent unless specified
food: 2000
food.delivery: 500 # Specific limit within food
food.coffee: 300 # Specific limit within food
# food.restaurant uses remaining food budget
```
### Display Order
Categories appear in this order in reports:
1. Essential categories (by budget %)
2. Discretionary categories (by budget %)
3. Other
4. Income (separate section)
5. Transfers (if shown)
## Localization
Category names support multiple languages:
```yaml
categories:
food:
name:
en: "Food & Dining"
zh: "餐饮"
ja: "食費"
ko: "식비"
icon: 🍜
```
### Language Selection
1. Use `user_config.language` setting
2. Fallback to English if translation unavailable
3. Icons are universal (no translation needed)
## Custom Categories
Users can create custom categories:
```yaml
# ~/.phoenixclaw/config.yaml
plugins:
phoenixclaw-ledger:
custom_categories:
- id: pets
name: Pets
name_zh: 宠物
icon: 🐱
color: "#8BC34A"
is_essential: false
budget_default: 5
```
### Custom Category Rules
- ID must be unique, lowercase, no spaces
- Must not conflict with default category IDs
- Icon should be a single emoji
- Color must be valid hex code
## Category Analysis
### Spending Health Indicators
```yaml
health_checks:
# Warn if category exceeds threshold
- category: food.delivery
warn_if_exceeds: 40% # of total food
message: "Delivery spending is high"
- category: entertainment
warn_if_exceeds: 15% # of total spending
message: "Entertainment spending above typical"
- category: subscription
warn_if_count_exceeds: 10
message: "You have many active subscriptions"
```
### Category Trends
Track month-over-month changes:
```yaml
trend_analysis:
compare_periods: 3 # Compare to last 3 months
significant_change: 20% # Alert if >20% change
# Generate insights like:
# "Food spending up 25% from last month"
# "Transportation down 15% - nice improvement!"
```
---
```
### references/financial-insights.md
```markdown
# Financial Insights Generation
This document defines how PhoenixClaw Ledger analyzes spending patterns and generates actionable insights for the journal's Growth Notes section.
## Insight Categories
### 1. Spending Patterns
Identify recurring behaviors and habits:
```yaml
pattern_insights:
- type: time_patterns
examples:
- "Most spending occurs on weekends (65%)"
- "Friday evenings show highest food expenses"
- "Morning coffee is a daily ¥25 habit"
- type: category_patterns
examples:
- "Food delivery increased 40% this month"
- "Subscription spending is steady at ¥200/month"
- "Impulse purchases average ¥150 each"
```
### 2. Behavioral Observations
Deeper analysis of spending behavior:
```yaml
behavioral_insights:
- type: impulse_detection
criteria: "Purchase not mentioned before or after"
examples:
- "3 impulse purchases this week totaling ¥450"
- "Electronics purchases often happen after payday"
- type: social_spending
criteria: "Multiple people mentioned in transaction"
examples:
- "Social meals average ¥180 (vs ¥45 solo)"
- "Group activities account for 30% of entertainment"
- type: emotional_spending
criteria: "Correlate with mood from PhoenixClaw Core"
examples:
- "Spending increases on low-energy days"
- "Retail therapy detected on 3 occasions"
```
### 3. Comparative Analysis
Compare across time periods:
```yaml
comparative_insights:
- type: month_over_month
examples:
- "Total spending up 15% vs last month"
- "Transport costs down 20% (more WFH days)"
- type: category_shifts
examples:
- "Dining out replaced by groceries (+¥300)"
- "New subscription added: Netflix (¥50/month)"
- type: budget_adherence
examples:
- "Stayed under budget 3 months in a row! 🎉"
- "Shopping category exceeded budget by ¥200"
```
### 4. Actionable Recommendations
Specific suggestions for improvement:
```yaml
recommendations:
- type: cost_reduction
trigger: "Category significantly over budget"
examples:
- "Consider cooking at home 2x more per week"
- "Review subscription list - 3 unused services detected"
- type: goal_alignment
trigger: "Spending conflicts with stated goals"
examples:
- "Saving goal at risk: discretionary spending up"
- "Travel fund on track with current savings rate"
- type: optimization
examples:
- "Switching to annual subscription saves ¥100"
- "Coffee shop rewards: 2 free drinks available"
```
## Insight Generation Rules
### Frequency Control
Avoid overwhelming users with too many insights:
```yaml
insight_limits:
daily_journal:
max_insights: 2
priority: [alerts, notable_spending, patterns]
weekly_summary:
max_insights: 5
priority: [trends, comparisons, recommendations]
monthly_report:
max_insights: 10
include_all_categories: true
```
### Significance Thresholds
Only surface meaningful insights:
```yaml
thresholds:
# Minimum change to report
min_percent_change: 15
min_absolute_change: 100
# Pattern detection
min_occurrences: 3 # Mention pattern after 3 instances
pattern_window_days: 14 # Look back period
# Anomaly detection
anomaly_threshold: 2.0 # Standard deviations from mean
```
### Tone Guidelines
```yaml
tone:
positive:
- "Great progress on staying within budget!"
- "Consistent spending habits this week 👍"
neutral:
- "Spending patterns this month:"
- "Here's what I noticed:"
concerned:
- "Something to consider:"
- "Worth reviewing:"
# Never use
avoid:
- Judgmental language
- Shame or guilt
- Comparisons to others
```
## Insight Templates
### Daily Insight Block
```markdown
> [!insight] 💡 Today's Financial Insight
> {insight_content}
```
### Pattern Alert
```markdown
> [!pattern] 📊 Spending Pattern Detected
> **{pattern_name}**
> {pattern_description}
>
> *Observed over the past {time_period}*
```
### Recommendation
```markdown
> [!tip] 💡 Suggestion
> {recommendation}
>
> **Potential savings:** ¥{amount}/month
```
### Achievement
```markdown
> [!success] 🎉 Financial Win
> {achievement_description}
```
## Integration with Growth Notes
Ledger contributes to PhoenixClaw's Growth Notes section:
```yaml
growth_notes_contribution:
section: "Financial Growth"
icon: 💰
content_types:
- budget_achievements
- spending_improvements
- financial_goals_progress
- habit_changes
example_output: |
### 💰 Financial Growth
- Stayed under food budget for 2 weeks straight
- Reduced impulse purchases by 50% vs last month
- On track for travel savings goal (¥2,400/¥5,000)
```
## Data Sources for Insights
### Required Data
```yaml
data_sources:
current_period:
- ledger.yaml (all transactions)
- budget.yaml (budget state)
historical:
- Previous month's ledger
- 3-month rolling average
- Year-to-date totals
from_core:
- Mood/energy from PhoenixClaw
- Goals from profile.md
- Patterns from growth-map.md
```
### Cross-Plugin Correlations
When PhoenixClaw Core data is available:
```yaml
correlations:
- source: mood
insight: "Spending correlates with mood patterns"
- source: energy
insight: "Low-energy days show 25% higher delivery orders"
- source: social
insight: "Social events drive 40% of entertainment spending"
```
## Privacy Considerations
### What Gets Stored
```yaml
stored_insights:
- Aggregated patterns (no individual transactions)
- Category trends
- Budget adherence metrics
never_stored:
- Specific merchant names (in insights)
- Exact amounts (use ranges)
- Personal judgments
```
### User Control
```yaml
user_controls:
disable_insights: false
insight_detail_level: normal # minimal | normal | detailed
exclude_categories: [] # Hide from insights
share_with_core: true # Allow PhoenixClaw Core integration
```
---
```
### references/goal-management.md
```markdown
# Financial Goal Management
This document defines how PhoenixClaw Ledger manages financial goals, tracks progress, and integrates with the daily journal and annual reports.
## Goal Types
PhoenixClaw Ledger supports four primary goal types:
### 1. Savings Goal (`savings`)
Long-term accumulation of funds for a specific purpose.
- **Example:** "存 5 万旅游基金" (Save 50,000 for travel fund)
- **Key Metrics:** Target amount, current balance, deadline.
### 2. Budget Control Goal (`budget_control`)
Strict limits on specific categories or behaviors over a period.
- **Example:** "本月餐饮不超 2000" (Food spending under 2,000 this month)
- **Key Metrics:** Category/Tag, spending limit, time period (weekly/monthly).
### 3. Habit Goal (`habit`)
Behavioral goals focused on consistency rather than currency.
- **Example:** "连续 7 天不叫外卖" (No takeout for 7 consecutive days)
- **Key Metrics:** Target behavior, current streak, target streak.
### 4. Wishlist Goal (`wishlist`)
Short-to-medium term savings for a specific item.
- **Example:** "存够买 MacBook" (Save enough for MacBook)
- **Key Metrics:** Item cost, allocated savings, progress percentage.
## Storage Schema
Goals are stored in `~/PhoenixClaw/Finance/goals.yaml`.
```yaml
# goals.yaml
goals:
- id: "goal_001"
name: "Travel Fund 2026"
type: savings
status: active # active | completed | cancelled | paused
currency: CNY
target_amount: 50000
current_amount: 12500
start_date: "2026-01-01"
deadline: "2026-12-31"
tags: [travel, savings]
created_at: "2025-12-20T10:00:00Z"
- id: "goal_002"
name: "Dine-out Limit"
type: budget_control
status: active
category: food
limit_amount: 2000
period: monthly
current_spent: 850
period_start: "2026-02-01"
period_end: "2026-02-28"
- id: "goal_003"
name: "Anti-Takeout Habit"
type: habit
status: active
behavior: "no_takeout"
target_streak: 7
current_streak: 4
best_streak: 12
last_triggered: "2026-02-02"
- id: "goal_004"
name: "MacBook Pro"
type: wishlist
status: active
item_cost: 15000
allocated_amount: 3000
priority: medium # low | medium | high
```
## Goal Workflow (CRUD)
### Create
- **Manual:** User adds goal via chat or direct YAML edit.
- **Automatic:** Ledger detects goal intent from conversation (e.g., "I want to save ¥10k for a bike").
- **ID Generation:** `goal_` prefix followed by incrementing index or hash.
### Read
- **Daily Scan:** PhoenixClaw Core scans `goals.yaml` during the 10 PM run.
- **Query:** User asks "How are my goals doing?".
### Update
- **Transaction-Driven:** Savings/Wishlist goals update when transactions with specific tags or descriptions are detected.
- **Budget-Driven:** `budget_control` goals update in real-time as transactions are categorized.
- **Behavioral:** `habit` goals update when daily memory analysis confirms the behavior (or lack thereof).
### Delete/Complete
- **Auto-Complete:** Triggered when `progress >= 100%`.
- **Manual Deletion:** User explicitly requests to stop tracking a goal.
## Progress Calculation
### Savings & Wishlist
Progress is a simple percentage of target reached.
```
progress_percent = (current_amount / target_amount) * 100
```
- **Example:** ¥12,500 / ¥50,000 = 25%
### Budget Control
Progress measures how much of the "allowance" has been consumed.
```
consumption_percent = (current_spent / limit_amount) * 100
status = "on_track" if (consumption_percent <= time_elapsed_percent) else "warning"
```
- **Time Elapsed %:** `(days_since_start / total_days_in_period) * 100`
### Habit
Progress is measured against the target streak.
```
streak_percent = (current_streak / target_streak) * 100
```
## Milestone Notifications
Milestones are highlighted in the daily journal's "Financial Growth" section.
| Milestone | Condition | Notification Style |
|-----------|-----------|--------------------|
| **Quarter-Way** | Progress reaches 25% | `[!insight]` Encouraging note |
| **Half-Way** | Progress reaches 50% | `[!success]` Celebration note |
| **Home Stretch** | Progress reaches 75% | `[!milestone]` Motivation boost |
| **Completed** | Progress reaches 100% | `[!success]` Achievement block |
### Notification Rules
- Only trigger once per milestone per goal.
- Max 2 milestone notifications in a single daily journal.
- Priority: Completed > 75% > 50% > 25%.
## Edge Case Handling
### 1. Deadline Passed
If `current_date > deadline` and `progress < 100%`:
- Status changes to `paused` (requires user intervention).
- Journal surfaces a `[!reflection]` callout asking if the goal is still relevant or needs a deadline extension.
### 2. Over-Budget (Budget Control)
If `current_spent > limit_amount`:
- Status flagged as `exceeded`.
- Immediate `[!alert]` in the daily journal.
- Calculation of required reduction in other categories to compensate.
### 3. Habit Break
If a habit behavior is violated:
- `current_streak` resets to 0.
- `[!reflection]` callout to identify the trigger/reason for the break.
### 4. Goal Modification
If a user changes a goal's target mid-way:
- Archive the previous progress state.
- Recalculate percentages from the new baseline.
## Integration Patterns
### Journal Output
Goals contribute to the `{{FINANCE_SUMMARY}}` and `{{GROWTH_NOTES}}` blocks:
- **Daily:** Milestone alerts and habit streak updates.
- **Weekly:** Summary of progress across all active goals.
- **Yearly:** Final status of all goals tracked during the year.
### Annual Report Format
Integration with `assets/yearly-report.md`:
```markdown
## Financial Goals
- Travel Fund 2026: ¥12,500/¥50,000 (25%) 🧗
- Dine-out Limit: ¥850/¥2,000 (42%) ✅
- Anti-Takeout Habit: 4/7 days streak (57%) 🔥
- MacBook Pro: ¥3,000/¥15,000 (20%) 🔋
```
```
### references/query-patterns.md
```markdown
# Real-time Financial Query Patterns
This document defines the query patterns and response templates for real-time financial inquiries supported by PhoenixClaw Ledger.
## Architecture Note
**Query parsing is an agent-level behavior.** The Ledger plugin provides the underlying data and logic for extraction, but the natural language understanding (NLU) required to map user questions to these patterns is handled by the OpenClaw agent. This document serves as a reference for the agent on how to interpret user intent and how to format the responses.
---
## 1. Time Range Queries (`time_range`)
Queries about total spending or income over a specific period (day, week, month, year).
### Patterns
| Language | Examples |
|----------|----------|
| **Chinese** | "今天花了多少", "这周支出了多少", "本月花费", "最近三天的开销" |
| **English** | "How much did I spend today?", "Total expenses this week", "Monthly spend so far", "Expenses for the last 3 days" |
### Response Template
```markdown
> [!summary] 💰 {{period_label}} Spending
> Total: **{{currency}}{{total_amount}}**
> Breakdown:
> - {{#each categories}}- {{name}}: {{currency}}{{amount}} ({{percent}}%){{/each}}
```
---
## 2. Category Queries (`category`)
Queries focused on specific spending categories (e.g., Food, Transport, Shopping).
### Patterns
| Language | Examples |
|----------|----------|
| **Chinese** | "在咖啡上花了多少", "餐饮支出是多少", "这个月打车花了多少", "购物开支" |
| **English** | "How much did I spend on coffee?", "Total for dining out", "Transport expenses this month", "Shopping spend" |
### Response Template
```markdown
> [!expense] 🏷️ {{category_name}}: {{period_label}}
> Total: **{{currency}}{{total_amount}}**
> Count: {{transaction_count}} transactions
> Recent:
> {{#each transactions}}- {{description}}: {{currency}}{{amount}} ({{date}}){{/each}}
```
---
## 3. Merchant Queries (`merchant`)
Queries about specific merchants or service providers.
### Patterns
| Language | Examples |
|----------|----------|
| **Chinese** | "星巴克消费记录", "最近去麦当劳花了多少", "在亚马逊买了什么" |
| **English** | "Starbucks transactions", "How much at McDonald's recently?", "What did I buy on Amazon?" |
### Response Template
```markdown
> [!receipt] 🛒 Merchant: {{merchant_name}}
> Total spent: **{{currency}}{{total_amount}}**
> Last visit: {{last_visit_date}}
> Transactions:
> {{#each transactions}}- {{date}}: {{currency}}{{amount}} ({{description}}){{/each}}
```
---
## 4. Budget Queries (`budget`)
Queries regarding current budget status and remaining limits.
### Patterns
| Language | Examples |
|----------|----------|
| **Chinese** | "还剩多少预算", "本月超支了吗", "我的预算情况", "预算进度" |
| **English** | "How much budget is left?", "Am I over budget?", "Show my budget status", "Budget progress" |
### Response Template
```markdown
> [!info] 🎯 Budget Status: {{period_label}}
> Used: **{{currency}}{{used_amount}}** / **{{currency}}{{budget_limit}}** ({{percent}}%)
> Remaining: **{{currency}}{{remaining_amount}}**
> {{#if over_budget}}> [!warning] ⚠️ Over budget by {{currency}}{{over_amount}}!{{else}}> Daily allowance: {{currency}}{{daily_allowance}} remaining{{/if}}
```
---
## 5. Comparison Queries (`comparison`)
Queries comparing spending between two periods or categories.
### Patterns
| Language | Examples |
|----------|----------|
| **Chinese** | "上周对比这周", "比起上个月支出如何", "这两次旅游花了多少对比" |
| **English** | "Compare this week to last week", "Spending vs last month", "Comparison between [Period A] and [Period B]" |
### Response Template
```markdown
> [!insight] 📊 Comparison: {{period_a}} vs {{period_b}}
> - {{period_a}}: **{{currency}}{{amount_a}}**
> - {{period_b}}: **{{currency}}{{amount_b}}**
> Difference: **{{diff_prefix}}{{currency}}{{diff_amount}}** ({{diff_percent}}%)
> {{#if decreased}}✨ You spent less than the previous period!{{else}}📈 Spending increased this period.{{/if}}
```
---
## Edge Case Handling
### 1. No Data Found
If no transactions match the query parameters.
- **Pattern**: "I couldn't find any records for [Category/Merchant] in [Period]."
- **Template**: `> [!info] 🔍 No records found for {{query_subject}} during this period.`
### 2. Ambiguous Time Range
If the user says "recently" or "a while ago" without specific dates.
- **Agent Behavior**: Default to "Last 30 days" and state the assumption.
- **Template**: `> [!info] 🕒 Showing records for the last 30 days (default).`
### 3. Unsupported Category
If the user asks for a category that hasn't been mapped yet.
- **Agent Behavior**: Search description fields for keywords and offer to create a new category mapping.
- **Template**: `> [!insight] 💡 I found {{count}} items related to "{{keyword}}", though they aren't in a specific category yet.`
### 4. Budget Not Set
If the user asks about budget but none is configured.
- **Agent Behavior**: Inform the user and provide the command to set one.
- **Template**: `> [!warning] ⚠️ No budget configured. Use "Set my monthly budget to [amount]" to start tracking.`
---
```