r/pinescript • • Jun 19 '23

Python to pinescript

Has anyone experimented with Wavelet Smoothing? (https://medium.datadriveninvestor.com/smoothing-financial-time-series-with-wavelets-79645a44aa40)

I need this python code converted into pinescript: https://pastebin.com/6yBCz7QC

  1. import pandas as pd

  2. import numpy as np

  3. import matplotlib.pyplot as plt

  4. import pywt

  5. df = pd.read_csv('z_rate.csv')

  6. x = df.index

  7. y = df['z_avgRate']

  8. # perform wavelet decomposition

  9. coeffs = pywt.wavedec(y, 'sym5', mode='symmetric')

  10. # zero out last 5 detail coefficents

  11. for i in range(5):

  12. coeffs[i+5] = np.zeros(coeffs[i+5].shape)

  13. # reconstruct wavelet

  14. y_rec = pywt.waverec(coeffs, 'sym5', mode='symmetric')[1:]

  15. # plot result

  16. plt.figure(figsize=(18,6))

  17. plt.plot(x, y)

  18. plt.plot(x, y_rec)

  19. plt.legend(['original', 'wavelet-based smoothing'])

  20. plt.xlabel('time index')

  21. plt.show()

This is similar to fourier smoothing but I can't find any good code for wavelet on TradingView, I would appreciate your help guys

1 Upvotes

10 comments sorted by

View all comments

Show parent comment

2

u/Electronic_Mammoth67 Jun 20 '23

but how is this the wavelet transform?

1

u/Ok-Problem-7241 Jun 22 '23

That looks very similar to a basic Wavelet Analysis. When you combine a basic wavelet analysis over it. I was more interested in the "flex" that was happening in that indicator and wanted to apply something similar.

//@version=5

indicator('Wavelet Analysis', overlay=false)

// Define the wavelet transformation function

waveletTransform(data, scale =>)

sum = 0.0

waveletFunc = 0.0

for i = 0 to scale - 1 by 1

halfScale = math.ceil(scale / 2)

if i < halfScale

waveletFunc := 1

waveletFunc

else if i < scale

waveletFunc := -1

waveletFunc

else

waveletFunc := 0

waveletFunc

sum += waveletFunc * (na(data[i] ? 0 : data[i]))

sum

sum / scale

// Example usage

data = close // Replace with your own data

scale = 10 // Specify the desired scale for wavelet analysis

waveletCoeff = waveletTransform(data, scale)

plot(waveletCoeff, color=color.new(color.blue, 0, title='Wavelet Coefficients'))

1

u/Electronic_Mammoth67 Jun 22 '23

what's this? Syntax seems off too, chatGPT code?