Function to fit a square wave to time series data