Sorting return by dates
Mostra commenti meno recenti
I would like to sort the average return of each year. I have a data base of stock returns from 1992-2021. I would like to know the average stock return of each year.
How should I code this? Should i set a date range? I know there is a sort function to place the years in ascending orders. However, it is unable to help me to calculate the return of a specific year.
Also, the dates are in matlab form, like ,727594, which requires datevec function to look at the dates. Does it affect the coding part?
or this task can be think as adding up the return and find the average return of stocks in the same year.
I have totally no idea how to do this, please help me with this. Thank you very much
Risposte (2)
Walter Roberson
il 29 Lug 2022
[Y, ~] = datevec(TheDateNumbers) ;
G = findgroups(Y) ;
results = grpstats(YourData, G, "mean");
If you want the return per stock then stock identification should be also be passed to findgroups.
1 Commento
King To Leung
il 29 Lug 2022
Dyuman Joshi
il 29 Lug 2022
Modificato: Dyuman Joshi
il 29 Lug 2022
%to get the year of a date
[year,~,~] = datevec(727594)
%storing the years in y (months and dates are not necessary)
%dates are stored in the 2nd column
[y,~,~] = datevec(data_crsp(:,2));
%calculating mean stock return for each year, return is in the 7th column
for k=1992:2021
stockreturn(k-1991) = mean(data_crsp(y==k,7));
%1st element will correspond to 1992, 2nd - 1993 and so on
end
12 Commenti
King To Leung
il 29 Lug 2022
Dyuman Joshi
il 29 Lug 2022
Modificato: Dyuman Joshi
il 29 Lug 2022
"Should I put my data column to replace the word stock?"
Yes
So, names like dates and stock are used to denote your input. Since we don't know what the variable name is, we make an assumption that can be easily related/understood.
King To Leung
il 29 Lug 2022
Dyuman Joshi
il 29 Lug 2022
Modificato: Dyuman Joshi
il 29 Lug 2022
Alright, I have adjusted my code according to your input. Let me know if it works or not.
King To Leung
il 29 Lug 2022
Walter Roberson
il 30 Lug 2022
What shows up for
unique(y)
mask = y >= 1992 & y <= 2021;
nnz(mask)
nnz(isnan(data_crsp(mask,7)))
King To Leung
il 30 Lug 2022
King To Leung
il 30 Lug 2022
Dyuman Joshi
il 30 Lug 2022
Can you post your data here? That way we can directly look at it and work accordingly.
King To Leung
il 30 Lug 2022
Dyuman Joshi
il 30 Lug 2022
Use the attach symbol in the dashboard menu.
King To Leung
il 30 Lug 2022
Categorie
Scopri di più su Language Fundamentals in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!