stripe-projects
stripe projects
backtest-capital-accounting
Critical fix for backtest capital accounting when equity curves are inflated or drawdown metrics are meaningless
Full skill instructions
| Item | Details |
|---|---|
| Date | 2025-12-16 |
| Goal | Fix inflated equity curves and meaningless drawdown in backtests |
| Environment | Python 3.10, pandas, custom BacktestEngine |
| Status | Success |
Backtest engines often fail to properly track cash flows, leading to:
The bug is subtle because the backtest "runs" without errors but produces unrealistic results.
_open_position() Implementationdef _open_position(self, symbol, side, price, time, bar_idx, confidence):
"""Open position with proper capital accounting."""
# Apply slippage first
slippage = price * self.config.slippage_pct
entry_price = price + (slippage if side == 1 else -slippage)
# Calculate position size from AVAILABLE capital
position_value = self.capital * self.config.position_size_pct
shares = position_value / entry_price
# CRITICAL: Deduct full position value + commission from capital
total_cost = (shares * entry_price) + self.config.commission_per_trade
self.capital -= total_cost # <-- This line is often missing!
# Store position
self.positions[symbol] = Position(...)
_close_position() Implementationdef _close_position(self, symbol, price, time, bar_idx, reason):
"""Close position with proper capital accounting."""
position = self.positions[symbol]
# Apply slippage
slippage = price * self.config.slippage_pct
exit_price = price - (slippage if position.side == 1 else -slippage)
commission = self.config.commission_per_trade
# CRITICAL: Add sale proceeds (exit value - commission) to capital
if position.side == 1: # Long
sale_proceeds = position.shares * exit_price - commission
else: # Short
# Short P&L: entry - exit (profit when price falls)
sale_proceeds = (2 * position.shares * position.entry_price) - \
(position.shares * exit_price) - commission
self.capital += sale_proceeds # <-- This line is often wrong!
del self.positions[symbol]
_calculate_equity() Implementationdef _calculate_equity(self, current_price: float) -> float:
"""Calculate total equity = cash + market value of positions."""
equity = self.capital # Cash on hand
for position in self.positions.values():
if position.side == 1: # Long
market_value = position.shares * current_price
else: # Short
# Short market value: 2*entry - current (profit when price falls)
market_value = (2 * position.shares * position.entry_price) - \
(position.shares * current_price)
equity += market_value
return equity
| Attempt | Why it Failed | Lesson Learned |
|---|---|---|
| Only tracking P&L on close | Capital shows full value even with open positions | Must deduct on entry, add on exit |
Using capital = initial + sum(pnl) | Ignores unrealized gains/losses | Equity must include position market value |
| Not applying slippage to entry/exit | Overstated returns | Apply slippage before calculating shares/proceeds |
| Adding position value to capital on close | Double-counts - position value already in equity | Add sale PROCEEDS, not position value |
| Short position P&L = (entry - exit) * shares | Wrong sign when price rises | Use 2*entry - exit formula for short market value |
# BacktestConfig with proper defaults
@dataclass
class BacktestConfig:
initial_capital: float = 100_000.0
position_size_pct: float = 0.10 # 10% per position
commission_per_trade: float = 1.0 # $1 per trade
slippage_pct: float = 0.0005 # 0.05% slippage
stop_loss_pct: float = 0.02 # 2% stop
take_profit_pct: float = 0.04 # 4% TP
After fixing, verify with this test:
# After a round trip (buy then sell same shares):
# capital_after = capital_before + realized_pnl - 2*commission - slippage_cost
# If capital_after > capital_before + realistic_pnl, accounting is broken
stripe projects
Harvest every `ponytail:` comment in the codebase into a debt ledger, so the deliberate shortcuts and deferrals ponytail leaves behind get tracked instead of rotting into "later means never". One-shot report, changes nothing.
okx dex market
okx agentic wallet
gmgn portfolio
okx dapp discovery
okx agent payments protocol
Stripe payment processing with checkout sessions, subscriptions, webhooks, and customer management.
Build comprehensive 3-5 year financial models with revenue projections, cost structures, cash flow analysis, and scenario planning for early-stage startups. Use this skill when creating financial projections, calculating burn rate or runway, modeling fundraising scenarios, or preparing investor-r...
Stock and cryptocurrency analysis with portfolio management and multi-dimensional scoring.
Real-time crypto derivatives positioning, whale tracking, liquidations, and institutional ETF flows across 37 specialized tools.
Master dbt (data build tool) for analytics engineering with model organization, testing, documentation, and incremental strategies. Use when building data transformations, creating data models, or implementing analytics engineering best practices.
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Stay Ahead with Finalle.ai: The Ultimate Financial News and Tools Platform
AI-powered Pine Script code generator for TradingView
Research stocks at the speed of thought.
Empower your investment strategies with AI signals, option flow data, and advanced chart patterns.
Danelfin review covering its AI stock and ETF scores, rankings, portfolio tools, current pricing, strengths, risks, and alternatives for investors.
A software for comprehensive market sentiment analysis.
'Stock Correlations' App by Freshly.ai: Reveal Stock Patterns and Trends