I can't remember the exact date right now, but a lot of people put the loss of South America's colonies to that of Ferdinand VII actions in renouncing the constitution.
As for Peru, it was quite possible that Spain might have held on had the Revolt of 1820 not happened. Spain was preparing a large second force to help the royalists, but due to a revolt by one of the commanders the army never made it to South America. Butterfly that commander away and there is a very good chance of the army making it to Peru. Rafael del Riego could have been killed off plenty of times actually, the Peninsular war and the general madness that was Spain post-peninsular war.
As for Peru, it was quite possible that Spain might have held on had the Revolt of 1820 not happened. Spain was preparing a large second force to help the royalists, but due to a revolt by one of the commanders the army never made it to South America. Butterfly that commander away and there is a very good chance of the army making it to Peru. Rafael del Riego could have been killed off plenty of times actually, the Peninsular war and the general madness that was Spain post-peninsular war.