Often people in the past could not always make sense of the random effects of life and especially nature or natural events. So, they had to come up with a reason why things happen, especially bad or negative things. This could include gods, demons, fairies and Jinns - powers that influence humans are circumstances. Religious thought sometimes added to this. However, because traditional people valued and trusted in older and wiser people in the family or tribe/group and when these elders died, people believed or wanted to believe that the spirit or influence of that elder was still with the family and even in the house. This may go back to burying the body of the dead under the floor or keeping it on the wall. You literally sleep on or next to the dead relative. So, if there was a strange noise or bump, then it could be the spirit of the dead relative. And maybe they are angry. This was well known in Asia and Africa and still is. In the West we have this very ancient tradition that has become All Saints Day or Halloween, when all the dead spirits returned home for a night, so if people have done something wrong then they dead spirit could punish these people. Often bad events at the same time could rationally or irrationally be attributed to these ghostly souls. The other reason for ghosts is from religious teaching that the dead can speak to people and like in the Bible we are warned not to talk to the dead, that is spirit-ism. The idea of the afterlife also could have created the ideas of ghosts and spirits - where did these souls go? What about angry souls that have not got right with God? What happens to our souls when we die? Notice how even the earliest human beings buried things for the next life with with the dead. I personally, know that the spiritual exists and that some experiences are in fact demonic spirits which still disobey God and want to hurt human beings who are created in the image of God. So, ghosts, if they do exist could be demonic spirits masquerading as the souls of the dead. That is why some psychics can hear from the grave. But the Bible warns us not to talk to the dead anyways.
I did a project on them a while back, I love researching stuff.