As others pointed out, older fairy tales didn’t always have happy endings, but I would agree that modern stories aimed at kids and even young adults do tend to have a happy ending.
One reason: it sells. The classic plot diagram shows resolution at the end, and when it’s a happy resolution after a whole story about struggle and conflict, it makes the audience feel good. I read the Divergent series awhile ago, and while I don’t want to post spoilers, the ending is bittersweet, and I hated it! I felt so shafted! Even though I can recognize that it was an artistic decision made for specific reasons blah blah, I just wanted everything to turn out happy in the end! Creators want to create works that will sell, and making their audiences feel crappy doesn’t help them do that.
It also probably relates to our psychological desire to protect children’s innocence and let them believe that the world is a good and fair place for as long as possible. It’s really scary to learn that bad things can happen to you even if you’re a good person, and lots of parents don’t want their kids having to think about that until it’s absolutely necessary.