Google Colab JavaScript Error
Created on: October 2, 2024
Answered using O1 Preview by Chat01
Created on: October 2, 2024
Answered using O1 Preview by Chat01
import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import argrelextrema
import os
from prophet import Prophet
import datetime
def fetch_price_data(ticker, start_date, end_date):
try:
data = yf.download(ticker, start=start_date, end=end_date, interval='1d', progress=False)
data.reset_index(inplace=True)
return data
except Exception as e:
print(f"Error fetching data for {ticker}: {e}")
return None
def calculate_supertrend(data, period=20, multiplier=4):
df = data.copy()
hl2 = (df['High'] + df['Low']) / 2
df['TR'] = abs(df['High'] - df['Low'])
df['TR1'] = abs(df['High'] - df['Close'].shift())
df['TR2'] = abs(df['Low'] - df['Close'].shift())
df['TR'] = df[['TR', 'TR1', 'TR2']].max(axis=1)
df['ATR'] = df['TR'].rolling(window=period).mean()
text# Basic Upperband and Lowerband df['basic_upperband'] = hl2 + (multiplier * df['ATR']) df['basic_lowerband'] = hl2 - (multiplier * df['ATR']) # Final Upperband and Lowerband df['final_upperband'] = df['basic_upperband'] df['final_lowerband'] = df['basic_lowerband'] for i in range(1, len(df)): # For upperband if df['Close'].iloc[i - 1] <= df['final_upperband'].iloc[i - 1]: df['final_upperband'].iloc[i] = min(df['basic_upperband'].iloc[i], df['final_upperband'].iloc[i - 1]) else: df['final_upperband'].iloc[i] = df['basic_upperband'].iloc[i] # For lowerband if df['Close'].iloc[i - 1] >= df['final_lowerband'].iloc[i - 1]: df['final_lowerband'].iloc[i] = max(df['basic_lowerband'].iloc[i], df['final_lowerband'].iloc[i - 1]) else: df['final_lowerband'].iloc[i] = df['basic_lowerband'].iloc[i] # Determine Supertrend df['Supertrend'] = np.nan for i in range(len(df)): if i == 0: df['Supertrend'].iloc[i] = df['final_upperband'].iloc[i] continue if df['Close'].iloc[i - 1] <= df['final_upperband'].iloc[i - 1]: if df['Close'].iloc[i] > df['final_upperband'].iloc[i]: df['Supertrend'].iloc[i] = df['final_lowerband'].iloc[i] else: df['Supertrend'].iloc[i] = df['final_upperband'].iloc[i] else: if df['Close'].iloc[i] < df['final_lowerband'].iloc[i]: df['Supertrend'].iloc[i] = df['final_upperband'].iloc[i] else: df['Supertrend'].iloc[i] = df['final_lowerband'].iloc[i] data['Supertrend'] = df['Supertrend'] return data
def identify_elliott_wave(data):
if data is None or data.empty:
return None
textclose = data['Close'].values idx = np.arange(len(close)) # Find local minima and maxima order = 5 # Sensitivity of extrema detection max_idx = argrelextrema(close, np.greater, order=order)[0] min_idx = argrelextrema(close, np.less, order=order)[0] # Combine and sort extrema extrema_idx = np.sort(np.concatenate((max_idx, min_idx))) extrema_prices = close[extrema_idx] # Check if there are enough extrema if len(extrema_idx) < 3: return None # Focus on the last 3 extrema last_extrema_idx = extrema_idx[-3:] last_extrema_prices = close[last_extrema_idx] # Identify Wave 1 and Wave 2 wave1_start_idx = last_extrema_idx[0] wave1_end_idx = last_extrema_idx[1] wave2_end_idx = last_extrema_idx[2] wave1_start = close[wave1_start_idx] wave1_end = close[wave1_end_idx] wave2_end = close[wave2_end_idx] # Determine if Wave 1 is upward if wave1_end > wave1_start: wave1_length = wave1_end - wave1_start wave2_length = wave1_end - wave2_end retracement = wave2_length / wave1_length # Check if retracement is within acceptable levels (e.g., 38.2% to 61.8%) if 0.382 <= retracement <= 0.618: # Potential for Wave 3 retracement_diff = abs(retracement - 0.5) probability = (1 - retracement_diff / 0.118) * 100 # Scale to 100% # Limit probability between 50% and 90% probability = max(50, min(probability, 90)) # Calculate volume during Wave 1 and Wave 3 # Estimate Wave 3 end as current index wave3_end_idx = len(data) - 1 # Assuming Wave 3 is ongoing till the last available data point # Extract volumes volume_wave1 = data['Volume'].iloc[wave1_start_idx:wave1_end_idx+1] volume_wave3 = data['Volume'].iloc[wave2_end_idx:wave3_end_idx+1] # Calculate average volumes avg_volume_wave1 = volume_wave1.mean() avg_volume_wave3 = volume_wave3.mean() # Volume confirmation: Volume during Wave 3 should be higher than during Wave 1 volume_confirmation = avg_volume_wave3 > avg_volume_wave1 # Get the dates of the extrema points wave1_start_date = data['Date'].iloc[wave1_start_idx].date() wave1_end_date = data['Date'].iloc[wave1_end_idx].date() wave2_end_date = data['Date'].iloc[wave2_end_idx].date() # Prepare wave data waves = { 'probability': probability, 'retracement': retracement, 'wave1_start_date': wave1_start_date, 'wave1_end_date': wave1_end_date, 'wave2_end_date': wave2_end_date, 'last_extrema_idx': last_extrema_idx, 'last_extrema_prices': last_extrema_prices, 'volume_confirmation': volume_confirmation, 'avg_volume_wave1': avg_volume_wave1, 'avg_volume_wave3': avg_volume_wave3 } return waves else: return None else: return None
def plot_elliott_wave(data, wave_data, ticker):
try:
# Modify charts_dir to save charts in Google Drive
charts_dir = '/content/drive/MyDrive/Charts'
if not os.path.exists(charts_dir):
os.makedirs(charts_dir)
text# Plot Elliott Wave plt.figure(figsize=(14, 7)) plt.plot(data['Date'], data['Close'], label='Close Price', color='blue') # Plot Supertrend plt.plot(data['Date'], data['Supertrend'], label='Supertrend (20,4)', color='green') indices = wave_data['last_extrema_idx'] prices = wave_data['last_extrema_prices'] dates = data['Date'].iloc[indices] plt.plot(dates, prices, 'ro-', label='Elliott Wave Points') for i, idx in enumerate(indices): date = data['Date'].iloc[idx].date() price = data['Close'].iloc[idx] plt.annotate(f"{date}", (date, price), textcoords="offset points", xytext=(0,10), ha='center') probability = wave_data['probability'] volume_msg = 'with' if wave_data['volume_confirmation'] else 'without' plt.title(f"{ticker} - Potential Wave 3 Formation {volume_msg} volume confirmation\nProbability: {probability:.2f}%") plt.xlabel('Date') plt.ylabel('Price') plt.legend() plt.grid(True) # Save the chart in Google Drive chart_filename = os.path.join(charts_dir, f"{ticker.replace('.NS', '')}_wave3.png") plt.savefig(chart_filename) print(f" Elliott Wave chart saved as {chart_filename}") plt.show() plt.close() except Exception as e: print(f"Error plotting Elliott Wave chart for {ticker}: {e}")
def predict_with_prophet(data, ticker, wave_data):
try:
# Prepare the data for Prophet
df = data[['Date', 'Close']].rename(columns={'Date': 'ds', 'Close': 'y'})
text# Initialize Prophet model model = Prophet(daily_seasonality=True) # Fit the model model.fit(df) # Make future predictions future = model.make_future_dataframe(periods=30) # Predict for the next 30 days forecast = model.predict(future) # Plot the forecast fig = model.plot(forecast) # Mark the 2nd wave end date on the Prophet plot wave2_end_date = wave_data['wave2_end_date'] wave2_end_price = data[data['Date'] == pd.Timestamp(wave2_end_date)]['Close'].values[0] # Add a star marker at the second wave end date plt.scatter(wave2_end_date, wave2_end_price, color='red', marker='*', s=200, label='Wave 2 End') # Annotate the second wave end date plt.annotate(f"Wave 2 End: {wave2_end_date}", xy=(wave2_end_date, wave2_end_price), xytext=(10, 10), textcoords="offset points", ha='center', fontsize=12, color='red') # Additional plot settings plt.title(f"{ticker} - Prophet Price Prediction with Wave 2 End") plt.xlabel('Date') plt.ylabel('Price') plt.legend() # Show the updated plot plt.show() # Save the chart in Google Drive charts_dir = '/content/drive/MyDrive/Charts' if not os.path.exists(charts_dir): os.makedirs(charts_dir) prophet_chart_filename = os.path.join(charts_dir, f"{ticker.replace('.NS', '')}_prophet_wave2.png") fig.savefig(prophet_chart_filename) print(f" Prophet chart saved as {prophet_chart_filename}") except Exception as e: print(f"Error in Prophet prediction for {ticker}: {e}")
def get_stock_list():
try:
# Mount Google Drive
from google.colab import drive
drive.mount('/content/drive')
text# Load the CSV file containing the list of stock tickers stock_list_df = pd.read_csv('/content/drive/MyDrive/ind_nifty500list (1).csv') # Replace 'Symbol' with the actual column name in your CSV file if 'Symbol' not in stock_list_df.columns: raise ValueError("The CSV file does not contain a 'Symbol' column.") stock_list = stock_list_df['Symbol'].tolist() # Append '.NS' suffix for NSE stocks if not already present stock_list = [ticker.strip().upper() if ticker.strip().upper().endswith('.NS') else ticker.strip().upper() + '.NS' for ticker in stock_list] print("Tickers to analyze:", stock_list) return stock_list except FileNotFoundError: print("CSV file not found. Please ensure the file is in your Google Drive and the path is correct.") return [] except Exception as e: print(f"An error occurred: {e}") return []
def main():
# Get the list of tickers from the CSV file in Google Drive
nifty200_tickers = get_stock_list()
if not nifty200_tickers:
print("No tickers to analyze. Exiting.")
return
text# Request start and end dates from the user start_date = input("Enter the start date (YYYY-MM-DD): ") end_date = input("Enter the end date (YYYY-MM-DD): ") results = [] print("\nAnalyzing stocks for potential Wave 3 formation...\n") for ticker in nifty200_tickers: print(f"Processing {ticker}...") data = fetch_price_data(ticker, start_date, end_date) if data is None or data.empty: print(f" Skipping {ticker} due to data issues.") continue # Calculate Supertrend indicator data = calculate_supertrend(data) wave_data = identify_elliott_wave(data) if wave_data: probability = wave_data['probability'] retracement = wave_data['retracement'] wave1_start_date = wave_data['wave1_start_date'] wave1_end_date = wave_data['wave1_end_date'] wave2_end_date = wave_data['wave2_end_date'] volume_confirmation = wave_data['volume_confirmation'] avg_volume_wave1 = wave_data['avg_volume_wave1'] avg_volume_wave3 = wave_data['avg_volume_wave3'] results.append({ 'Ticker': ticker, 'Probability': probability, 'Retracement': retracement, 'Wave1_Start_Date': wave1_start_date, 'Wave1_End_Date': wave1_end_date, 'Wave2_End_Date': wave2_end_date, 'Volume_Confirmation': volume_confirmation, 'Avg_Volume_Wave1': avg_volume_wave1, 'Avg_Volume_Wave3': avg_volume_wave3 }) volume_msg = 'with' if volume_confirmation else 'without' print(f" Potential Wave 3 formation detected {volume_msg} volume confirmation, probability {probability:.2f}% starting on {wave1_start_date}") # Plot the Elliott Wave chart with Supertrend plot_elliott_wave(data, wave_data, ticker) # Run Prophet to predict stock prices and mark Wave 2 End Date predict_with_prophet(data, ticker, wave_data) else: print(f" No potential Wave 3 formation detected.") # Convert results to DataFrame if results: df_results = pd.DataFrame(results) # Sort by Probability in descending order df_results.sort_values(by='Probability', ascending=False, inplace=True) print("\nSummary of Stocks with Potential Wave 3 Formation:") print(df_results) # Save the results DataFrame to Google Drive results_dir = '/content/drive/MyDrive/Results' if not os.path.exists(results_dir): os.makedirs(results_dir) output_file = os.path.join(results_dir, 'stock_wave3_results.csv') df_results.to_csv(output_file, index=False) print(f"\nResults saved to {output_file}") else: print("\nNo stocks with potential Wave 3 formation were found.")
if name == "main":
main()
getting the below error
Could not load the JavaScript files needed to display output. This is probably because your Google Account login access has expired or because third-party cookies are not allowed by your browser. Please reload this page.
Identifying the issue
OK, let's see: the error message indicates a problem with JavaScript files not loading, often due to expired Google Account login or blocked third-party cookies. This hints at some browser settings needing attention.
Ensuring browser access
The error message hints at browser or session problems. Ensuring a valid Google account login and enabling third-party cookies are crucial first steps.
OK, so you're mentioning various solutions to fix the JavaScript loading issue in Google Colab. This includes reloading the page, clearing cookies, and running the code in an incognito window.
Updating my approach
I'm considering why the session might be lost, thinking expired session, third-party cookies, browser extensions, or network issues could be factors.
Adjusting browser settings
I’m curious about tweaking browser settings to enable third-party cookies for Colab. This involves navigating privacy settings, adding specific sites, and disabling browser extensions.
Testing different approaches
I’m exploring browser caches, network restrictions, and browser updates. Creating a new notebook and running a minimal code snippet can pinpoint the issue.
Being mindful of JavaScript issues
It looks like you're encountering a common issue in Google Colab related to displaying outputs that require JavaScript, such as plots or interactive elements. The error message:
Could not load the JavaScript files needed to display output. This is probably because your Google Account login access has expired or because third-party cookies are not allowed by your browser. Please reload this page.
indicates that the JavaScript files necessary for rendering outputs aren't loading properly. This can happen due to several reasons, including expired login sessions, browser settings, or network issues.
Here's how you can resolve this problem:
Google Colab relies on third-party cookies to load certain scripts. If these are blocked, you'll encounter issues.
For Google Chrome:
[*.]google.com
[*.]googleusercontent.com
[*.]colab.research.google.com
For Mozilla Firefox:
For Microsoft Edge and Other Browsers:
Extensions like ad blockers, privacy tools, or script blockers can interfere with Colab.
To ensure that the issue isn't with your code, try running a minimal example:
pythonimport matplotlib.pyplot as plt plt.plot([1, 2, 3], [4, 5, 6]) plt.show()
Since your code uses prophet
, yfinance
, and other libraries, make sure they are installed properly.
python!pip install yfinance !pip install prophet !pip install --upgrade plotly
While the error message points to a browser issue, it's still good practice to ensure your code doesn't have any syntax errors or exceptions that might prevent outputs from displaying.
If the issue persists, consider running your code locally:
Action:
Reason: This bypasses browser and Colab-specific issues.
The error you're seeing is usually due to browser settings preventing Colab from loading the necessary JavaScript files to display outputs like plots. By ensuring that third-party cookies are allowed, disabling interfering extensions, and refreshing your session, you should be able to resolve the issue.
Note: Always ensure you're following best practices for security. Only enable third-party cookies or disable extensions when necessary, and consider reverting settings once you're done if you're concerned about privacy.
Let me know if you need further assistance or if the issue persists after trying these steps!