Madrid is broadly cooperative once you avoid the weaker patches
May, October and September are the months where the destination looks most broadly convincing. If you want to skip the shakier chunk of the year, look first at August, January and July.
Compare nearby choices.
Stay in Spain, but see whether another destination fits your timing better.
Great places deserve great timing.