Shakespeare's England was Protestant under the rule of Elizabeth I, daughter of Henry VIII. Henry, in order to gain a divorce from his first wife, Catherine of Aragon, to marry again because he wanted an heir. Because Rome would not grant him his divorce, he broke with the Roman Catholic Church and created his own church, granting himself a divorce. This new church is the Church of England, which has some similarities to the Catholic Church; the most noticeable difference is the lack of a pope. However, in terms of beliefs...
Henry maintained a strong preference for traditional Catholic practices...
And...Christian Anglicanism is a tradition...
...with historical connections to the Church of England.
To the point, the Anglican Church believed in purgatory. Purgatory...
...has come to refer...to a wide range of...conceptions of postmortem suffering short of everlasting damnation...
Those who believe in purgatory feel that if they die without having cleansed their souls by confession of their sins will go to a place where a soul suffers, but not to hell itself. Some believe that time spent in purgatory will afford a soul the chance to redeem him- or herself.
In Shakespeare's Hamlet, the Ghost resides in purgatory when he is not roaming about, as he is in Act One, scene five, and later in the play, as well. The Ghost (who is the spirit of Old Hamlet, Hamlet's father) tells Hamlet:
My hour is almost come,
When I to sulphurous and tormenting flames
Must render up myself. (lines 4-6)
The Ghost goes on to describe his time in purgatory—that will "burn" away the sins that were on his soul when he died because he was unable to confess his sins before he was murdered. (This is, of course, a surprise to Hamlet; everyone believes that Old Hamlet died of a snake bite, being bitten while napping in the orchard.)
I am thy father's spirit,
Doom'd for a certain term to walk the night,
And for the day confined to fast in fires,
Till the foul crimes done in my days of nature
Are burnt and purged away. (13-17)
The Ghost explains his biggest regret, that which puts him in his present situation, is his murder out of a state of grace (with sins on his soul).
…Thus was I, sleeping, by a brother's hand
Of life, of crown, of queen, at once dispatch'd;
Cut off even in the blossoms of my sin,
Unhouseled, disappointed, unaneled,
No reckoning made, but sent to my account
With all my imperfections on my head. (79-84)
Elizabethans would have believed that the Ghost would come to Hamlet to ask him to avenge his death, as the Ghost would not be able to do so himself. This is why the Ghost roams the ramparts of the castle. He also appears to protect Gertrude from Hamlet when son confronts mother about her marriage to his father's murderer later in the play.