We don't know exactly why Shakespeare wrote Macbeth. While we have much documentary evidence that Shakespeare was Shakespeare, all of it is business related, such as contracts and wills: we have nary a shred of paper in which Shakespeare recorded a personal opinion or thought. We can only rely on his poetry and plays and larger historical currents to guide our thinking. Therefore, the best we can do is to make an educated guess.
Macbeth was written about 1606, shortly after James I took the throne in England and became patron of Shakespeare's theater company. We can surmise Shakespeare had two purposes in writing this play: to flatter James and to caution him.
The play flatters James, also king of Scotland, by being set in Scotland and showing his ancestor, Banquo, in a positive light. An allusion in the play to King Edward the Confessor curing scrofula was also a nod to James I, who revived the idea that the royal touch could cure illnesses.
Furthermore, Shakespeare showed he knew James's story well: James believed in witchcraft and thought that witches had raised a storm that threatened him and his wife as they set sail to Denmark. Shakespeare's acknowledgment of witches and their power would have played flattering tribute to James's worldview.
More importantly than these flattering little touches, however, is the overall theme of the play. English citizens, with good reason, feared James would veer into tyranny. He took an aggressive stance on the rights and power of the monarchy in a way that unnerved many. Shakespeare's play shows the ill effects of a tyrant on a country and on the tyrant himself, and thus Macbeth acts as cautionary tale or "advice to princes"—advising James to take it easy and steer a moderate course.