Python Forum
Problem Converting Tradingview Indicator to Python code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Problem Converting Tradingview Indicator to Python code
#1
Hello, I have been trying to convert the CCI-EMA indicator prepared with pinescript on Tradingwiev to Python code for about a week and filtering through this code, but the graphic image on TW and the Python graphic image are different from each other. While it appears on CCI-EMA on TW, it is under the code I wrote. What am I doing wrong? When I want to solve this problem and filter the stocks that cut the ema value of the CCI indicator upwards, when I check the stocks listed with tw after the filtering, I see that there is either no intersection or they are far ahead of the intersection point. However, I want to filter the stocks that are at the exact intersection point, please help me, professional friends, in this regard. I would be very happy if they do, I present the code example below.
import numpy as np
import yfinance as yf
import pandas as pd

def calculate_wma(src, length):
    weights = np.arange(1, length + 1)
    wma = np.convolve(src, weights, mode='full') / weights.sum()
    return wma[:-(length-1)]

def calculate_dev(src, length):
    mean = np.mean(src[-length:])
    dev = np.sqrt(np.mean((src[-length:] - mean) ** 2))
    return dev

def calculate_ema(data, window):
    c = 2.0 / (window + 1)
    ema = np.zeros_like(data)
    ema[0] = data[0]
    for i in range(1, len(data)):
        ema[i] = (data[i] - ema[i-1]) * c + ema[i-1]
    return ema

def analyze_symbol(symbol, cci_length, ema_length):
    try:
        data = yf.download(symbol, start="2024-03-01", end="2024-04-25", interval="1h")
        if data.empty:
            raise ValueError(f"No price data found for symbol {symbol}")
        
        src = data['Close'].values

        ma1 = calculate_wma(src, cci_length)
        cci1 = (src - ma1) / (0.015 * calculate_dev(src, cci_length))
        ema_cci1 = calculate_ema(cci1, ema_length)

        crossings = np.where(np.diff(np.sign(cci1 - ema_cci1)))[0]

        if len(crossings) > 0 and cci1[crossings[-1]] > ema_cci1[crossings[-1]]:
            return symbol
    except Exception as e:
        raise ValueError(f"Failed analysis for {symbol} with error: {e}")

def filter_symbols(symbols_df, cci_length, ema_length):
    filtered_symbols = []
    total_symbols = len(symbols_df)
    for i, symbol in enumerate(symbols_df['Symbol'], 1):
        print(f"Analyzing symbol {i}/{total_symbols}: {symbol}")
        try:
            result = analyze_symbol(symbol, cci_length, ema_length)
            if result:
                filtered_symbols.append(result)
        except ValueError as e:
            print(e)  # Hata mesajını ekrana yazdır
    return filtered_symbols

def save_symbols_to_excel(filtered_symbols, output_file):
    filtered_symbols_df = pd.DataFrame(filtered_symbols, columns=['Symbol'])
    filtered_symbols_df.to_excel(output_file, index=False)

def main():
    print("Merhaba Ben Filtreleme Sorgusu Lütfen Excel Dosya Yolunu Aşağıya Girin")
    symbol_file = input("Enter the path to the Excel file containing stock symbols: ")
    symbols_df = pd.read_excel(symbol_file)
    
    cci_length = int(input("Enter the CCI Length: "))
    ema_length = int(input("Enter the EMA Length: "))
    
    print("Filtering symbols...")
    filtered_symbols = filter_symbols(symbols_df, cci_length, ema_length)
    
    output_file = 'CCİ-Hisseler.xlsx'
    save_symbols_to_excel(filtered_symbols, output_file)
    print(f"Filtered symbols saved to {output_file}")

if __name__ == "__main__":
    main()
I also present the TW code below.
study(title="CCIEMA", shorttitle="CCI+EMA by perrito Blacky")
length1 = input(20, minval=1, title="CCI")
ma_length = input(13, minval=1, title="EMA")
src = input(close, title="Source")
ma1 = wma(src, length1)
cci1 = (src - ma1) / (0.015 * dev(src, length1))
//plot(ema(cci1, ma_length), color=green, linewidth=2)
plot(ema(cci1, ma_length), linewidth=2)

plotColour = (cci1 > ema(cci1, ma_length)) ? green : red
plotCCIEMA = plot(series=cci1, color=plotColour, linewidth=2)
//plotHoriz  = plot(series=0, color=blue, style=circles)
//fill(plot1=plotCCIEMA, plot2=plotHoriz, color=blue, transp=90)

band0 = hline(200, color=red)
band1 = hline(100, color=blue)
band2 = hline(0,title="zero")
band3 = hline(-100, color=blue)
band4 = hline(-200, color=red)
fill(band1, band3, color=blue, transp=95)
deanhystad write Apr-25-2024, 08:35 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
I don't understand why no one offers any ideas about my problem. ))::
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  CandleStick & MACD Indicator using plotly.graph_object bianca 0 584 Aug-18-2023, 06:46 PM
Last Post: bianca
  Converting python to FileMaker DWolf 6 1,752 Sep-22-2022, 03:40 AM
Last Post: DWolf
  Problem with importing Python file in Visual Studio Code DXav 7 5,208 Jun-15-2022, 12:54 PM
Last Post: snippsat
  Progress Indicator for Xmodem 0.4.6 KenHorse 1 1,996 Jan-30-2021, 07:12 PM
Last Post: bowlofred
  how to deal with problem of converting string to int usthbstar 1 2,002 Jan-05-2021, 01:33 PM
Last Post: perfringo
  C to Python code conversion print problem anakk1n 1 2,209 May-22-2020, 04:15 PM
Last Post: deanhystad
  Converting SQL Code To Python Code Query eddywinch82 13 31,125 Feb-15-2020, 06:42 PM
Last Post: buran
  Converting python to c# benahmadi 1 2,672 Oct-22-2019, 09:50 PM
Last Post: micseydel
  converting array to and from string in python 3.7.2 srm 5 6,270 Jul-03-2019, 01:11 PM
Last Post: snippsat
  help with converting C# function to Python korenron 17 11,461 May-19-2019, 10:26 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020