Why is my iMac shutting down randomly?
Have you checked your device temperature? I had a similar problem with an old MacBook Pro and it was randomly shutting down because it was overheating.

You can check temperature with SMC Fan control or iStat Menus.

Check on System Monitor the power usage, that's always helpful to check what process can be making your device overheating.

In my case was chrome plus some developer tools that i use at work.