This paper assumes that the market returns follow a two-state Markov process that randomly switches between bull and bear states. We show that in this case the exponential moving average (EMA) represents the optimal trend-following rule. The paper provides the analytical solution to the optimal window size (decay constant) in the EMA rule. We estimate the optimal window size for timing the S&P 500 stock market index using real-world data. A comparative statics analysis finds that the optimal window size depends mainly on the signal-to-noise ratio of returns and the state transition probabilities.