I believe you have the correct approach.
I would do something like this:
f = 1/20;
t=0:0.2:50;
noise = randn(size(t));
y = sin (2*pi*f*t) + noise;
Y = zeros(size(y)); % the signal after smooth
len = 4; % smooth every 4 samples
for n=1:length(y)-len
if (n>len)
Y(n) = trapz(y(n:n+len))/len;
end
end
figure
plot(t, y)
hold on
plot(t, Y, 'LineWidth',1.5)
hold off
grid
Note that I use randn here instead of rand. The randn function produces Gaussian-distributed (normally-distributed) random numbers with a mean of 0 and a standard deviation of 1. The rand function produces uniformly-distributed random numbers going from 0 to 1, with a mean of 0.5. This may be the source of the amplitude deviation you were seeing, since the mean would integrate, creating a positive slope instead of the 0 slope created by using randn (that approximates real white noise).
.