0% found this document useful (0 votes)
259 views

Datacamp Python 3

This document provides an introduction to portfolio analysis in Python. It discusses key concepts like active return, tracking error, and active weights. It shows how to calculate these metrics in Python and analyze factor exposures using regression models. Professional portfolio analysis tools like Quantopian's Pyfolio package are also introduced, which can be used to backtest strategies and create performance and risk tear sheets.

Uploaded by

Luca Farina
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
259 views

Datacamp Python 3

This document provides an introduction to portfolio analysis in Python. It discusses key concepts like active return, tracking error, and active weights. It shows how to calculate these metrics in Python and analyze factor exposures using regression models. Professional portfolio analysis tools like Quantopian's Pyfolio package are also introduced, which can be used to backtest strategies and create performance and risk tear sheets.

Uploaded by

Luca Farina
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Comparing against a

benchmark
I N T R O D U C T I O N TO P O R T F O L I O A N A LY S I S I N P Y T H O N

Charlotte Werger
Data Scientist
Active investing against a benchmark

INTRODUCTION TO PORTFOLIO ANALYSIS IN PYTHON


Active return for an actively managed portfolio

Active return is the performance of an (active) investment, relative to the investment's


benchmark.

Calculated as the difference between the benchmark and the actual return.

Active return is achieved by "active" investing, i.e. taking overweight and underweight positions
from the benchmark.

INTRODUCTION TO PORTFOLIO ANALYSIS IN PYTHON


Tracking error for an index tracker

Passive investment funds, or index trackers, don't use active return as a measure for
performance.

Tracking error is the name used for the difference in portfolio and benchmark for a passive
investment fund.

INTRODUCTION TO PORTFOLIO ANALYSIS IN PYTHON


Active weights

1 Source: Schwab Center for Financial Research.

INTRODUCTION TO PORTFOLIO ANALYSIS IN PYTHON


Active return in Python
# Inspect the data
portfolio_data.head()

mean_ret var pf_w bm_w GICS Sector


Ticker
A 0.146 0.035 0.002 0.005 Health Care
AAL 0.444 0.094 0.214 0.189 Industrials
AAP 0.242 0.029 0.000 0.000 Consumer Discretionary
AAPL 0.225 0.027 0.324 0.459 Information Technology
ABBV 0.182 0.029 0.026 0.010 Health Care

1 Global Industry Classi cation System (GICS)

INTRODUCTION TO PORTFOLIO ANALYSIS IN PYTHON


Active return in Python
# Calculate mean portfolio return
total_return_pf = (pf_w*mean_ret).sum()

# Calculate mean benchmark return


total_return_bm = (bm_w*mean_ret).sum()

# Calculate active return


active_return = total_return_pf - total_return_bm
print ("Simple active return: ", active_return)

Simple active return: 6.5764

INTRODUCTION TO PORTFOLIO ANALYSIS IN PYTHON


Active weights in Python
# Group dataframe by GICS sectors
grouped_df=portfolio_data.groupby('GICS Sector').sum()

# Calculate active weights of portfolio


grouped_df['active_weight']=grouped_df['pf_weights']-
grouped_df['bm_weights']

print (grouped_df['active_weight'])

GICS Sector
Consumer Discretionary 20.257
Financials -2.116
...etc

INTRODUCTION TO PORTFOLIO ANALYSIS IN PYTHON


Let's practice!
I N T R O D U C T I O N TO P O R T F O L I O A N A LY S I S I N P Y T H O N
Risk factors
I N T R O D U C T I O N TO P O R T F O L I O A N A LY S I S I N P Y T H O N

Charlotte Werger
Data Scientist
What is a factor?
Factors in portfolios are like nutrients in food

INTRODUCTION TO PORTFOLIO ANALYSIS IN PYTHON


Factors in portfolios
Different types of factors:

Macro factors: interest rates, currency, country, industry

Style factors: momentum, volatility, value and quality

INTRODUCTION TO PORTFOLIO ANALYSIS IN PYTHON


Using factor models to determine risk exposure

1 Source: https://invesco.eu/investment 2 campus/educational 3 papers/factor 4 investing

INTRODUCTION TO PORTFOLIO ANALYSIS IN PYTHON


Factor exposures
df.head()

date portfolio volatility quality


2015-01-05 -1.827811 1.02 -1.76
2015-01-06 -0.889347 0.41 -0.82
2015-01-07 1.162984 1.07 1.39
2015-01-08 1.788828 0.31 1.93
2015-01-09 -0.840381 0.28 -0.77

INTRODUCTION TO PORTFOLIO ANALYSIS IN PYTHON


Factor exposures
df.corr()

portfolio volatility quality


portfolio 1.000000 0.056596 0.983416
volatility 0.056596 1.000000 0.092852
quality 0.983416 0.092852 1.000000

INTRODUCTION TO PORTFOLIO ANALYSIS IN PYTHON


Correlations change over time
# Rolling correlation
df['corr']=df['portfolio'].rolling(30).corr(df['quality'])

# Plot results
df['corr'].plot()

INTRODUCTION TO PORTFOLIO ANALYSIS IN PYTHON


Rolling correlation with quality

INTRODUCTION TO PORTFOLIO ANALYSIS IN PYTHON


Let's practice!
I N T R O D U C T I O N TO P O R T F O L I O A N A LY S I S I N P Y T H O N
Factor models
I N T R O D U C T I O N TO P O R T F O L I O A N A LY S I S I N P Y T H O N

Charlotte Werger
Data Scientist
Using factors to explain performance

Factors are used for risk management.

Factors are used to help explain performance.

Factor models help you relate factors to portfolio returns

Empirical factor models exist that have been tested on historic data.

Fama French 3 factor model is a well-known factor model.

INTRODUCTION TO PORTFOLIO ANALYSIS IN PYTHON


Fama French Multi Factor model

Rpf = α + βm MKT + βs SMB + βh HML


MKT is the excess return of the market, i.e. Rm − Rf
SMB (Small Minus Big) a size factor

HML (High Minus Low) a value factor

INTRODUCTION TO PORTFOLIO ANALYSIS IN PYTHON


Regression model refresher

INTRODUCTION TO PORTFOLIO ANALYSIS IN PYTHON


Difference between beta and correlation

INTRODUCTION TO PORTFOLIO ANALYSIS IN PYTHON


Regression model in Python
import statsmodels.api as sm

# Define the model


model = sm.OLS(factor_data['sp500'],
factor_data[['momentum','value']]).fit()

# Get the model predictions


predictions = model.predict(factor_data[['momentum','value']])

b1, b2 = model.params

INTRODUCTION TO PORTFOLIO ANALYSIS IN PYTHON


The regression summary output
# Print out the summary statistics
model.summary()

INTRODUCTION TO PORTFOLIO ANALYSIS IN PYTHON


Obtaining betas quickly
# Get just beta coefficients from linear regression model
b1, b2 = regression.linear_model.OLS(df['returns'],
df[['F1', 'F2']]).fit().params

# Print the coefficients


print 'Sensitivities of active returns to factors:
\nF1: %f\nF2: %f' % (b1, b2)

Sensitivities of active returns to factors:


F1: -0.0381
F2: 0.9858

INTRODUCTION TO PORTFOLIO ANALYSIS IN PYTHON


Let's practice!
I N T R O D U C T I O N TO P O R T F O L I O A N A LY S I S I N P Y T H O N
Portfolio analysis
tools
I N T R O D U C T I O N TO P O R T F O L I O A N A LY S I S I N P Y T H O N

Charlotte Werger
Data Scientist
Professional portfolio analysis tools

INTRODUCTION TO PORTFOLIO ANALYSIS IN PYTHON


Back-testing your strategy
Back-testing: run your strategy on historic data and see how it would have performed

Strategy works on historic data: not guaranteed to work well on future data -> changes in markets

INTRODUCTION TO PORTFOLIO ANALYSIS IN PYTHON


Quantopian's pyfolio tool

1 Github: https://github.com/quantopian/pyfolio

INTRODUCTION TO PORTFOLIO ANALYSIS IN PYTHON


Performance and risk analysis in Pyfolio
# Install the package
!pip install pyfolio
# Import the package
import pyfolio as pf

# Read the data as a pandas series


returns=pd.Series(pd.read_csv('pf_returns.csv')
returns.index=pd.to_datetime(returns.index)

# Create a tear sheet on returns


pf.create_returns_tear_sheet(returns)

# If you have backtest and live data


pf.create_returns_tear_sheet(returns, live_start_date='2018-03-01')

INTRODUCTION TO PORTFOLIO ANALYSIS IN PYTHON


Pyfolio's tear sheet

INTRODUCTION TO PORTFOLIO ANALYSIS IN PYTHON


Holdings and exposures in Pyfolio
# define our sector mappings
sect_map = {'COST': 'Consumer Goods',
'INTC': 'Technology',
'CERN': 'Healthcare',
'GPS': 'Technology',
'MMM': 'Construction',
'DELL': 'Technology',
'AMD': 'Technology'}

pf.create_position_tear_sheet(returns, positions,
sector_mappings=sect_map)

INTRODUCTION TO PORTFOLIO ANALYSIS IN PYTHON


Exposure tear sheet results

INTRODUCTION TO PORTFOLIO ANALYSIS IN PYTHON


Let's practice!
I N T R O D U C T I O N TO P O R T F O L I O A N A LY S I S I N P Y T H O N

You might also like