A trader using alternative data who already forecasted expected returns of different stocks want to find what is the optimal weights of his portfolio. Let’s input the users’ data in the optimization.
Our goal is to maximize the expected return given by the user divided by the square root of the variance and find what are the optimal weights for the portfolio.
goal = expected_return / variance.sqrt()
The optimization is run on 2 years of data from 01/01/2012 to 01/01/2014. A portfolio is created with 2 stocks: AAPL and GOOG. Expected return is inputted by user. Portfolio’s initial value is $1 million.
After running the optimzation, we found that the optimal weights are the following for Apple and Google. The first 3 months correspond to the warming period of the model.
We can also backtest our optimize porfotfolio. Here we decided to calculate the variance of the portfolio.
How to install hft Python package
Use Anaconda2, install JDK. Refer yourself to this manual.
conda install -c portfolioeffect hft
Implementation of the strategy using hft Python package
from hft.optimization import * from hft.metric import * import pandas as pd import time import datetime #Create Portfolio portfolio = Portfolio("2012-01-01 09:30:00", "2014-01-01 16:00:00", 'SPY') positionG = portfolio.add_position('GOOG', 10000) positionA = portfolio.add_position('AAPL', 10000) portfolio.settings(portfolioMetricsMode='price', inputSamplingInterval='30s', resultsSamplingInterval='1d', windowLength='50d') #Read expected return input data filename = 'return.csv' data = pd.read_csv(filename) #Optimize portfolio's weights variance = portfolio.variance() expected_return = portfolio.expected_return() goal = expected_return / variance.sqrt() optimizer = Optimizer(goal, direction="max") for symbol in list(set(data['symbol'])): temp = data[data.symbol == symbol] Time = [(time.mktime(datetime.datetime.strptime(i, "%m/%d/%Y").timetuple())+57600)* 1000 for i in temp['date']] optimizer = optimizer.forecast("ExpReturn", Metric([Time, list(temp['alpha'])], symbol)) optimalPortfolio = optimizer.run() #Plot optimal weights optimalPortfolio.get_position('AAPL').weight().plot(title='AAPL Weight') optimalPortfolio.get_position('GOOG').weight().plot(title='GOOG Weight') #Plot portfolio's variance optimalPortfolio.variance().plot(title='Portfolio Variance')