In Mathematica 8.04 I've created a histogram of returns on a stock using:
returns = FinancialData["SP500", "Return", {Date[] - {5, 0, 0, 0, 0, 0}, Date[]}, "Value"];
μ = Mean[returns];
h = Histogram[returns, 300, "PDF"];
where "returns" is a list of the daily returns, and I want 300 bins in the probability density method. Next, I would like to draw a line that represents the mean of the returns so I use:
meanLine = Graphics[{Thick, Darker[Green], Line[{{μ, 0}, {μ, maxFreq + 2}}]}];
The problem is that I need to calculate the highest y-value for the line, which should be equal to the count of the data points in the bin with the most points (I've called this maxFreq
above). I am currently setting this value manually because I don't know how to extract it from the histogram (h). Note that the x-coordinate of this line (μ
) is simply the mean of the returns.
I've tried looking at FullForm[h]
to see if I could figure out how to extract the data. Buried within that output is the following:
List[List[Rectangle[List[-0.0015, 0.], List[-0.001, 54.0111]
which shows that I want to set maxFreq = 54.0111. So, I suppose that I want to use the Max
function, but I don't know how to access the heights of each bin. I think that I need to use some variation of the Part
function, but I can't figure out how. Any clues would be appreciated.
Here is the code that will generate what I'm looking for, but maxFreq is manually entered:
returns = FinancialData["SP500", "Return", {Date[] - {5, 0, 0, 0, 0, 0}, Date[]}, "Value"];
μ = Mean[returns];
h = Histogram[returns, 300, "PDF"];
maxFreq = 54;
meanLine = Graphics[{Thick, Darker[Green],Line[{{μ, 0}, {μ, maxFreq + 2}}]}];
Show[h, meanLine]
Answer
As mentioned by others, use HistogramList
. You can even use the resulting information to generate the plot without recomputing the information:
{bins, heights} = HistogramList[returns, 300, "PDF"];
maxFreq = Max[heights];
Histogram[returns, {bins}, heights &,
Epilog -> {{Thick, Darker[Green],
Line[{{μ, 0}, {μ, maxFreq + 2}}]}}]
Comments
Post a Comment