I struggle with both situations, but mainly getting back to the stage from the ledge. For example in the Marth vs Marth matchup I always struggle with getting back onto the stage from ledge. I can't seem to escape being down tilted or forward smashed while trying to recover.
Some basic tools you should be able to apply:
1. Learn to DJ regrab on the ledge without poking your head above. Marth has a really good ledge grab range, so once you get to the ledge, you need to be comfortable managing your invincibility. You're by no means 100% safe when DJ regrabbing, but most people won't try to approach you on the ledge just on principle.
2. Invul ledgedash; practice it until you can consistently get on with enough invulnerability to shield. Bonus points if you learn to reverse ledgedash back onto the ledge to bait them into whiffing an attack by the ledge.
3. Learn to techjump-bair when you up-B to the ledge and get hit by an attack.
4. Learn when you can sweetspot around dtilt/fsmash by being as far from the ledge as possible, both horizontally and vertically (easy to practice on your own).
5. Study and practice side-B stalling. The top Marths know how to save their jump and first side-B so when they recover low, they can use these to wait for the opponent to get off the ledge. 99% of Marth recoveries consist of threatening the opponent with a possible up-B so that they roll early and you simply DJ/side-B and up-B as their ledgeroll ends.
6. Learn to Survival DI well. The best way to recover is to not have to use your up-B in the first place. The better you DI, the less often you will have to up-B, and the more often you will easily make it back because all you have to do is DJ to grab the ledge.