Hi and Welcome. My Name is ***** ***** I look forward to assisting you today with your question.
The phone usually turn off automatically if there is any issue with the internal board, battery or other components. Software issues usually don't cause this. Viruses or malware also won't cause this. To make sure this is not an issue with battery, can you install another battery and check ?
Also all unwanted applications like Avast, cleaning apps etc and then check as well ?
Let me know it goes please
To rule out software, I want you to test your S4 in Safe Mode for a few hours. Turn off the phone. Turn it back ON and then immediately hold down Volume down until it boot into lock screen. This will boot into safe mode and only important system files will run in this mode. This will tell us if any of your applications are causing this issue.
Keep running it in safe mode for a few hours and see if it turning off in safe mode. This is to check if there is any issue with software