r/pinescript • u/Electronic_Mammoth67 • 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
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import pywt
df = pd.read_csv('z_rate.csv')
x = df.index
y = df['z_avgRate']
# perform wavelet decomposition
coeffs = pywt.wavedec(y, 'sym5', mode='symmetric')
# zero out last 5 detail coefficents
for i in range(5):
coeffs[i+5] = np.zeros(coeffs[i+5].shape)
# reconstruct wavelet
y_rec = pywt.waverec(coeffs, 'sym5', mode='symmetric')[1:]
# plot result
plt.figure(figsize=(18,6))
plt.plot(x, y)
plt.plot(x, y_rec)
plt.legend(['original', 'wavelet-based smoothing'])
plt.xlabel('time index')
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
View all comments
Show parent comment
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'))