import pandas as pd
from alpha_vantage.timeseries import TimeSeries
import matplotlib.pyplot as plt
import numpy as np
import datetime
api_key = [enter_your_api_key]
def get_stock_data(symbol, interval='5min', size='compact'):
ts = TimeSeries(key=api_key, output_format='pandas')
data, meta_data = ts.get_intraday(symbol=symbol, interval=interval, outputsize=size)
df = data.rename(columns=lambda x: x.split(' ')[-1]) # Remove space in column names
df.index = pd.to_datetime(df.index)
return df
def calculate_superposition_bands(df, length=20, multiplier=1.5):
df['Middle_Band'] = df['close'].rolling(window=length).mean()
df['ATR'] = df['high'] - df['low']
df['Upper_Band'] = df['Middle_Band'] + multiplier * df['ATR']
df['Lower_Band'] = df['Middle_Band'] - multiplier * df['ATR']
return df
def generate_signals(df, atr_multiplier=0.5):
df['ATR'] = df['high'] - df['low']
df['Buy_Signal'] = ((df['close'] > df['Lower_Band']) & (df['close'].shift(1) <= df['Lower_Band'].shift(1))).astype(int)
df['Sell_Signal'] = ((df['close'] > df['Middle_Band']) & (df['close'].shift(1) <= df['Middle_Band'].shift(1))
& (df['close'] >= df['close'].shift(1) + atr_multiplier * df['ATR'].shift(1))).astype(int)
return df
def plot_superposition_bands(df, symbol, threshold=10, rolling_window=5):
df_smoothed = df.copy()
df_smoothed['close'] = df['close'].rolling(window=rolling_window).mean()
plt.figure(figsize=(12, 6))
plt.plot(df_smoothed.index, df_smoothed['close'], label='Close Price (Smoothed)', color='black')
plt.plot(df.index, df['Middle_Band'], label='Middle Band', color='blue')
plt.plot(df.index, df['Upper_Band'], label='Upper Band', color='red', linestyle='--')
plt.plot(df.index, df['Lower_Band'], label='Lower Band', color='green', linestyle='--')
plt.scatter(df[df['Buy_Signal'] == 1].index, df[df['Buy_Signal'] == 1]['close'], label='Buy Signal', marker='^', color='green')
plt.scatter(df[df['Sell_Signal'] == 1].index, df[df['Sell_Signal'] == 1]['close'], label='Sell Signal', marker='v', color='red')
plt.title(f'Superposition Bands Analysis for {symbol}')
plt.xlabel('Date (MST)')
plt.ylabel('Price')
plt.legend()
# Set y-axis range with a threshold to exclude extreme values
plt.ylim([df_smoothed['close'].min() - threshold, df_smoothed['close'].max() + threshold])
# Display relevant trading hours on x-axis
trading_hours = pd.date_range('09:30', '16:00', freq='30min')
plt.xticks(trading_hours, trading_hours.strftime('%H:%M'))
plt.show()
def monitor_stock(symbol):
df = get_stock_data(symbol)
df = calculate_superposition_bands(df)
df = generate_signals(df)
plot_superposition_bands(df, symbol)
# Example: Monitor the stock with the symbol 'TSLA'
monitor_stock('TSLA')