Though it is impossible to say exactly why William Shakespeare wrote "Macbeth," the political and historical context of the play gives scholars major clues. "Macbeth" serves as a cautionary tale for those who would threaten the king and acts as a reassertion of the divine right of monarchs.
Shakespeare wrote "Macbeth" in 1606, one year after the Gunpowder Plot of 1605 and three years after James I ascended to the English throne. James I was Scottish, and "Macbeth" may have been designed to flatter him and appeal to his interests in a number of ways. The Gunpowder Plot, which involved conspirators who questioned the legitimacy of James' claim to the crown, ended in the torture and execution of those involved. "Macbeth" is meant to warn those who would try to assassinate a king of their inevitable fate.
"Macbeth" reflects the philosophy born in the Middle Ages that monarchs were appointed at birth by God, and that aspiring to become royalty through other means is a sin. This philosophy was still prevalent in Shakespeare's time and would have greatly appealed to James I. The fact that Macbeth's fatal flaw is ambition means that he murders a king in order to gain power, leading to his own downfall.
Shakespeare also appealed to the king's extensive interest in the supernatural. James I was directly involved in the witch trials in Scotland, and he would have been interested in the play's depiction of the three witches as devilish harbingers of doom.