How do I derive weights given a weighted average? - algebra

Ok I feel like this has to have a simple solution but I can't for the life of me figure it out. I have a given weighted average, let's say total returns of a portfolio. And I want to break that out into returns from equity and returns from bonds. I know the returns of each and my total return, but I don't know how to calculate what weights I had in each.
I know I can use goal seek in Excel to get the answer, but there has to be some calculation I can use.
Ex: Total Return (weighted average of stocks and bonds) = 3.48%, Stock Returns = 5.21%, Bond Returns = 0.59%

If i understand well your question, you want to know how to calculate that the weight of the stock portfolio is 1.67 the weight of the Bond Portfolio.
1.0059 bond + 1.0521 stock = 1.0348 ( bond + stock ) and stock = w * bond
after replacing stock by w*bond on the first equation, and isolating w , you can find that the initial portfolio contains 1.67 stocks for 1 bond. Hope it helps.

Related

Shifting line index based on a specific criteria Matlab

I have a table similar to the one above. For each species, I have the growth rate of year1 to 100. Suppose the table is called Data_Table.
I have to shift the index of growth rate column for each species based on a criteria.
For instance,
if criteria
First_Index = Incubation - x;
else
First_Index = Incubation - x + 1;
end
First index can take value 1 or 2.
If it is equal to 1, the growth rate for the species should not change.
If it is equal to 2, the second growth rate becomes the first growth
rate, the 3rd growth rate becomes the 2nd and so on ..
Data_Table(1,'Growth_Rate') = Data_Table(First_Index, 'Growth_Rate');
Any idea on how I can do that simply on Matlab without touching the other columns ? Circshift as written below is completely messing up the data in data_table.
Data_Table(:,'Growth_Rate') = circshift(Data_Table(:, 'Growth_Rate'),First_Index);
Thanks in advance

Calculating the product of all the odd numbers

So I am trying to create a script that calculates the product of all the odd numbers from 1 to 1000 (using MATLAB). The program runs but the product is not correct:
%Program is meant to calculate the product of all the odd numbers from 1 to 1000
% declare variable ‘product’ as zero
product = 0.;
% initialize counter, ‘n’, to 1000
n = 1000;
for i = 1:2:n
product = product + i;
end
fprintf('The product of all the odd numbers from 1 to %d is %d\n', n, product)
So I'm not really sure how to go about this and am looking for some guidance. Thanks!
Solution
Currently, your script is set to add all of the odd numbers from 1 to 1000.
To perform the product, you just need to change the starting value of product to 1 and multiply within the loop:
product = 1;
for i = 1:2:1000
product = product * i;
end
However, it is faster to create a vector and have the built-in prod function perform the multiplication:
product = prod(1:2:1000);
Problem
MATLAB does not by default have enough memory in the default 64-bit numbers to compute the exact value of this product.
The number is too large since this is essentially a factorial.
You'll find that MATLAB returns Inf for the 500 numbers you're multiplying, and it is only finite for up to 150 elements.
In fact, using floating point arithmetic, the number is only accurate up to 15 digits for the first 17 digits using floats (integers saturate at that level as well).
Using Mathematica (which can perform arbitrary digit arithmetic out-of-the-box since I'm feeling lazy), I can see that the answer needs at least 1300 digits of precision, which we can have MATLAB do through the Symbolic Toolbox's vpa function:
digits(1300);
p = vpa(1);
pint = vpa(1);
for k = 2:N
pint = pint*p(k);
end
disp(pint);
>> StackOverflow
100748329763750854004038917392303538250323418583550415705013777513334847930864905026212149922688916514224446856302103818809813965739969905602683824057028542369814437703275217182106137628427025253936696857063927677887236450311036887007989218384076420973974651860279864376153012567675767840733574225799002463604490891982796305162134708837541147007332276627034016790073315219533088052639255340728943149219519187498959529434982654113006616219355830114439411562650611374970334868978510289340267833632215930432706056111069583472778227977585526504938921664232801595705593340414168289146933191250605578218896799783237156997993612173843567447982392426109444012350386990916069363415575527636429080027392875413821124412782341957015410685185402984322002697631153866494712956244870206835064084512590679022924697003630949759950902438767963278695296882620493296103779237046934780464541286585179975172680371269700518965123152181467825566303777704391998857792627009043170482928030252033752456172692668989206857862233381387134495504231267039972111966329704875185659372569246229419619030694680808504265784672316785572965414328005856656944666840982779185954031239345256896720409853053597049715408663604581472840976596002762935980048845023622727663267632821809277089697420848324327380396425724029541015625.0

matlab - calculate the 95 % interval around the mean

If I have a vector of monthly-averaged values like
aa = [1,2,3,2,1,3,5,3,4,8,9,7;...
11,12,3,21,1,3,15,3,4,8,19,7;...
21,2,3,2,1,23,5,3,34,84,9,7]';
where each column refers to the monthly-averaged values from different locations and each row represents the month of year. I can calculate the average of all of the sites as:
mean_a = nanmean(aa,2);
and thus can plot the averages of these as:
plot(1:12, mean_a);
How would I now calculate the 95 % confidence interval around these mean values?
Any advice would be appreciated.
My attempt:
Assuming a normal distribution:
aa = [1,2,3,2,1,3,5,3,4,8,9,7;...
11,12,3,21,1,3,15,3,4,8,19,7;...
21,2,3,2,1,23,5,3,34,84,9,7]';
mean_a = nanmean(aa,2);
sem = (nanstd(aa')./sqrt(size(aa,2))).*1.96;
errorbar(1:12,mean_a,sem);
Calculate the quantile using quantile: or if you know the distribution, multiply the standard deviation with the correct quantile value.
I know this is an old question but for the record, here is a function called confidence_intervals() that will give any confidence intervals for a dataset and can be used with the errorbar() function in Matlab. It can also be used, given the optional argument, to find the confidence intervals with the log-normal variance.
As in your example, the code becomes:
aa = [1,2,3,2,1,3,5,3,4,8,9,7;...
11,12,3,21,1,3,15,3,4,8,19,7;...
21,2,3,2,1,23,5,3,34,84,9,7]';
errorbar( 1:12, mean(aa), confidence_intervals( aa, 95 ) )

What to use instead of reshape when the number of observations within one day are not the same?

I am just starting to learn Matlab and I would appreciate very much if you could help me...
I am stuck with calculating the returns between some hours and for each day..
For some data was going ok the following method:
(now the price is between that hours)
n=length(price);
% The number if days
%(79 is the number of observations within one day)
ndays = n/79;
price_d = reshape(price,79,ndays);
%I take returns for each day
returns_d = log(price_d(2:79,:))- log(price_d(1:78,:));
However now I have another data where the number of observations are not anymore the same for each day..So in one day I have 79 in another 30,75 observations within a day. Therefore I CANNOT use anymore RESHAPE..:(
How should I do in order to have sorted the observations(prices) according to each day? So to have similar thing as before: row with the prices and column with prices corresponding to each day..
So I have a nx1(n=935039) vector of the data like this: 734142 734142 734142 734142 734142 734143 734143 734143 734143 734143 734143 734143 734143 734143..
Then a vector with prices:1115.80000000000 1115.40000000000 1116 1116 1115.80000000000 1115.70000000000 1115.70000000000 1115.40000000000 1115.60000000000 1115.60000000000 1115.70000000000 1115.60000000000 1115.80000000000 1115.80000000000 1115.70000000000 correpondig to each date...
And a vector with time in seconds:0 300 600 900 1200 1500 1800 2100 2400 2700 3000 3300 3600 3900 ...
There is no way to split them either in one matrix with I don't know how many rows(which are gonna be the prices for each day) but I know the number of columns 1260(which are the days I have).. Or if not just to make 1260 vectors(nx1) with the prices for each day.
In Ox will be something like this(my coordinator 4 phd told me,but he doesn't use matlab):for(i = 1; i <= sizeof(vdates); i = i+1) daily_file = selectifr([bid,ask], dates .== vdates[i]); if empty continue save daily_file contract_name + "_" + sprint(vdates[i]) + ".mat"; HOwever I cannot find the opossite function of ''selectifr'' from Ox to Matlab..
I have the future index on S&P for my 5minutes intraday data. So I prefer to have either in one matrix the days(1260)columns with prices(rows)(like I have them when using reshape)..Or to have 1260 nx1 vector with prices correspondig to each day.. After I will have to look where the volume is changing so I am passing to another contract(Rolloverdates)..Can you help me to split them in days,or individual vectors with prices for each day?
..I don't have a nx1260 vector...I was just saying that my unique(dates)=1260
You could use a cell array that contains vectors of different lengths, one for each day. Calculating something for each day can then be done using cellfun or arrayfun.
>> measurements = {[1,2,3],[10,11],[14,15,16,17]};
>> avg_per_day = cellfun(#mean, measurements)
avg_per_day =
2.0000 10.5000 15.5000

How do I create ranking (descending) table in matlab based on inputs from two separate data tables? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have four data sets (please bear with me here):
1st Table: List of 10 tickers (stock symbols) in one column in txt format in matlab.
2nd table: dates in numerical format in one column (10 days in double format).
3rd table: I have 10*10 data set of random numbers (assume 0-1 for simplicity). (Earnings Per Share growth EPS for example)--so I want high EPS growth in my ranking for portfolio construction.
4th table: I have another 10*10 data set of random numbers (assume 0-1 for simplicity). (Price to earnings ratios for example daily).-so I want low P/E ratio in my ranking for portfolio construction.
NOW: I want to rank portfolio of stocks each day made up of 3 stocks (largest values) from table one for a particular day and bottom three stocks from table 2 (smallest values). The output must be list of tickers for each day (3 in this case) based on combined ranking of the two factors (table 3 & 4 as described).
Any ideas? In short I need to end up with a top bucket with three tickers...
It is not entirely clear from the post what you are trying to achieve. Here is a take based on guessing, with various options.
Your first two "tables" store symbols for stocks and days (irrelevant for ranking). Your third and fourth are scores arranged in a stock x day manner. Let's assume stocks vertical, days horizontal and stocks symbolized with a value in [1:10].
N = 10; % num of stocks
M = 10; % num of days
T3 = rand(N,M); % table 3 stocks x days
T4 = rand(N,M); % table 4 stocks x days
Sort the score tables in ascending and descending order (to get upper and lower scores per day, i.e. per column):
[Sl,L] = sort(T3, 'descend');
[Ss,S] = sort(T4, 'ascend');
Keep three largest and smallest:
largest = L(1:3,:); % bucket of 3 largest per day
smallest = S(1:3,:); % bucket of 3 smallest per day
IF you need the ones in both (0 is nan):
% Inter-section of both buckets
indexI = zeros(3,M);
for i=1:M
z = largest(ismember(largest(:,i),smallest(:,i)));
if ~isempty(z)
indexI(1:length(z),i) = z;
end
end
IF you need the ones in either one (0 is nan):
% Union of both buckets
indexU = zeros(6,M);
for i=1:M
z = unique([largest(:,i),smallest(:,i)]);
indexU(1:length(z),i) = z;
end
IF you need a ranking of scores/stocks from the set of largest_of_3 and smallest_of_4:
scoreAll = [Sl(1:3,:); Ss(1:3,:)];
indexAll = [largest;smallest];
[~,indexSort] = sort(scoreAll,'descend');
for i=1:M
indexBest(:,i) = indexAll(indexSort(1:3,i),i);
end
UPDATE
To get a weighted ranking of the final scores, define the weight vector (1 x scores) and use one of the two options below, before sorting scoreAllW instead of scoreAll:
w = [0.3 ;0.3; 0.3; 0.7; 0.7; 0.7];
scoreAllW = scoreAll.*repmat(w,1,10); % Option 1
scoreAllW = bsxfun(#times, scoreAll, w); % Option 2