Forecasting Model Enhance Portfolio Optimization in Energy Stock Trading


Quants Method in Finance 4073
Forecasting Model Enhance Portfolio Optimization in Energy Stock Trading
Due: 12/14/2012

Professor: Alexander Greyserman
Group members: Feng Yu

1. Introduction 1
2. Data Preparation 1
3. Trading Model Construction and In sample analysis 2
3.0 Energy stocks as main investment vehical 2
3.1 Defensive Stocks 2
3.2 Classic Portfolio optimization framework 3
3.3 Forecasting model enhanced Portfolio optimization trading strategy 4
3.3.1 Forecasting model 5 Time Series approach(Rejected) 5 Moving Average approach 6
3.3.2 Trading Strategy Execution detail 7
4 Risk Management 8
5 Transcation cost 9
6 Leverage 10
7 Backtesting 10
8 Conclusion 11
9 Limitation and future study 12
10 Reference 12
11 Appendix 14


The Markowitz’s Modern Portfolio Theory (MPT) and the Capital Asset Pricing Model (CAPM) are milestones in asset pricing and management in both the academy and the industry. These two theories are elegant theoretical achievements that have revolutionized the vision of Finance and Economics.In this paper , my team will build winning trading strategy upon the portfolio optimization . First, my team built balanced portfolio which combined high performance energy stocks and defensive stocks. Then, using forecasting model generated expected return, the trading strategy utilized dynamics portolio optimizatoin to rebalance expsures as the market fluctuates. In addtion , risk management process was building into this trading agrithm to balance the trade off of risk and return to achieve the optimal . Overall , our trading strategy will producing strong risk adjusted return in both up and down markets.

Data Preparation
In this paper, we choosed daily closing price of 7 US oil stocks (NYSE:SU, NYSE:CVX) and 3 defensive stocks (NYSE:) that spanning 11 years from Yahoo Finance to fit the time series model. The data spans from 1/3/1999 to 11/20/2012. S&P 500 index were used for benchmarking , this index was download from bloomburg for the same time span. This project also controled oil price as an exogenous variable. WTI Crude oil daily closing spot price was extracted from for the same time span. Matlab script was used to automate data extraction from Yahoo Finance. Data analysis and model fitting is done in R and Matlab.

One issue we entered is that the closing price series are clearly upward trending. In order to detrend and get stationary series, one step difference and log transformation were applied. The result log return series is stationary series, which passed our stationary test.

Another 2 issues are dividend adjustment and missing data. Since all dividends paid to shareholders, dividend ajusted returns were calculated. For missing crude oil spot price due to the different holiday schedule between NYSE and Chicago Commodity exchange, we used previous business day closing price instead.

Trading Model Construction and In sample analysis

Energy stocks as main investment vehical

The energy sector should be a key componet of any savvy investor’s portfolio. Energy stocks currently represent a 11.3% weighting of the benchmark S&P 500 Index and this sector has delivered exceptional investment returns over the 24-year period ending December 31,2010. Even taking into account of the big drop caused by 2008 financial crisis , the energy sector still has returned overall 10.54% on an annualized basis over past 20 years period.

Looking forward , our team believe the energy sector , expecially oil stocks , will remain performing strong in next 20 years, there are 4 main reasons that favor owning energy stock in a winning portfolio. First of all , Global demand for energy service will continue to accelerate . Secondly , future supplies of oil will be harder to find and more costly to extract. Thirdly , the strong financial characteristics of energy firms, including rising dividends, will be key feature which will lead to higher future stock price. Last but not least , considering the nomial money injected through 3 rounds of Quantitative Easing , energy stock will be a strong inflatoin hedge.

The combination of these factors should enable energy sector to continue to generate the above market average return in next 20 years. This is the first major reason my team like to invest our portflio intensively in this sector .

Another major reason is that the energy sector has very high volatility and mean reverse pattern. Combination of these two features offers the opportunity for our trading strategy to generate the profit when market rallys or even when market declines. This paper will discuss this in detail in section ()

Our team picked picked total 7 oil stocks() from this sector mainly based on two criteria : highest average return in past 10 years and large proven oil reserves. For example, Suncor Inc. may not have highest average return , but it own largest oil sand field,which can garantee more than 100 years production based on current forecast.

However , just like any investment instruments , there are many market threats which may significantly weak the return potential of this sector. We will adjust this in “Limitation and future study” section.

Defensive Stocks

Like any market sector with high return , energy sector is very sensitive to economics and political shock and has exceptional high volatily. For example , during 2008 financial crisis , the max draw down for Suncor Inc is ().

Like section 3.0 stated , higher volatilty is an attractive feature since it offer opportunity for our trading strategy to generate profit from both upward and downward price move. However, extreme price moves, such as what we experienced during 2008 crsis period, are unfavorable . In addition, during the period , whole sector was moved in the same direction limited our trading strategy’s ability to balance the portfoilo . Therefore , it is necessary to include denfensive stocks which is weakly correlated with energy sector or recession resistent to balance the whole portfoio , even these defensive stocks may have lower return.

Based on the literature , the technology sector has relative low correlation with energy sector . This project picked two stocks from this sector. Apple (NYSE:AAPL) and Microsof (MYSE: MSFT) .

Walmat is well know recession stock , which perform very stable during the recession, even 2008 crisis period. This stock was also included in our portfolio as key recession hedge. (The plot attached blew shows: Walmart VS Suncor price series)

Classic Portfolio optimization framework

Modern portfolio theory (MPT) is a theory of finance which attempts to maximize portfolio expected return for a given amount of portfolio risk, or equivalently minimize risk for a given level of expected return, by carefully choosing the proportions of various assets.

The fundamental concept behind MPT is that the assets in an investment portfolio should not be selected individually, each on their own merits. Rather, it is important to consider how each asset changes in price relative to how every other asset in the portfolio changes in price.

Investing is a tradeoff between risk and expected return. In general, assets with higher expected returns are riskier. For a given amount of risk, MPT describes how to select a portfolio with the highest possible expected return. Or, for a given expected return, MPT explains how to select a portfolio with the lowest possible risk (the targeted expected return cannot be more than the highest-returning available security, of course, unless negative holdings of assets are possible.)

Therefore, MPT is a form of diversification. Under certain assumptions and for specific quantitative definitions of risk and return, MPT explains how to find the best possible diversification strategy.

Forecasting model enhanced Portfolio optimization trading strategy
Portfolio optmization can generate optimal asset allocation which perfectly balancing the risk and return. However , based on original setting , the model used the insample return average as return expecation to feed into the model . This may offer stability to the model to ensure it will generate the result, but it may not be an idea approach to generate optimal asset allocation for future period,especially for energy sector.

In energy sector , the return is highly sensive to all kinds of external shock . In most of case , the specific future return will significantly deviate from the in sample mean return. More important, the sample mean return will not be a good estimate of furture return.

In light of this , our team will use Forecsting model generated future return as the input to achieve the idea assect allocation for future period.

Forecasting model
In the project , we applied two forecasting model, time series approach and moving average approach, to generate the return expectation .

Rejected :Time Series approach
In order to find best fitted time series model , we fit model for each individual energy stock. Since the result is very similar, in this paper , withoust loosing generosity , the result of Chevron Corporation(NYSE: cvx) was presented as example.

ARMA model definition

The process is said to be ARMA (p, q) process if {Xt} is stationary and if for every t,
where Zt~WN (0, ).

This model bases on the following assumption:
Before we fit time series model, we assume that the sequence of data is Weak Stationarity: Generally speaking,the mean and the variance of a stochastic process do not depend on t (that is they are constant) and the autocovari-ance between and only can depend on the lag p (p is an integer, the quantities also need to be finite). This assumption can be justified by Dicky-Fuller test.

We also assume that the innovations are iid White noise distributed as WN (0, ).

Model estimation

The log return series passed the stationary test (the resulted Augemented DF test is -15.7585, and the p value is 0.01), no further lag difference is required. Therefore an ARMA (p, q) model is suggested. According to the AIC criterian, we arrive a ARMA (2, 2) model.
The fitted model is

Fitted model analysis and reason for rejection
In order to test goodness of fit and the forecasting power of this fitted time series model , my team ploted the return vs innovation (attached below). Surprisingly, we find these two plots have exactly same shape , which means fitted model didn’t explain data well. The return variation cannot by digest by this model , in turn this model will not be able to offer any form of forecasting power. This approach is rejected.

In order to find the reason for this shocking results, my team rechecked fitted ARMA(2,2) model . This model is backward looking into last two periods and through autoregression further look back to previous periods. This setting is not good fit for the energy sector. The oil stock price is mainly driven by the news . By definition news may have very few correlation with previous period. Therefore, it is hard to generate the good prediction under the framework of timeseries model ARMA(2,2)

Moving Average approach
Why Moving Average will be a good estimater for future return?
Due to the nature of energy stocks, the stock price is highly correlated with the oil price. Based on the literature , the oil price exhibits strong mean reversion pattern , which always has tendency move toward its intrinsic value , which is decided by the marginal production cost and long term supply and demand condition. In turn, we may expect that energy stock prices also have mean reversion pattern. From the oil stock price time series plot , random walk with trend will be most appropriate model to fit the price move. Therefore , the moving average of most recent period price will be the best estimate of the future price. Then we can use the expected price to get the expect return for the future period.
E(P_(t+1) )=(P_t+P_(t-1)+⋯+P_(t-(n-1)))/n

E(r_(t+1) )=(E(P_(t+1)) – P_t)/P_t

Type of moving average and Moving window size

My team compared simple moving average , weighted moving average and exponetial moving average approach. Based random walk with trend model, the last two approaches don’t have any theorical or pratical advantange . In order to simplify the calcuation, we choose simple moving average approach.

Using in sample data , we will test and compare windows size: 30 , 60 ,90 and 120 days.

Trading Strategy Execution detail

Considering transcation cost, daily balancing will not generate any profit. This project will only consider monthly balancing for two reasons. First of all, compare to weekly transcation , monthly transcation has cleary cost benefit which can offset the potential drawbacks. Secondly, this trading strategy heavily relies on the mean reverse characteristic of oil stock price time series. Therefore , it is critical to give stock time to move toward its short term means.

Based on our trading strategy, for each month, the portfolio will rebalanced on first business day. First , expected return for 7 energy stocks will be calucated based on the corresponding moving window(30,60, 90 and 120 days). In order to stabilize the model , defensive stock will using the average in sample return as expected return. In second step, expected return will be feed into portfolio optimization to generate the asset weight . Then , in third step, we will use the last period stock holding number vector dot product with current stock price vector to generate current market value. The allocating this total dollar amount to each stock to generate new stock holding number vector and dollar amount vector for next period.

If we difference and sum last period total dollar amount stock holding vector , then we will get the total transcation volume , then times transcation cost rate, we will get transcation cost.

Monthly transcation will moving forward for each month from 2000 to 2011.

Risk Management
Risk measurement & cVaR calcuation

A new approach to optimizing or hedging a portfolio of financial instruments to reduce risk is presented and tested on applications. It focuses on minimizing Conditional Value-at-Risk (CVaR) rather than minimizing Value-at-Risk (VaR), but portfolios with low CVaR necessarily have low VaR as well. CVaR, also called Mean Excess Loss, Mean Shortfall, or Tail VaR, is anyway considered to be a more consistent measure of risk than VaR.

Central to the new approach is a technique for portfolio optimization which calculates VaR and optimizes CVaR simultaneously. This technique is suitable for use by investment companies, brokerage firms, mutual funds, and any business that evaluates risks. It can be combined with analytical or scenario-based methods to optimize portfolios with large numbers of instruments, in which case the calculations often come down to linear programming or nonsmooth programming. The methodology can be applied also to the optimization of percentiles in contexts outside of finance.

An alternative to VaR which is more sensitive to the shape of the tail of the PDF. n% CVaR is the expected loss conditionally averaged over % of worst possible outcomes:

Risk adjustment process

In our project, We use historical return rate(1999-2006) of the 10 equities to estimate the conditional var. Based on the correlation matrix of the 10 equities and historical return rate, we calculate the multi-density function of return rate, then we use Monte Carlo Method to simulate 10000 samples from this density. (each sample is a 10-dim vector)

For each time span, we have a-10 dim portfolio optimization weight of equities and the weight multiple each sample is the ultimate return rate:

We got 10000 ultimate return rate sample and the 5% financial loss of a certain holding time is as below: (VAR=-0.0160999 , CVAR=-0.02192215).

If the CVAR of a period is less than the default threthold (-0.04), we will increase the risk aversion setting in Matlab, so the weight of risk-free potfolio will increase and the weight of equities will decrease. But the internal weight of each equity will not change.

If the CVAR of a period is larger than the default threthold (-0.04), we will decrease the risk aversion setting in Matlab, so the weight of risk-free potfolio will decrease and the weight of equities will increase. But the internal weight of each equity will not change.

Transcation cost
In this project , we assumed that the transaction cost is 5 basis points. All results were transaction costs extracted. Transaction cost has material impact on the portfolio performance. For 90 days no leverage case, total transaction for 10 years period (beginning portfolio size $100,000) is $365,250, which dragged down annual return by 2.21%.

In this project , we tested both unleveraged and leverage scenario. Under the unleveraged case, we will allow each stock to hold maximum of 100% and minimum of 0% portfolio value . In the leveraged case, each stock was allow to short sell 100% of portfolio value and hold maximum of 150% of portfolio value.

In both in sample and out sample result, we can clearly see the ability to leverage will significantly increase the return.

In sample result
This project treated return series between 2000 and 2006 as in sample data. In this time window, we calculated the sharp ratio ,variance of both leveraged and unleveraged case for all moving windows size, the result summary has been attached .

In Sample
Moving windows 30 60 90 120
Sharp Ratio 0.1428 0.1655 0.2585 0.1271
Variance 0.0059 0.0059 0.0056 0.0064
Sharp Ratio(Leverage) 0.1237 0.1724 0.1726 0.1301
Variance (Leverage) 0.0294 0.0293 0.0269 0.0267

Based on the insample data, 90 days moving average result is clear winner with highest sharp ratio. At the same time, variance is lowest. Therefore , we will use 90 days moving as moving windows.

2007-2012 data are using as out sample data to conduct back testing. (Result has been attached below). Exactly same as the in sample result, for no leveraged case, 90 days moving average still performed well.

But in leveraged case, 30 days moving average outperformed the rest . More important , there is trend that smaller the window size , the higher return the portfolio can achieve. This result is contradicting the conclusion from in sample data.

In light of this finding, we compared the in sample and out sample period. The main difference is that during out sample period , there is extremely high volatility period which is caused by 2008 financial crisis. During the period , the price move is very dramatic. This may explain why 30 days moving window will perform better. Due to smaller size of time windows, the moving average has larger move. In turn , the expected return will have higher variance. More extreme expected return will lead to more dramatic asset allocation. If the expected return was on the correct side , it will certainly lead to better result.

However, considering the maginitude of 2008 financial crisis, looking forward, market will more likely to act close to in sample period than out sample. Therefore, We still recommend to use 90 days moving average windows .
Out Sample
Moving windows 30 60 90 120
monthly return 101.34% 101.14% 101.27% 101.15%
annual return 117.27% 114.54% 116.30% 114.74%
Initial value $320,730 $461,840 $723,920 $333,190
End value $823,050 $1,030,900 $1,768,800 $751,580

Out Sample Leveraged
Moving windows 30 60 90 120
monthly return 107.50% 105.43% 104.49% 104.32%
annual return 238.25% 188.54% 169.38% 166.03%
Initial value $702,940 $1,400,700 $1,329,700 $759,220
End value $119,590,000 $59,680,000 $30,053,000 $15,245,000

Result and Benchmarking

In order to evaluate our trading strategy , we compare the result to two benchmarks (daily mark to market plot has been attached: Green line is our Portfolio, Red line is Energy index, Blue line). The energy index is caluated under setting: buy and hold equal weight of 7 selected oil stock for the whole time span.

Our portfolio with annualized return 116.3% easily beated S&P500(flat) and Energy index(annualized return 114.3%).

In the plot , it is worth to point out there is large daily draw down during 2008 crisis period. This is mainly due to the nature of monthly balancing, the trading agorithm didn’t have chace to balance the portfolio within the month. However, considering the amount of transcation cost, this may be the necessary evil .

The result of both in sample and out sample analysis indicated that 90 days moving average generated good trading results in the regular market setting (i.e. no extrem market move close to the magnitude during 2008 crisis period).

During crisis period, we can take advantage of leverage , then 30 days moving average may generate better result.

Limitation and future study
Though having many attractive features, energy stock, main investment vehical of our trading strategy , may not perform well in next 10 year for a few reasons. First of all , alternative energy may have negative impact on the oil firm stock price . Secondly, new technology such as gas hydrate exploration & production may push down oil price price, this may harm oil firm’s income potential . Last but not least , overall economy may not recover quick enough to generate sufficent demand for oil to sustain current oil price. Therefore , investor who are using this trade strategy should pay attention to the developement of all these potential threat. In the future study, we may refine the trading model to taking into account of the possible impact of these threats.


[1] Tim Bollerslev, (1986), ” Generalized autoregressive and conditional heteroskastics”, Journal of Econometrics 31 (1986),Duke University
[2] Bollerslev T., Engle R.F., NelsonD.B., (1994); ARCH Model, Handbook of Econometrics Volume IV, Chapter 49, 2961-3031 edited by Engle and McFadden, Elsevier Science.
[3] Bollerslev T., Ghysels E., (1996); Periodic Autoregressive Conditional Heteroscedasticity, Journal of Business and Economic Statistics 14, 139-151.
[4] Brooks R.D., Faff R.W., Mckenzie M.D., Mitchell H., (2000); A Multi-Country Study of Power ARCH Models and National Stock Market Return, Journal of International Money and Finance 19, 377-397. PDF
[5] Engle R.F., (2001); GARCH 101: An Introduction to the Use of ARCH/GARCH models in Applied Econometrics, forthcoming Journal of Economic Perspectives. PDF
[6] Harvey A.C., (1981); The Econometric Analysis of Time Series, Oxford.
[7] Lambert P., Laurent S., (2001); Modeling Financial Time Series Using GARCH-Type Models and a Skewed Student Density, Mimeo, University de Liege.
[8] Mincer J., Zarnowitz V., (1969); The Evaluation of Economic Forecasts, in: Economic Forecasts and Expectations, edited by J.Mincer, New York, National Bureau of Economic Research.
[9] Taylor S., (1986); Modeling Financial Time Series, Wiley, New York.
[10] Kim, Y.S., Rachev, S.T., Chung, D.M., Bianchi, M.L., 2009. The modified tempered stable distribution, GARCH-models and option pricing. Probability and Mathematical Statistics 29 (1), 91-117.
[11] D.Marcek, “Stock Price forecasting: Statistical, classical and fuzzy neural network approach,” in MDAI, ser. Lecture Notes in Computer Science, V.Torra and Y. Narukawa, Eds., vol. 3131. Springer, 2004, pp. 41-48.
[12] T. Sandhom, “Autoregressive time series forecasting of computational demand,” CoRR, vol. abs/0711.2062, 2007
[13] H.Y. Kwok, C.M. Chen, and L. Xu, “Comparison between mixture of ARMA and mixture of AR model with application to time series forecasting,” in Proceedings of Fifth International Conference on Neural Information Processing, 1998, pp. 1049-1052.
[14] Ross, S.A. (1976). The arbitrage theory of capital asset pricing. J. Econom. Theory 13341?360. MR0429063
[15] Zhou, X.Y. and Li, D. (2000). Continuous time mean-variance portfolio selection: A stochastic LQ framework. Appl. Math. Optim. 42 19?33. MR1751306
[16] Zhou, X.Y. and Yin, G. (2003). Markowitz’ mean-variance portfolio selection withregime switching: A continuous time model. SIAM J.
Control Optim. 42 1466?1482.MR2044805


Mathlab script:

function [hist_date, hist_high, hist_low, hist_open, hist_close, hist_vol] = get_hist_stock_data(stock_symbol)

% Define starting year (the further back in time, the longer it takes to download)
start_year = ‘1999’;

% Get current date
%[this_year, this_month, this_day, dummy, dummy] = datevec(date);
this_year = 2012;
this_month = 12;
this_day = 4;

% Build URL string
url_string = ‘’;
url_string = strcat(url_string, ‘&s=’, upper(stock_symbol) );
url_string = strcat(url_string, ‘&d=’, num2str(this_month-1) );
url_string = strcat(url_string, ‘&e=’, num2str(this_day) );
url_string = strcat(url_string, ‘&f=’, num2str(this_year) );
url_string = strcat(url_string, ‘&g=d&a=0&b=1&c=’, start_year);
url_string = strcat(url_string, ‘&ignore.csv’);

% Open a connection to the URL and retrieve data into a buffer
buffer =……

% Read the first line (a header) and discard
dummy = readLine(buffer);

% Read all remaining lines in buffer
ptr = 1;
while 1
% Read line
buff_line = char(readLine(buffer));

% Break if this is the end
if length(buff_line)<3, break; end % Find comma delimiter locations commas = find(buff_line== ','); % Extract high, low, open, close, etc. from string DATEvar = buff_line(1:commas(1)-1); OPENvar = str2num( buff_line(commas(1)+1:commas(2)-1) ); HIGHvar = str2num( buff_line(commas(2)+1:commas(3)-1) ); LOWvar = str2num( buff_line(commas(3)+1:commas(4)-1) ); CLOSEvar = str2num( buff_line(commas(4)+1:commas(5)-1) ); VOLvar = str2num( buff_line(commas(5)+1:commas(6)-1) ); adj_close = str2num( buff_line(commas(6)+1:end) ); %Adjust for dividends, splits, etc. DATEtemp{ptr,1} = DATEvar; OPENtemp(ptr,1) = OPENvar * adj_close / CLOSEvar; HIGHtemp(ptr,1) = HIGHvar * adj_close / CLOSEvar; LOWtemp (ptr,1) = LOWvar * adj_close / CLOSEvar; CLOSEtemp(ptr,1)= CLOSEvar * adj_close / CLOSEvar; VOLtemp(ptr,1) = VOLvar; ptr = ptr + 1; end % Reverse to normal chronological order, so 1st entry is oldest data point hist_date = flipud(DATEtemp); hist_open = flipud(OPENtemp); hist_high = flipud(HIGHtemp); hist_low = flipud(LOWtemp); hist_close = flipud(CLOSEtemp); hist_vol = flipud(VOLtemp); stockNameList = {'su' ;'cvx';'bp';'imo';'mro';'tot'; 'xom';'aapl';'msft';'wmt'}; nStock = length(stockNameList); timePeriod = 3495; m_hist_close=zeros(timePeriod,nStock); m_hist_open=zeros(timePeriod,nStock); %m_return=zeros(timePeriod-1,nStock); for i = 1:nStock [hist_date, hist_high, hist_low, hist_open, hist_close, hist_vol] = get_hist_stock_data(stockNameList(i)); m_hist_close(:,i) = hist_close(1:timePeriod); m_hist_open(:,i) = hist_open(1:timePeriod); end; % Generate return m_return = price2ret(m_hist_close); [m n] = size(m_return); m_e_return = zeros(m,n); % Generate expected return using 30 moving average nDay = 90; for i = 253:3494 meanPrice = mean(m_hist_close(i-nDay: i,:)); m_e_return(i,:)= log(meanPrice./m_hist_close(i,:)); end; %find first day of month firstDayMonth=zeros(156,2); monthPrice=zeros(156,nStock); monthTC=zeros(156,nStock); j=1; monthDate=hist_date(1:156); for i=231 : 3496 if month(hist_date(i))~= month(hist_date(i-1)) firstDayMonth(j)=i; monthDate(j)=hist_date(i); monthPrice(j,:)=m_hist_close(i,:); j=j+1; end; end; TranscationFactor=0.005; %Portfoilo value pval = 1; aRiskfreeRate = 0.04; RiskfreeRate =(1+aRiskfreeRate)^(1/12)-1; %RiskfreeRate =0.04; aBorrowRate = 0.07; BorrowRate = (1+aBorrowRate)^(1/12)-1; %BorrowRate=0.07; RiskAversion = 3; numPorts = nStock; %get covariance % cCov=cov(m_hist_close); %covariance using monthly price monthlyReturn=monthPrice(2:156,:)./monthPrice(1:155,:)-1; cCov=cov(monthlyReturn); % monthly_Wts=zeros(157,nStock); monthly_Return=zeros(157,nStock); monthly_Risk=zeros(157,nStock); monthly_RiskyFactor=zeros(157,nStock); monthly_PortValue=zeros(157,nStock); monthly_StockNum=zeros(157,nStock); monthly_ExceptionI=zeros(157,1); monthly_PortValue(1)=100000; %setup constrain A=[0 0 0 1]; b=[0.8]; conSet=[A,b]; AssetMin=[0 0 0 0 0 0 0 0 0 0]; AssetMax=[1 1 1 1 1 1 1 1 1 1]; %AssetMin=[-1 -1 -1 -1 -1 -1 -1 -1 -1 -1]; %AssetMax=[1.5 1.5 1.5 1.5 1.5 1.5 1.5 1.5 1.5 1.5]; includeTC =1; %nonTangent=0; for i= 2 : 156 meanPrice = mean(m_hist_close(firstDayMonth(i)-nDay: firstDayMonth(i),:)); currentReturn= meanPrice./m_hist_close(firstDayMonth(i),:)-1; constraint = portcons('PortValue',pval,numPorts,'AssetLims',AssetMin, AssetMax,numPorts); [PortRisk,PortRet,PortWts]=portopt(currentReturn,cCov,50,[],constraint); try [riskyRisk,riskyReturn,riskyWts,riskFraction,overallRisk,overallReturn] = portalloc(PortRisk,PortRet,PortWts,RiskfreeRate,BorrowRate,RiskAversion); catch exception monthly_Wts(i,:)=monthly_Wts(i-1,:); monthly_RiskyFactor(i)=monthly_RiskyFactor(i-1); monthly_Return(i)=monthly_Return(i-1); monthly_Risk(i)=monthly_Risk(i-1); monthly_ExceptionI(i)=1; nonTangent=0; if i~=2 monthly_PortValue(i)=dot(monthly_StockNum(i-1,:),m_hist_close(firstDayMonth(i),:)); else monthly_PortValue(i)=monthly_PortValue(i-1); end monthly_StockNum(i,:)=(monthly_Wts(i,:)*monthly_PortValue(i))./m_hist_close(firstDayMonth(i),:); continue end if isnan(monthly_Wts(i)) monthly_Wts(i,:)=monthly_Wts(i-1,:); else monthly_Wts(i,:)=riskyWts; end monthly_RiskyFactor(i)=riskFraction; monthly_Return(i)=riskyReturn; monthly_Risk(i)=riskyRisk; if i~=2 monthly_PortValue(i)=dot(monthly_StockNum(i-1,:),m_hist_close(firstDayMonth(i),:)); else monthly_PortValue(i)=monthly_PortValue(i-1); end monthly_StockNum(i,:)=(monthly_Wts(i,:)*monthly_PortValue(i))./m_hist_close(firstDayMonth(i),:); monthTC(i)=sum((abs(monthly_StockNum(i,:)-monthly_StockNum(i-1,:)).*m_hist_close(firstDayMonth(i),:)))*TranscationFactor; if includeTC==1 monthly_PortValue(i)= monthly_PortValue(i)-monthTC(i); end end; plot(FResult30MAValue); FResult30MAValue=monthly_PortValue(:,1); FResult30MAValue(1:156); r30_1=price2ret(FResult30MAValue(1:86)); r30_2=price2ret(FResult30MAValue(87:156)); r30=price2ret(FResult30MAValue); x1=sharpe(r30_1,RiskfreeRate); x2=sharpe(r30_2,RiskfreeRate); x1 x2 var1=var(r30_1); var2=var(r30_2); var1 var2 monthly_PortValue(85,1) monthly_PortValue(156,1) [MDD, MDDs, MDDe, MDDr]=MAXDRAWDOWN(r30); r30ts=timeSeries(r30(1:155),monthDate(1:155)); r30ts.TimeInfo.Units='months'; r30ts.TimeInfo.Format='mm,yyyy'; plot(r30ts); r30ts=timeSeries(FResult30MAValue(1:155),monthDate(1:155)); r30ts.TimeInfo.Units='months'; r30ts.TimeInfo.Format='mm,yyyy'; plot(r30ts); showSeries=[m_hist_close(:,2),m_hist_close(:,10)]; %showSeries=hist_close; resultTS=timeSeries(showSeries,hist_date(1:3495)); resultTS.TimeInfo.Units='months'; resultTS.TimeInfo.Format='mm,yyyy'; plot(resultTS); m_daily_wts=zeros(timePeriod,nStock); m_daily_PortValue=zeros(timePeriod,nStock); j=1; for i=231 : 3495 if month(hist_date(i))~= month(hist_date(i-1)) j=j+1; m_daily_wts(i,:)=monthly_StockNum(j,:); else m_daily_wts(i,:)=monthly_StockNum(j,:); end m_daily_PortValue(i,1)=dot(m_daily_wts(i,:),m_hist_close(i,:)); end; showSeries=[m_hist_close(:,2),m_hist_close(:,10)]; %showSeries=hist_close; resultTS=timeSeries(showSeries,hist_date(1:3495)); resultTS.TimeInfo.Units='months'; resultTS.TimeInfo.Format='mm,yyyy'; plot(resultTS); energyIndex=zeros(3495,1); for i =1:3495 energyIndex(i)=mean(m_hist_close(i,1:8)); end; energyIndexU=energyIndex(275:3479); energyIndexU=(energyIndexU./energyIndexU(1))*100000; DRFRate = 0.04^(1/252); CSeries=energyIndexU; n=length(CSeries); rCSeries= CSeries(2:n)./CSeries(1:n-1); x=sharpe(rCSeries,DRFRate); var(rCSeries); spindex=(sp500(:,2)/sp500(1,2))*100000; showSeries=[spindex(1:3205),m_daily_PortValue(275:3479,1),energyIndexU]; %showSeries=hist_close; resultTS=timeSeries(showSeries,hist_date(1:3205)); resultTS.TimeInfo.Units='months'; resultTS.TimeInfo.Format='mm,yyyy'; plot(resultTS); title('BenchMark comparison: Daily Settlement'); xlabel('Time '); ylabel('Portfolio Value: Our Portfio VS Energy VS S&P'); [hist_date, hist_high, hist_low, hist_open, hist_close, hist_vol] = get_hist_stock_data('cvx'); [hist_date, hist_high, hist_low, hist_open, hist_close, hist_vol] = get_hist_stock_data('su'); % year hist_date(1:248); %Crisis 01/01/2008 1759 - 10/29/09 2220 %last day '2012-11-20' 2990 %Plot price series and return figure(2); subplot(2,1,1); timeSeries1 = timeseries(hist_close,hist_date); plot(timeSeries1); %datetick('x'); xlabel('Date'); ylabel('Stock Price'); title('Stock price plot'); %legend(series,'Location','NorthWest'); %Return series hist_return = price2ret(hist_close); subplot(2,1,2); timeSeries1 = timeseries(hist_return, hist_date(2:end)); plot(timeSeries1); xlabel('Date'); ylabel('Stock return'); title('Stock return plot'); figure hist_returnC=hist_return(1:2995); %hist_returnC=hist_return; % return : Plot the sample ACF and PACF figure(2); subplot(2,1,1); autocorr(hist_returnC,20); subplot(2,1,2); parcorr(hist_returnC,20); %setup armax model arma(2,2), garch(1,1) spec = garchset('R',2,'M',2,'P',1,'Q',1); spec = garchset('R',2,'M',2,'P',0,'Q',0); garchfit(spec,hist_return); garchfit(spec,hist_return(1:2220)); [b,bint,r] = regress(hist_closeP,oilPrice) hist_closeP=hist_close(1:2990) logOilPrice= log(oilPrice) [lb,lbint,lr] = regress(hist_closeP,logOilPrice) %cvx %regress return with oil price %natural oil price oilPrice=data; hist_returnP=hist_return(1:2990); [b,bint,r] = regress(hist_returnP,oilPrice); %regress Oil stock price with oil price hist_closeP=hist_close(1:2990); [b,bint,r] = regress(hist_closeP,oilPrice); %regress oil stock return with oil log price lgOilPrice = log(oilPrice); [B,BINT,R,RINT,STATS] = regress(hist_returnP,lgOilPrice); %Arma fit cvx whole period hist_returnC = hist_return(1820:2000); %1759,2220 spec = garchset('R',2,'M',3,'P',0,'Q',4); [coeff,error] = garchfit(spec,hist_returnC); garchdisp(coeff,error) [res,sig,LogL] = garchinfer(coeff,hist_returnC); %conditional standard deviations ,standarized residuals, Loglikelihood objective function value figure(1); subplot(2,1,1); plot(sig); xlim([0,length(hist_returnC)]); title('Conditional Standard Deviation'); subplot(2,1,2); plot(res); xlim([0,length(hist_returnC)]); title('residul'); figure(1); subplot(2,1,1); plot(hist_returnC); xlim([0,length(hist_returnC)]); title('Conditional Standard Deviation'); subplot(2,1,2); plot(res); xlim([0,length(hist_returnC)]); title('residul'); returnOilPrice = price2ret(oilPrice); %Su for whole period hist_returnC = hist_return(2:2989); %returnOilPrice = returnOilPrice(1:2988); %hist_returnC = hist_return(250:377); spec = garchset('R',2,'M',2,'P',1,'Q',1); %%%%%%%% isArmax = 0; lgOilPrice = price2ret(oilPrice); if isArmax== 0 [coeff,error] = garchfit(spec,hist_returnC); else [coeff,error] = garchfit(spec,hist_returnC,returnOilPrice(2:2989)); end; %[coeff,error] = garchfit(spec,hist_returnC); garchdisp(coeff,error); if isArmax== 0 [res,sig,LogL] = garchinfer(coeff,hist_returnC); else [res,sig,LogL] = garchinfer(coeff,hist_returnC,returnOilPrice(2:2989)); end; figure(1); subplot(2,1,1); plot(sig); xlim([0,length(hist_returnC)]); title('Conditional Standard Deviation'); subplot(2,1,2); plot(res); xlim([0,length(hist_returnC)]); title('residul'); %forecast if isArmax== 0 [SigmaForecast,MeanForecast] = garchpred(coeff,hist_returnC,10); else [SigmaForecast,MeanForecast] = garchpred(coeff,hist_returnC,10); end; R Script: data=read.csv("/Users/daoxinwang/Desktop/aa.csv",header=T) weight=c(0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1) data1=data[,-1] for(i in 1:2010){ data1[i,]=(data1[i+1,]-data1[i,])/data1[i,] } data2=data1[-2011,] x=c(seq(1,2010,1)) for(i in 1:2010){ x[i]=sum(data2[i,]*weight) } hist(x,breaks=seq(-0.055,0.05,0.001),xlab="return rate") var=quantile(x,probs = seq(0, 1, 0.05))[2] abline(v=var,lwd=3,col="#0000ff99") x1=x[x<=var] cvar=mean(x1)


Please enter your comment!
Please enter your name here