Riot measures what they call "core metrics" so that, in their words, "so that if you're doing the right thing for your team, we're going to score you well for it."
http://boards.na.leagueoflegends.com/en/c/gameplay-balance/bZL8vAWw-champion-mastery-qa?comment=00540000
You get compared to other people in your region who played the same champion as you in the same role as you, the higher your score amongst these people the better your grade will be.
https://support.riotgames.com/hc/en-us/articles/204211284-Champion-Mastery-Guide
Also, there are a lot of people giving false advice, a lot of people believe that kda and cs is somehow a direct factor in your grade. These people are most likely wrong as it has been observed that a player can have a pretty terrible kda and cs and lose the game yet still achieve a S level grade.
http://boards.na.leagueoflegends.com/en/c/gameplay-balance/cTJF3oUc-s-on-feeding-trundle
Riot has also noted that even the best of players cannot consistently get the highest grades (though they do get them more often), which leads me to believe there is at least some degree of luck involved.
The true workings of the system are unlikely to ever be revealed to us, so the best you can do is just doing your best and not worry about it. Good luck.