## 1 Rolling Midpoint Range
import numpy as np
import pandas as pd
import yfinance as yf
import [Link] as plt
def find_levels(data, window):
high = data['High'].rolling(window=window).max()
low = data['Low'].rolling(window=window).min()
midpoint = (high + low) / 2
diff = high - low
resistance = midpoint + (diff / 2)
support = midpoint - (diff / 2)
return support, resistance
# Download historical stock prices
symbol = "BTC-USD"
start_date = '2015-01-01'
end_date = '2024-04-04'
data = [Link](symbol, start=start_date, end=end_date)
window = 30
# Calculate support and resistance levels
support, resistance = find_levels(data, window)
# Plot the stock price, support, and resistance lines
fig, ax = [Link](figsize=(24, 8))
[Link]([Link], data['Close'], label='Stock Price')
[Link]([Link], support, label='Support', linestyle='--', color='green')
[Link]([Link], resistance, label='Resistance', linestyle='--', color='red')
ax.set_xlabel('Date')
ax.set_ylabel('Price')
ax.set_title(f'{symbol} Stock Price with Support and Resistance Levels')
[Link]()
# Add annotations for last support and resistance levels
last_support = [Link][-1]
last_resistance = [Link][-1]
[Link](f'Support: {last_support:.2f}', xy=([Link][-1], last_support),
xytext=([Link][-1] - [Link](days=30), last_support + 10),
arrowprops=dict(facecolor='green', arrowstyle='->'))
[Link](f'Resistance: {last_resistance:.2f}', xy=([Link][-1], last_resistance),
xytext=([Link][-1] - [Link](days=30), last_resistance - 10),
arrowprops=dict(facecolor='red', arrowstyle='->'))
[Link]()
[*********************100%%**********************] 1 of 1 completed
## 2 Fibonacci Retracement
import yfinance as yf
import pandas as pd
import numpy as np
import [Link] as plt
# Get the stock data for [Link]
symbol = "MSFT"
stock_data = [Link](symbol, start="2018-01-01", end="2024-04-04")
# Define the lookback period for calculating high and low prices
lookback_period = 15
# Calculate the high and low prices over the lookback period
high_prices = stock_data["High"].rolling(window=lookback_period).max()
low_prices = stock_data["Low"].rolling(window=lookback_period).min()
# Calculate the price difference and Fibonacci levels
price_diff = high_prices - low_prices
levels = [Link]([0, 0.236, 0.382, 0.5, 0.618, 0.786, 1])
fib_levels = low_prices.[Link](-1, 1) + price_diff.[Link](-1, 1) * levels
# Get the last price for each Fibonacci level
last_prices = fib_levels[-1, :]
# Define a color palette for the Fibonacci levels
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
# Plot the stock price with the Fibonacci retracement levels and last prices
fig, ax = [Link](figsize=(24,8))
[Link](stock_data.index, stock_data["Close"], label="Stock Price")
offsets = [-16, -14, -12, -10, 8, 10, 12]
for i, level in enumerate(levels):
if level == 0 or level == 1:
linestyle = "--"
else:
linestyle = "-"
[Link](stock_data.index, fib_levels[:, i], label=f"Fib {level:.3f}", linestyle=linestyle, color=colors[i])
[Link](f"{last_prices[i]:.2f}",
xy=(stock_data.index[-1], fib_levels[-1, i]),
xytext=(stock_data.index[-1] + [Link](days=5), fib_levels[-1, i] + offsets[i]),
ha="left", va="center", fontsize=16, color=colors[i])
ax.set_xlabel("Date")
ax.set_ylabel("Price")
ax.set_title(f"{symbol} with Fibonacci Retracement Levels")
[Link](loc="lower right", fontsize=14)
[Link]()
[*********************100%%**********************] 1 of 1 completed
## 3 Swing Highs and Lows
import yfinance as yf
import pandas as pd
from [Link] import argrelextrema
import [Link] as plt
# Download stock data
symbol = "AAPL"
stock_data = [Link](symbol, start="2020-01-01", end="2024-04-04")
# Identify local maxima (swing highs)
stock_data['Swing_High'] = stock_data['High'][argrelextrema(stock_data['High'].values, np.greater_equal, order=5
# Identify local minima (swing lows)
stock_data['Swing_Low'] = stock_data['Low'][argrelextrema(stock_data['Low'].values, np.less_equal, order=5)[0]]
# Find last two non-NaN values for Swing Highs and Swing Lows
last_two_resistances = stock_data['Swing_High'].dropna().tail(2)
last_two_supports = stock_data['Swing_Low'].dropna().tail(2)
# Plotting
[Link](figsize=(24,8))
[Link](stock_data['Close'], label="Close Price")
[Link](stock_data.index, stock_data['Swing_High'], color='r', label='Swing Highs', marker='o')
[Link](stock_data.index, stock_data['Swing_Low'], color='g', label='Swing Lows', marker='o')
# Annotate the last two resistance and support prices
for date, price in last_two_resistances.items():
[Link](f"{price:.2f}", (date, price), textcoords="offset points", xytext=(10,10), ha='center', color='r'
for date, price in last_two_supports.items():
[Link](f"{price:.2f}", (date, price), textcoords="offset points", xytext=(10,-15), ha='center', color=
[Link](f'{symbol} with Swing Highs & Lows')
[Link]()
[Link]()
[*********************100%%**********************] 1 of 1 completed
/var/folders/18/sbrpvhfj1mj55h_nf1msrh4m0000gn/T/ipykernel_1078/[Link]: FutureWarning: Series.__getite
m__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as label
s (consistent with DataFrame behavior). To access a value by position, use `[Link][pos]`
stock_data['Swing_High'] = stock_data['High'][argrelextrema(stock_data['High'].values, np.greater_equal, orde
r=5)[0]]
/var/folders/18/sbrpvhfj1mj55h_nf1msrh4m0000gn/T/ipykernel_1078/[Link]: FutureWarning: Series.__getite
m__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as label
s (consistent with DataFrame behavior). To access a value by position, use `[Link][pos]`
stock_data['Swing_Low'] = stock_data['Low'][argrelextrema(stock_data['Low'].values, np.less_equal, order=5)[0
]]
## 4 Pivot Point Analysis
import pandas as pd
import numpy as np
import [Link] as plt
import yfinance as yf
def calculate_pivot_points(df):
df['Pivot'] = (df['High'] + df['Low'] + df['Close']) / 3
df['R1'] = 2 * df['Pivot'] - df['Low']
df['S1'] = 2 * df['Pivot'] - df['High']
df['R2'] = df['Pivot'] + (df['High'] - df['Low'])
df['S2'] = df['Pivot'] - (df['High'] - df['Low'])
return df
ticker = 'NVDA'
start_date = '2023-01-01'
end_date = '2024-04-04'
data = [Link](ticker, start=start_date, end=end_date)
df = calculate_pivot_points(data)
df = [Link]()
fig, ax = [Link](figsize=(30, 9))
[Link]([Link], df['Close'], label='Price', linewidth=2)
[Link]([Link], df['Pivot'], label='Pivot', linestyle='--', linewidth=1, color='black')
[Link]([Link], df['R1'], label='Resistance 1', linestyle='--', linewidth=1, color='red')
[Link]([Link], df['S1'], label='Support 1', linestyle='--', linewidth=1, color='green')
[Link]([Link], df['R2'], label='Resistance 2', linestyle='--', linewidth=1, color='orange')
[Link]([Link], df['S2'], label='Support 2', linestyle='--', linewidth=1, color='blue')
ax.set_title(f'{ticker} Stock Price with Pivot Points and Support/Resistance Levels')
ax.set_xlabel('Date')
ax.set_ylabel('Price')
[Link]()
# Annotate prices for the last observation
last_date = [Link][-1]
points = {
'Price': df['Close'].iloc[-1],
'Pivot': df['Pivot'].iloc[-1],
'R1': df['R1'].iloc[-1],
'S1': df['S1'].iloc[-1],
'R2': df['R2'].iloc[-1],
'S2': df['S2'].iloc[-1],
}
colors = {
'Price': 'blue',
'Pivot': 'black',
'R1': 'red',
'S1': 'green',
'R2': 'orange',
'S2': 'blue'
}
sorted_points = sorted([Link](), key=lambda x: x[1])
for i, (label, value) in enumerate(sorted_points):
[Link](f"{value:.2f}", xy=(last_date, value), xytext=(5, i * 15),
textcoords="offset points", fontsize=15, ha='left', va='center', color=colors[label])
[Link]()
[*********************100%%**********************] 1 of 1 completed
## 5 K-Means Price Clustering
import yfinance as yf
import numpy as np
import [Link] as plt
from [Link] import KMeans
# Download stock data
symbol = "BTC-USD"
stock_data = [Link](symbol, start="2020-01-01", end="2024-04-04")
# Preparing data for clustering: Normalize time and price to have similar scales
X_time = [Link](0, 1, len(stock_data)).reshape(-1, 1)
X_price = (stock_data['Close'].values - [Link](stock_data['Close'])) / ([Link](stock_data['Close']) - [Link](stock_da
X_cluster = np.column_stack((X_time, X_price))
# Applying KMeans clustering
num_clusters = 5
kmeans = KMeans(n_clusters=num_clusters)
[Link](X_cluster)
# Extract cluster centers and rescale back to original price range
cluster_centers = kmeans.cluster_centers_[:, 1] * ([Link](stock_data['Close']) - [Link](stock_data['Close'])) +
# Plotting
[Link](figsize=(28,7))
[Link](stock_data['Close'], label="Close Price")
for center in cluster_centers:
[Link](y=center, color='r', linestyle='--')
[Link](f"{center:.2f}", xy=(stock_data.index[-1], center * 1.01), xytext=(5,0), textcoords="offset points"
[Link](f'{symbol} Price Data with KMeans Clustering')
[Link]()
[Link]()
[*********************100%%**********************] 1 of 1 completed
## 6 Volume Profiler
import yfinance as yf
import numpy as np
import [Link] as plt
# Download stock data
symbol = "BTC-USD"
stock_data = [Link](symbol, start="2018-01-01", end="2024-04-04")
# Calculate volume profile
price_bins = [Link](stock_data['Low'].min(), stock_data['High'].max(), 100)
volume_profile = []
for i in range(len(price_bins)-1):
bin_mask = (stock_data['Close'] > price_bins[i]) & (stock_data['Close'] <= price_bins[i+1])
volume_profile.append(stock_data['Volume'][bin_mask].sum())
# Estimating support and resistance
current_price = stock_data['Close'].iloc[-1]
support_idx = [Link](volume_profile[:[Link](current_price, price_bins)])
resistance_idx = [Link](volume_profile[[Link](current_price, price_bins):]) + [Link](current_price,
support_price = price_bins[support_idx]
resistance_price = price_bins[resistance_idx]
# Plotting
fig, (ax1, ax2) = [Link](nrows=1, ncols=2, figsize=(20, 5), gridspec_kw={'width_ratios': [3, 1]})
[Link](stock_data['Close'], label="Close Price")
[Link](y=support_price, color='g', linestyle='--', label='Support')
[Link](y=resistance_price, color='r', linestyle='--', label='Resistance')
[Link]()
ax1.set_title(f'{symbol} Price Data')
[Link](price_bins[:-1], volume_profile, height=(price_bins[1] - price_bins[0]), color='blue', edgecolor='none'
ax2.set_title('Volume Profile')
plt.tight_layout()
[Link]()
print(f"Estimated Support Price: {support_price:.2f}")
print(f"Estimated Resistance Price: {resistance_price:.2f}")
[*********************100%%**********************] 1 of 1 completed
Estimated Support Price: 8893.02
Estimated Resistance Price: 68048.35
## 7 Linear and Polinomial Regression
import yfinance as yf
import pandas as pd
import numpy as np
import [Link] as plt
from [Link] import argrelextrema
from [Link] import PolynomialFeatures
from sklearn.linear_model import LinearRegression
# Specify the ticker
symbol = "BTC-USD"
# Download stock data
stock_data = [Link](symbol, start="2023-01-01", end="2024-04-04")
# Identify local maxima (swing highs) and minima (swing lows)
swing_highs = argrelextrema(stock_data['High'].values, np.greater_equal, order=5)[0]
swing_lows = argrelextrema(stock_data['Low'].values, np.less_equal, order=5)[0]
# Linear regression for trendlines
upper_m, upper_b = [Link](swing_highs, stock_data['High'].values[swing_highs], 1)
lower_m, lower_b = [Link](swing_lows, stock_data['Low'].values[swing_lows], 1)
stock_data['Upper_Trendline'] = upper_m * [Link](len(stock_data)) + upper_b
stock_data['Lower_Trendline'] = lower_m * [Link](len(stock_data)) + lower_b
# Preparing data for polynomial regression
X = [Link](range(len(stock_data))).reshape(-1, 1)
y = stock_data['Close'].values
# Polynomial regression
poly = PolynomialFeatures(degree=5)
X_poly = poly.fit_transform(X)
poly_regressor = LinearRegression()
poly_regressor.fit(X_poly, y)
y_pred = poly_regressor.predict(X_poly)
# Plotting
fig, (ax1, ax2) = [Link](1, 2, figsize=(20,6))
[Link](stock_data['Close'], label="Close Price")
[Link](stock_data['Upper_Trendline'], label="Upper Trendline", color="orange")
[Link](stock_data['Lower_Trendline'], label="Lower Trendline", color="blue")
# Annotate last prices for Trendlines
[Link](f"{stock_data['Upper_Trendline'].iloc[-1]:.2f}",
xy=(stock_data.index[-1], stock_data['Upper_Trendline'].iloc[-1]),
xytext=(stock_data.index[-1], stock_data['Upper_Trendline'].iloc[-1] + 5),
arrowprops=dict(arrowstyle='->'))
[Link](f"{stock_data['Lower_Trendline'].iloc[-1]:.2f}",
xy=(stock_data.index[-1], stock_data['Lower_Trendline'].iloc[-1]),
xytext=(stock_data.index[-1], stock_data['Lower_Trendline'].iloc[-1] - 10),
arrowprops=dict(arrowstyle='->'))
ax1.set_title(f'{symbol} with Trendlines')
[Link](loc = "lower right")
[Link](stock_data['Close'], label="Close Price")
[Link](stock_data.index, y_pred, color='r', label="Polynomial Support/Resistance")
# Annotate last price for Polynomial Regression
[Link](f"{y_pred[-1]:.2f}",
xy=(stock_data.index[-1], y_pred[-1]),
xytext=(stock_data.index[-1], y_pred[-1] + 5),
arrowprops=dict(arrowstyle='->'))
ax2.set_title(f'{symbol} Price Data with Polynomial Regression')
[Link]()
plt.tight_layout()
[Link]()
[*********************100%%**********************] 1 of 1 completed
Loading [MathJax]/jax/output/CommonHTML/fonts/TeX/[Link]