That seems tricky. Last train leaves at 8pm and last bus at 7pm.
Other options to consider:
Private car or Uber. Will cost you around 120 Euro. Uber may charge a significant "prime time" surcharge for New Years Eve, so you would be better of booking a private car up front.
Rental car for a one way seems too expensive, but may be an option of you are planning to return to Madrid anyway (as little as 30 Euro). Certainly not a good idea if you are planning to party in Madrid before departure.