You should apply before your student visa or Tier 4 (General) student visa expires. You can apply once your educational institution has informed the Home Office that you've completed your course under your student or Tier 4 (General) student visa. You need not wait until your graduation or the issuance of a certificate to apply.