Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

whats wrong with my code #!/usr/bin/env python import numpy as np import pandas as pd…

  1. User

    whats wrong with my code #!/usr/bin/env python import numpy as np import pandas as pd import yfinance as yf from sklearn.preprocessing import StandardScaler from sklearn.feature_selection import SelectKBest, f_classif

    Function to fetch historical stock data

    def fetch_stock_data(ticker, start_date, end_date): stock_data = yf.download(ticker, start=start_date, end=end_date) return stock_data

    Function to compute the Relative Strength Index (RSI)

    def compute_rsi(prices, window=14): deltas = np.diff(prices) seed = deltas[:window + 1] up = seed[seed >= 0].sum() / window down = -seed[seed < 0].sum() / window rs = up / down rsi = np.zeros_like(prices) rsi[:window] = 100.0 - (100.0 / (1.0 + rs))

    for i in range(window, len(prices)):
        delta = deltas[i - 1]  # Use the previous delta
        if delta > 0:
            upval = delta
            downval = 0.0
        else:
            upval = 0.0
            downval = -delta
    
        up = (up * (window - 1) + upval) / window
        down = (down * (window - 1) + downval) / window
        rs = up / down
        rsi[i] = 100.0 - (100.0 / (1.0 + rs))
    
    return rsi
    

    Function to fetch historical stock data

    def fetch_stock_data(ticker, start_date, end_date): try: stock_data = yf.download(ticker, start=start_date, end=end_date) return stock_data except Exception as e: print(f"Failed to download data for ticker {ticker}: {e}") return None

    ...

    def rank_stocks(start_date, end_date): # Fetch historical data for all available tickers all_tickers = yf.download('^GSPC', start=start_date, end=end_date) all_tickers = pd.DataFrame(all_tickers['Adj Close']) all_tickers = all_tickers.columns

    feature_scores = []
    
    for ticker in all_tickers:
        stock_data = fetch_stock_data(ticker, start_date, end_date)
        if stock_data is None:
            continue
    
        stock_data = compute_indicators(stock_data)
        features = stock_data[['MA_5', 'MA_15', 'RSI', '%K', '%D']].tail(1).values
    
        # Standardize the features
        scaler = StandardScaler()
        standardized_features = scaler.fit_transform(features)
    
        # Evaluate features using ANOVA F-value
        kbest = SelectKBest(f_classif, k=5)
        kbest.fit(standardized_features, np.ones((1,)))
        feature_scores.append((ticker, kbest.scores_.sum()))
    
    # Sort stocks by feature scores
    ranked_stocks = sorted(feature_scores, key=lambda x: x[1], reverse=True)[:10]
    
    return ranked_stocks
    

    Function to compute feature scores and rank stocks

    def rank_stocks(start_date, end_date): # Fetch historical data for all available tickers all_tickers = yf.download('^GSPC', start=start_date, end=end_date) all_tickers = pd.DataFrame(all_tickers['Adj Close']) all_tickers = all_tickers.columns

    feature_scores = []
    
    for ticker in all_tickers:
        stock_data = fetch_stock_data(ticker, start_date, end_date)
        stock_data = compute_indicators(stock_data)
        features = stock_data[['MA_5', 'MA_15', 'RSI', '%K', '%D']].tail(1).values
    
        # Standardize the features
        scaler = StandardScaler()
        standardized_features = scaler.fit_transform(features)
    
        # Evaluate features using ANOVA F-value
        kbest = SelectKBest(f_classif, k=5)
        kbest.fit(standardized_features, np.ones((1,)))
        feature_scores.append((ticker, kbest.scores_.sum()))
    
    # Sort stocks by feature scores
    ranked_stocks = sorted(feature_scores, key=lambda x: x[1], reverse=True)[:10]
    
    return ranked_stocks
    

    if name == "main": # Specify the date range for stock data start_date = "2019-01-01" end_date = "2023-06-03"

    # Rank stocks based on technical indicators
    ranked_stocks = rank_stocks(start_date, end_date)
    
    # Print results
    print("Top 10 stocks based on technical indicators:")
    for rank, stock in enumerate(ranked_stocks, start=1):
        print(f"{rank}. {stock[0]} (Score: {stock[1]})")
    
  2. Assistant

    There are several functions defined multiple times in the code, including fetch_stock_data and rank_stocks. This can cause conflicts and unexpected behavior.

    Also, the compute_indicators function is not defined in the code, which would likely cause errors when running rank_stocks.

    Finally, there may be other issues with the code that are not immediately apparent without additional context or information.