0

I'm getting my feet wet with R, and after much trial and error with my current task, I'm still stuck. I have price data for a stock ticker. I'm trying to find bear markets within my data, defined as a pricing data point <= 20% below an earlier point (but not too much earlier). Is this a time- series task? I hope this isn't too vague; I'm still learning the capabilities, so it's the best, most concise way I know to ask.

Thanks in advance..

StatsViaCsh
  • 2,600
  • 10
  • 44
  • 63
  • add data to your question – eddi Jul 11 '13 at 18:06
  • Have a look at [this posting](http://stackoverflow.com/questions/14737899/calculate-cumulatve-growth-drawdown-from-local-min-max). With the information you can find there and a little googling you should be able to solve the task. To complement Doctor Dan's answer the 'tseries' package also has a maxdrawdown function. – hvollmeier Jul 11 '13 at 18:36

2 Answers2

3

Here is a version that detects days having a price that is smaller than previous prices by some proportion (e.g., 20%) for some lookback period (e.g., 60 days).

## Some prices
set.seed(321)
prices    <- cumprod(1 + rnorm(300, 0.005, 0.05))

## Detection of "bear" periods
threshold <- 0.2
lookback  <- 60  # Set to length(prices) for no lookback restriction
is.bear   <- sapply(1:length(prices),
                    function(i, prices, threshold = 0.2, lookback = length(prices)){
                        (prices[i] / max(tail(prices[1:i], lookback))) < (1 - threshold)
                    },
                    prices = prices, threshold = threshold, lookback = lookback)
## Result
plot(prices, type = "l")
rug(which(is.bear), col = "red", lwd = 2)

enter image description here

QuantIbex
  • 2,324
  • 1
  • 15
  • 18
1

Take a look at PerformanceAnalytics, specifically, DrawdownPeak, it may be what you're looking for

Doctor Dan
  • 771
  • 4
  • 11