The Rays' trip to Cuba was the first by a major league team since 1999 when the Baltimore Orioles visited.
Obama and Castro sat side by side behind the plate to watch the game in Estadio Latinoamericano. Former major league stars Derek Jeter, Dave Winfield and Luis Tiant and commissioner Rob Manfred also attended along with U.S. Secretary of State John Kerry and Obama's wife, Michelle, and daughters Sasha and Malia.
The near-capacity crowd cheered loudly when both men entered the stadium. Obama and Castro left by the third inning.
Loney singled in Kevin Kiermaier with the first run in the second inning and homered in the top of the fourth to give the Rays a 3-0 lead.
Rays starter Matt Moore pitched six innings and gave up no runs, six hits and one walk while striking out three.
Cuba ended the Rays' shutout bid in the ninth when Rudy Reyes homered off Alex Colome.
Tampa right fielder Dayron Varona returned to Cuba for the first time since leaving through Haiti in 2013. He went 0 for 2.