update
This commit is contained in:
164
vbt-snippets.md
164
vbt-snippets.md
@ -1,5 +1,5 @@
|
||||
- [DEBUGGING](#debugging)
|
||||
- [FETCHING DATA](#fetching-data)
|
||||
- [Fetching Data](#fetching-data)
|
||||
- [REINDEX to main session](#reindex-to-main-session)
|
||||
- [Smart indexing](#smart-indexing)
|
||||
- [Data manipulation](#data-manipulation)
|
||||
@ -9,7 +9,7 @@
|
||||
- [RESAMPLING](#resampling)
|
||||
- [config](#config)
|
||||
- [REALIGN](#realign)
|
||||
- [REALIGN\_CLOSING accessors](#realign_closing-accessors)
|
||||
- [REALIGN\_CLOSING accessors](#realignclosing-accessors)
|
||||
- [SIGNALS](#signals)
|
||||
- [Comparing](#comparing)
|
||||
- [GENERATE SIGNALS IRERATIVELY (numba)](#generate-signals-ireratively-numba)
|
||||
@ -28,11 +28,11 @@
|
||||
- [Stoploss/Takeprofit](#stoplosstakeprofit)
|
||||
- [SL - ATR based](#sl---atr-based)
|
||||
- [EXIT after time](#exit-after-time)
|
||||
- [CALLBACKS -](#callbacks--)
|
||||
- [CALLBACKS -](#callbacks)
|
||||
- [MEMORY](#memory)
|
||||
- [Portfolio](#portfolio)
|
||||
- [from signals](#from-signals)
|
||||
- [CALLBACKS](#callbacks)
|
||||
- [CALLBACKS](#callbacks-1)
|
||||
- [Access running total return from sim](#access-running-total-return-from-sim)
|
||||
- [Staticization](#staticization)
|
||||
- [Grouping](#grouping)
|
||||
@ -41,6 +41,15 @@
|
||||
- [PnL by hour of the day (BOXPLOT)](#pnl-by-hour-of-the-day-boxplot)
|
||||
- [PF resampling](#pf-resampling)
|
||||
- [PF Plotting](#pf-plotting)
|
||||
- [Key Portfolio Analysis Methods \& Properties](#key-portfolio-analysis-methods--properties)
|
||||
- [1. **Basic Portfolio Metrics**](#1-basic-portfolio-metrics)
|
||||
- [2. **Comprehensive Stats Method**](#2-comprehensive-stats-method)
|
||||
- [3. **Trade Analysis**](#3-trade-analysis)
|
||||
- [4. **Drawdown Analysis**](#4-drawdown-analysis)
|
||||
- [5. **Order Analysis**](#5-order-analysis)
|
||||
- [6. **Custom Metrics**](#6-custom-metrics)
|
||||
- [7. **Visualization Methods**](#7-visualization-methods)
|
||||
- [8. **Advanced Analysis Examples**](#8-advanced-analysis-examples)
|
||||
- [Entries/exits visual analysis](#entriesexits-visual-analysis)
|
||||
- [Configuration](#configuration)
|
||||
- [Optimalization](#optimalization)
|
||||
@ -104,7 +113,7 @@ ollCov.run(ts1, ts2, [2, 3], some_arg="some_value")
|
||||
```
|
||||
|
||||
|
||||
# FETCHING DATA
|
||||
# Fetching Data
|
||||
```python
|
||||
#fetching from remote db
|
||||
from lib.db import Connection
|
||||
@ -984,6 +993,150 @@ pf.trades.plot_expanding_mfe_returns().show() #expanding mea/mfe returns
|
||||
```
|
||||
[Plot Edge ratio](http://5.161.179.223:8000/static/js/vbt/features/analysis/index.html#edge-ratio) `pf.trades.plot_running_edge_ratio()`
|
||||
|
||||
|
||||
I'll research VectorBT PRO's portfolio analysis capabilities for you. Let me search for information about analyzing Portfolio objects, particularly those created by `Portfolio.from_signal`.Let me search for the correct Portfolio creation methods and analysis capabilities:Now let me search specifically for Portfolio analysis methods and attributes:Let me search for more specific information about Portfolio methods and examples:Let me search for specific Portfolio methods that provide analysis capabilities:Now let me find information about the Portfolio.from_signals method:Let me run some code to test the Portfolio analysis capabilities:Let me search for more specific Portfolio analysis examples and metrics:Based on my research of VectorBT PRO's Portfolio analysis capabilities, here's a comprehensive overview of how to analyze Portfolio objects (including those created by `Portfolio.from_signals`):
|
||||
|
||||
## Key Portfolio Analysis Methods & Properties
|
||||
|
||||
### 1. **Basic Portfolio Metrics**
|
||||
The Portfolio object provides numerous built-in properties for analysis:
|
||||
|
||||
- **Returns & Performance:**
|
||||
- `pf.returns` - Portfolio returns time series
|
||||
- `pf.total_return` - Total return percentage
|
||||
- `pf.annualized_return` - Annualized return
|
||||
- `pf.cumulative_returns` - Cumulative returns time series
|
||||
|
||||
- **Risk Metrics:**
|
||||
- `pf.sharpe_ratio` - Sharpe ratio
|
||||
- `pf.sortino_ratio` - Sortino ratio
|
||||
- `pf.max_drawdown` - Maximum drawdown
|
||||
- `pf.annualized_volatility` - Annualized volatility
|
||||
- `pf.value_at_risk` - Value at Risk
|
||||
- `pf.cond_value_at_risk` - Conditional Value at Risk
|
||||
|
||||
- **Portfolio Value & Cash:**
|
||||
- `pf.value` - Portfolio value time series
|
||||
- `pf.final_value` - Final portfolio value
|
||||
- `pf.cash` - Cash holdings over time
|
||||
- `pf.asset_value` - Asset value over time
|
||||
|
||||
### 2. **Comprehensive Stats Method**
|
||||
The most powerful analysis tool is the `stats()` method:
|
||||
|
||||
```python
|
||||
# Get default statistics
|
||||
pf.stats()
|
||||
|
||||
# Get specific metrics
|
||||
pf.stats(['total_return', 'sharpe_ratio', 'max_dd', 'total_trades'])
|
||||
|
||||
# Get all available metrics
|
||||
pf.stats('all')
|
||||
```
|
||||
|
||||
**Common metric names for `stats()`:**
|
||||
- `'total_return'` - Total return percentage
|
||||
- `'total_trades'` - Number of trades
|
||||
- `'win_rate'` - Winning trade percentage
|
||||
- `'sharpe_ratio'` - Sharpe ratio
|
||||
- `'sortino_ratio'` - Sortino ratio
|
||||
- `'max_dd'` - Maximum drawdown (note: `max_dd`, not `max_drawdown`)
|
||||
- `'calmar_ratio'` - Calmar ratio
|
||||
- `'omega_ratio'` - Omega ratio
|
||||
- `'expectancy'` - Expected value per trade
|
||||
- `'profit_factor'` - Profit factor
|
||||
- `'best_trade'` - Best trade return
|
||||
- `'worst_trade'` - Worst trade return
|
||||
- `'avg_winning_trade'` - Average winning trade
|
||||
- `'avg_losing_trade'` - Average losing trade
|
||||
|
||||
### 3. **Trade Analysis**
|
||||
Access detailed trade information through the `trades` property:
|
||||
|
||||
```python
|
||||
# Trade statistics
|
||||
pf.trades.stats()
|
||||
pf.trades.count() # Total number of trades
|
||||
pf.trades.win_rate # Win rate
|
||||
pf.trades.profit_factor # Profit factor
|
||||
|
||||
# Direction-specific analysis
|
||||
pf.trades.direction_long.count() # Number of long trades
|
||||
pf.trades.direction_short.count() # Number of short trades
|
||||
pf.trades.direction_long.pnl.sum() # Total long P&L
|
||||
pf.trades.direction_short.pnl.sum() # Total short P&L
|
||||
|
||||
# Trade records
|
||||
pf.trades.records_readable # Human-readable trade records
|
||||
pf.trade_history # Detailed trade history DataFrame
|
||||
```
|
||||
|
||||
### 4. **Drawdown Analysis**
|
||||
Analyze drawdowns using the `drawdowns` property:
|
||||
|
||||
```python
|
||||
pf.drawdowns.stats() # Drawdown statistics
|
||||
pf.drawdowns.max_duration # Maximum drawdown duration
|
||||
pf.drawdown # Drawdown time series
|
||||
```
|
||||
|
||||
### 5. **Order Analysis**
|
||||
Examine order execution details:
|
||||
|
||||
```python
|
||||
pf.orders.stats() # Order statistics
|
||||
pf.orders.records_readable # Human-readable order records
|
||||
```
|
||||
|
||||
### 6. **Custom Metrics**
|
||||
You can add custom metrics to the Portfolio class:
|
||||
|
||||
```python
|
||||
# Add custom metrics
|
||||
vbt.Portfolio.metrics["skew"] = dict(title="Skew", calc_func="returns.skew")
|
||||
vbt.Portfolio.metrics["kurtosis"] = dict(title="Kurtosis", calc_func="returns.kurtosis")
|
||||
|
||||
# Then use in stats
|
||||
pf.stats(['skew', 'kurtosis'])
|
||||
```
|
||||
|
||||
### 7. **Visualization Methods**
|
||||
Portfolio objects have built-in plotting capabilities:
|
||||
|
||||
```python
|
||||
pf.plot() # Default portfolio plot
|
||||
pf.plot_value() # Portfolio value over time
|
||||
pf.plot_cumulative_returns() # Cumulative returns
|
||||
pf.plot_drawdowns() # Drawdown plot
|
||||
pf.plot_underwater() # Underwater plot
|
||||
pf.trades.plot() # Trade analysis plots
|
||||
```
|
||||
|
||||
### 8. **Advanced Analysis Examples**
|
||||
|
||||
**Multi-parameter analysis:**
|
||||
```python
|
||||
# Combine multiple metrics into DataFrame
|
||||
metrics = [
|
||||
pf.total_return,
|
||||
pf.trades.win_rate,
|
||||
pf.sharpe_ratio,
|
||||
pf.max_drawdown,
|
||||
pf.trades.count()
|
||||
]
|
||||
keys = ['total_return', 'win_rate', 'sharpe_ratio', 'max_drawdown', 'trade_count']
|
||||
combined_stats = pd.concat(metrics, axis=1, keys=keys)
|
||||
```
|
||||
|
||||
**Performance optimization:**
|
||||
- Use `save_returns=True` in `Portfolio.from_signals()` to pre-calculate returns and speed up metric calculations
|
||||
- Enable caching for repeated analysis
|
||||
|
||||
This comprehensive analysis framework allows you to thoroughly evaluate portfolio performance from multiple angles - returns, risk, trade efficiency, and drawdown characteristics.
|
||||
|
||||
Would you like me to help you implement any specific analysis workflow, or do you have questions about particular metrics or methods?
|
||||
|
||||
## Entries/exits visual analysis
|
||||
|
||||
```python
|
||||
@ -1471,3 +1624,4 @@ nyse = get_calendar('NYSE')
|
||||
# Create a CustomBusinessDay object using the NYSE trading calendar
|
||||
custom_bd = CustomBusinessDay(holidays=nyse.holidays().holidays, weekmask=nyse.weekmask, calendar=nyse)
|
||||
```
|
||||
|
||||
|
||||
Reference in New Issue
Block a user