When evaluating the performance of an investing strategy, it is helpful to quantify the frequency, duration, and profitability of its independent bets, or "round trip" trades. A round trip trade is started when a new long or short position is opened and then later completely or partially closed out.
The intent of the round trip tearsheet is to help differentiate strategies that profited off a few lucky trades from strategies that profited repeatedly from genuine alpha. Breaking down round trip profitability by traded name and sector can also help inform universe selection and identify exposure risks. For example, even if your equity curve looks robust, if only two securities in your universe of fifteen names contributed to overall profitability, you may have reason to question the logic of your strategy.
To identify round trips, pyfolio reconstructs the complete portfolio based on the transactions that you pass in. When you make a trade, pyfolio checks if shares are already present in your portfolio purchased at a certain price. If there are, we compute the PnL, returns and duration of that round trip trade. In calculating round trips, pyfolio will also append position closing transactions at the last timestamp in the positions data. This closing transaction will cause the PnL from any open positions to realized as completed round trips.
In [1]:
%matplotlib inline
import gzip
import os
import pandas as pd
import pyfolio as pf
In [2]:
transactions = pd.read_csv(gzip.open('../tests/test_data/test_txn.csv.gz'),
index_col=0, parse_dates=0)
positions = pd.read_csv(gzip.open('../tests/test_data/test_pos.csv.gz'),
index_col=0, parse_dates=0)
returns = pd.read_csv(gzip.open('../tests/test_data/test_returns.csv.gz'),
index_col=0, parse_dates=0, header=None)[1]
In [3]:
# Optional: Sector mappings may be passed in as a dict or pd.Series. If a mapping is
# provided, PnL from symbols with mappings will be summed to display profitability by sector.
sect_map = {'COST': 'Consumer Goods', 'INTC':'Technology', 'CERN':'Healthcare', 'GPS':'Technology',
'MMM': 'Construction', 'DELL': 'Technology', 'AMD':'Technology'}
The easiest way to run the analysis is to call pyfolio.create_round_trip_tear_sheet()
. Passing in a sector map is optional. You can also pass round_trips=True
to pyfolio.create_full_tear_sheet()
to have this be created along all the other analyses.
In [4]:
pf.create_round_trip_tear_sheet(returns, positions, transactions, sector_mappings=sect_map)
Under the hood, several functions are being called. extract_round_trips()
does the portfolio reconstruction and creates the round-trip trades.
In [4]:
rts = pf.round_trips.extract_round_trips(transactions,
portfolio_value=positions.sum(axis='columns') / (returns + 1))
In [5]:
rts.head()
Out[5]:
In [7]:
pf.round_trips.print_round_trip_stats(rts)