The purpose of this paper is to propose a methodology that allies both theoretical and empirical aspects to model and solve the problem of finding the optimal market-based corporate financial structure in a risky environment; the firm's asset value follows a geometric Brownian motion with a return adjusted by the probability of default which is stochastic and follows an Ornstein-Uhlenbeck process. We consider a decision manager to optimize the financial structure of his company, maximizes the expected utility of the shareholders' final wealth by solving a dynamic programming problem. The value function obeys a quadratic Hamilton-Jacobi-Bellman (HJB) equation and the explicit solution gives the optimal debt ratio. The Kalman filter approach is used to estimate the model parameters. We empirically examined the implications of the credit ratings on the optimal capital structure decision. The data used are daily, obtained from the 'Data Stream' database and cover a sample of 16 U.S companies of various sectors and different rating categories over the period from January 01, 2015, to December 31, 2015. The estimated average optimal debt ratios are relatively high showing different patterns between and within investment and speculative-grade firms. In fact, the evolution of the optimal debt ratio according to the rating is influenced by a restrictive or an easy entry into the debt market and by the value of the estimated rate of return.