How to reshape efficiently Panel Data
이전 댓글 표시
I have a database where I store historical prices of ~1000 stocks for a +10yr period in a panel data format (nx4) ([Ticker] [Date] [Price] [Return]). I import the data into Matlab and then try to construct two historical matrices (one for Price and another for Returns) in the format (columns->tickers, rows->dates, values -> Price/Return). In order to do that I use the following code:
historical_returns; %panel data cell array imported from the database
historical_dates; %array that includes all historical dates
tickers; %array that includes all the tickers
Matrix_Prices = zeros(length(historical_dates),length(tickers));
Matrix_Returns = zeros(length(historical_dates),length(tickers));
for i=1:size(historical_returns,1)
temp_ticker = historical_returns{i,1};
temp_date = historical_returns{i,2};
temp_price = historical_returns{i,3};
temp_return = historical_returns{i,4};
row = find(strcmpi(historical_dates,temp_date));
column = find(strcmpi(tickers,temp_ticker));
Matrix_Prices(row,column) = temp_price;
Matrix_Returns(row,column) = temp_return;
end
The code above takes ~200sec to run assuming historical_returns has a size of 1mmx4 (which increases as the # of tickers and dates increase). I am trying to optimize the code (if possible), so I am not sure if there is a faster way to construct Matrix_Returns. I have thought of storing the data in a different format, but given the limit of column size in Access and SQL databases, I cannot create a new column for each ticker.
채택된 답변
추가 답변 (1개)
Peter Perkins
2015년 1월 7일
This is a one-liner using the unstack function on a table. It would be something like
wideData = unstack(tallData,{'Price' 'Return'},'Ticker')
where tallData is a table with four variables, Ticker, Date, Price, and Return. Hope this helps.
카테고리
도움말 센터 및 File Exchange에서 Financial Toolbox에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!