Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pandas as pd
- import numpy as np
- import plotly.graph_objects as go
- # Sample data
- data = pd.DataFrame({
- "close": [100, 102, 104, 107, 106, 105, 110, 115, 112, 118, 120, 115, 110, 105],
- "open": [98, 100, 102, 104, 107, 106, 112, 110, 115, 112, 118, 120, 115, 110],
- "high": [102, 104, 107, 106, 105, 108, 115, 118, 120, 115, 125, 118, 112, 115],
- "low": [97, 98, 101, 100, 103, 105, 109, 110, 112, 108, 112, 110, 105, 100]
- })
- # Constants
- periods = 10
- multiplier = 3.0
- change_atr = True
- show_signals = True
- highlighting = True
- # Calculate ATR
- if change_atr:
- atr = data['high'] - data['low']
- else:
- atr = atr2 = np.mean(data['high'] - data['low'])
- for i in range(1, len(data)):
- atr2 = (atr2 * (periods - 1) + atr[i]) / periods
- atr[i] = atr2
- # Calculate SuperTrend
- up = data['high'] - multiplier * atr
- up1 = [up[0]]
- for i in range(1, len(data)):
- up1.append(up[i - 1] if data['close'][i - 1] > up[i - 1] else up[i])
- down = data['low'] + multiplier * atr
- down1 = [down[0]]
- for i in range(1, len(data)):
- down1.append(down[i - 1] if data['close'][i - 1] < down[i - 1] else down[i])
- trend = [1]
- for i in range(1, len(data)):
- if trend[i - 1] == -1 and data['close'][i] > down1[i - 1]:
- trend.append(1)
- elif trend[i - 1] == 1 and data['close'][i] < up1[i - 1]:
- trend.append(-1)
- else:
- trend.append(trend[i - 1])
- # Visualize SuperTrend
- fig = go.Figure()
- fig.add_trace(go.Scatter(x=data.index, y=up, mode='lines', name='Up Trend', line=dict(width=2, color='green'))
- fig.add_trace(go.Scatter(x=data.index, y=down, mode='lines', name='Down Trend', line=dict(width=2, color='red'))
- buy_signal_indices = [i for i in range(1, len(data)) if trend[i] == 1 and trend[i - 1] == -1]
- buy_signals = [up[i] for i in buy_signal_indices]
- sell_signal_indices = [i for i in range(1, len(data)) if trend[i] == -1 and trend[i - 1] == 1]
- sell_signals = [down[i] for i in sell_signal_indices]
- fig.add_trace(go.Scatter(x=buy_signal_indices, y=buy_signals, mode='markers', name='Buy Signals', marker=dict(size=6, color='green'))
- fig.add_trace(go.Scatter(x=sell_signal_indices, y=sell_signals, mode='markers', name='Sell Signals', marker=dict(size=6, color='red'))
- fig.update_layout(title='SuperTrend Indicator', xaxis_title='Date', yaxis_title='Price')
- fig.show()
- import pandas as pd
- # Sample data
- data = pd.DataFrame({
- "close": [100, 102, 104, 107, 106, 105, 110, 115, 112, 118, 120, 115, 110, 105],
- })
- # Constants
- periods = 10
- multiplier = 3.0
- change_atr = True
- show_signals = True
- # Calculate ATR
- if change_atr:
- atr = data['close'].diff().abs()
- else:
- atr = atr2 = data['close'].diff().abs().rolling(periods).mean()
- # Calculate SuperTrend
- up = data['close'] - multiplier * atr
- up1 = up.shift(1)
- up.iloc[0] = up1.iloc[0] if data['close'].iloc[0] > up1.iloc[0] else up.iloc[0]
- down = data['close'] + multiplier * atr
- down1 = down.shift(1)
- down.iloc[0] = down1.iloc[0] if data['close'].iloc[0] < down1.iloc[0] else down.iloc[0]
- trend = 1
- trend_values = [trend]
- for i in range(1, len(data)):
- if trend == -1 and data['close'].iloc[i] > down1.iloc[i]:
- trend = 1
- elif trend == 1 and data['close'].iloc[i] < up1.iloc[i]:
- trend = -1
- trend_values.append(trend)
- # Generate buy and sell suggestions
- buy_signals = []
- sell_signals = []
- for i in range(1, len(data)):
- if trend_values[i] == 1 and trend_values[i - 1] == -1:
- buy_signals.append((i, "Buy"))
- elif trend_values[i] == -1 and trend_values[i - 1] == 1:
- sell_signals.append((i, "Sell"))
- # Print buy and sell suggestions
- for i, signal in buy_signals:
- print(f"At index {i}, suggest to {signal} the stock.")
- for i, signal in sell_signals:
- print(f"At index {i}, suggest to {signal} the stock.")
- ==================================================================================================
- import yfinance as yf
- import pandas as pd
- def calculate_super_trend(data, periods=10, multiplier=3.0, change_atr=True):
- if change_atr:
- atr = data['Close'].diff().abs()
- else:
- atr = atr2 = data['Close'].diff().abs().rolling(periods).mean()
- up = data['Close'] - multiplier * atr
- up1 = up.shift(1)
- up.iloc[0] = up1.iloc[0] if data['Close'].iloc[0] > up1.iloc[0] else up.iloc[0]
- down = data['Close'] + multiplier * atr
- down1 = down.shift(1)
- down.iloc[0] = down1.iloc[0] if data['Close'].iloc[0] < down1.iloc[0] else down.iloc[0]
- trend = 1
- trend_values = [trend]
- for i in range(1, len(data)):
- if trend == -1 and data['Close'].iloc[i] > down1.iloc[i]:
- trend = 1
- elif trend == 1 and data['Close'].iloc[i] < up1.iloc[i]:
- trend = -1
- trend_values.append(trend)
- return trend_values
- # Define a list of stock symbols
- stocks = ["AAPL", "GOOGL", "MSFT", "TSLA"]
- for stock_symbol in stocks:
- stock_data = yf.download(stock_symbol, period="1y")
- stock_data['SuperTrend'] = calculate_super_trend(stock_data)
- buy_signals = []
- sell_signals = []
- for i in range(1, len(stock_data)):
- if stock_data['SuperTrend'].iloc[i] == 1 and stock_data['SuperTrend'].iloc[i - 1] == -1:
- buy_signals.append((i, "Buy"))
- elif stock_data['SuperTrend'].iloc[i] == -1 and stock_data['SuperTrend'].iloc[i - 1] == 1:
- sell_signals.append((i, "Sell"))
- print(f"Stock: {stock_symbol}")
- print("Buy Signals:")
- for i, signal in buy_signals:
- print(f"At index {i}, suggest to {signal} the stock.")
- print("Sell Signals:")
- for i, signal in sell_signals:
- print(f"At index {i}, suggest to {signal} the stock.")
- print("\n")
- ======================================================
- import yfinance as yf
- import pandas as pd
- def calculate_super_trend(data, periods=10, multiplier=3.0, change_atr=True):
- if change_atr:
- atr = data['Close'].diff().abs()
- else:
- atr = atr2 = data['Close'].diff().abs().rolling(periods).mean()
- up = data['Close'] - multiplier * atr
- up1 = up.shift(1)
- up.iloc[0] = up1.iloc[0] if data['Close'].iloc[0] > up1.iloc[0] else up.iloc[0]
- down = data['Close'] + multiplier * atr
- down1 = down.shift(1)
- down.iloc[0] = down1.iloc[0] if data['Close'].iloc[0] < down1.iloc[0] else down.iloc[0]
- trend = 1
- trend_values = [trend]
- for i in range(1, len(data)):
- if trend == -1 and data['Close'].iloc[i] > down1.iloc[i]:
- trend = 1
- elif trend == 1 and data['Close'].iloc[i] < up1.iloc[i]:
- trend = -1
- trend_values.append(trend)
- return trend_values
- # Define a list of stock symbols
- stocks = ["AAPL", "GOOGL", "TSLA","SBIN.NS"]
- for stock_symbol in stocks:
- stock_data = yf.download(stock_symbol, period="1y")
- stock_data['SuperTrend'] = calculate_super_trend(stock_data)
- last_signal = stock_data['SuperTrend'].iloc[-1]
- if last_signal == 1:
- print(f"For stock {stock_symbol}, the final suggestion is to Buy.")
- elif last_signal == -1:
- print(f"For stock {stock_symbol}, the final suggestion is to Sell.")
- else:
- print(f"For stock {stock_symbol}, no suggestion is available.")
- =============================== Grouped Results =============================
- import yfinance as yf
- import pandas as pd
- def calculate_super_trend(data, periods=10, multiplier=3.0, change_atr=True):
- if change_atr:
- atr = data['Close'].diff().abs()
- else:
- atr = atr2 = data['Close'].diff().abs().rolling(periods).mean()
- up = data['Close'] - multiplier * atr
- up1 = up.shift(1)
- up.iloc[0] = up1.iloc[0] if data['Close'].iloc[0] > up1.iloc[0] else up.iloc[0]
- down = data['Close'] + multiplier * atr
- down1 = down.shift(1)
- down.iloc[0] = down1.iloc[0] if data['Close'].iloc[0] < down1.iloc[0] else down.iloc[0]
- trend = 1
- trend_values = [trend]
- for i in range(1, len(data)):
- if trend == -1 and data['Close'].iloc[i] > down1.iloc[i]:
- trend = 1
- elif trend == 1 and data['Close'].iloc[i] < up1.iloc[i]:
- trend = -1
- trend_values.append(trend)
- return trend_values
- # Define a list of stock symbols
- stocks = ["GOOGL", "SBIN.NS", "TSLA"]
- buy_suggestions = []
- sell_suggestions = []
- for stock_symbol in stocks:
- stock_data = yf.download(stock_symbol, period="1y")
- stock_data['SuperTrend'] = calculate_super_trend(stock_data)
- last_signal = stock_data['SuperTrend'].iloc[-1]
- if last_signal == 1:
- buy_suggestions.append((stock_symbol, "Buy"))
- elif last_signal == -1:
- sell_suggestions.append((stock_symbol, "Sell"))
- # Group Buy and Sell suggestions for better visualization
- all_suggestions = buy_suggestions + sell_suggestions
- print("Buy Suggestions:")
- for stock, suggestion in buy_suggestions:
- print(f"For stock {stock}, the final suggestion is to {suggestion}.")
- print("\nSell Suggestions:")
- for stock, suggestion in sell_suggestions:
- print(f"For stock {stock}, the final suggestion is to {suggestion}.")
- print("\nAll Suggestions (Buy first, then Sell):")
- for stock, suggestion in all_suggestions:
- print(f"For stock {stock}, the final suggestion is to {suggestion}.")
- ============================ Final Result ================================
- import yfinance as yf
- import pandas as pd
- import os
- from datetime import datetime
- def calculate_super_trend(data, periods=10, multiplier=3.0, change_atr=True):
- if change_atr:
- atr = data['Close'].diff().abs()
- else:
- atr = atr2 = data['Close'].diff().abs().rolling(periods).mean()
- up = data['Close'] - multiplier * atr
- up1 = up.shift(1)
- up.iloc[0] = up1.iloc[0] if data['Close'].iloc[0] > up1.iloc[0] else up.iloc[0]
- down = data['Close'] + multiplier * atr
- down1 = down.shift(1)
- down.iloc[0] = down1.iloc[0] if data['Close'].iloc[0] < down1.iloc[0] else down.iloc[0]
- trend = 1
- trend_values = [trend]
- for i in range(1, len(data)):
- if trend == -1 and data['Close'].iloc[i] > down1.iloc[i]:
- trend = 1
- elif trend == 1 and data['Close'].iloc[i] < up1.iloc[i]:
- trend = -1
- trend_values.append(trend)
- return trend_values
- # Create a "cache" folder if it doesn't exist
- if not os.path.exists("cache"):
- os.makedirs("cache")
- # Define a list of stock symbols
- stocks = ["GOOGL", "SBIN.NS", "TSLA"]
- buy_suggestions = []
- sell_suggestions = []
- for stock_symbol in stocks:
- # Construct the cache file name using the stock symbol and current date
- today = datetime.now().strftime('%Y-%m-%d')
- cache_filename = f"cache/{stock_symbol}_{today}.csv"
- if os.path.exists(cache_filename):
- # Load data from cache if available
- stock_data = pd.read_csv(cache_filename, index_col=0, parse_dates=True)
- else:
- # Download new data
- stock_data = yf.download(stock_symbol, period="1d")
- stock_data['SuperTrend'] = calculate_super_trend(stock_data)
- # Check if SuperTrend data is empty
- if stock_data['SuperTrend'].dropna().empty:
- print(f"No SuperTrend data available for {stock_symbol}.")
- else:
- # Save the data to the cache
- stock_data.to_csv(cache_filename)
- last_signal = stock_data['SuperTrend'].iloc[-1]
- if last_signal == 1:
- buy_suggestions.append((stock_symbol, "Buy"))
- elif last_signal == -1:
- sell_suggestions.append((stock_symbol, "Sell"))
- # Group Buy and Sell suggestions for better visualization
- all_suggestions = buy_suggestions + sell_suggestions
- print("Buy Suggestions:")
- for stock, suggestion in buy_suggestions:
- print(f"For stock {stock}, the final suggestion is to {suggestion}.")
- print("\nSell Suggestions:")
- for stock, suggestion in sell_suggestions:
- print(f"For stock {stock}, the final suggestion is to {suggestion}.")
- print("\nAll Suggestions (Buy first, then Sell):")
- for stock, suggestion in all_suggestions:
- print(f"For stock {stock}, the final suggestion is to {suggestion}.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement