Skip to content

Instantly share code, notes, and snippets.

@CryptoFaker
Created February 5, 2025 01:48
Show Gist options
  • Save CryptoFaker/f90e7d113f01b9afad8eb6cfe64ac01a to your computer and use it in GitHub Desktop.
Save CryptoFaker/f90e7d113f01b9afad8eb6cfe64ac01a to your computer and use it in GitHub Desktop.
SpikeMethod for CSV data
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import linregress
file_name = "Pydata1.csv"
data = pd.read_csv(file_name, sep=";", parse_dates=["Time"], index_col="Time")
data.columns = data.columns.str.strip().str.lower()
data = data.dropna()
print("Kolumnnamn i datan:", data.columns)
print("Första raderna i datan:\n", data.head())
def calculate_bollinger_bands(df, window=20, num_std=2):
df['sma'] = df['price'].rolling(window=window).mean()
df['std'] = df['price'].rolling(window=window).std()
df['upper band'] = df['sma'] + (num_std * df['std'])
df['lower band'] = df['sma'] - (num_std * df['std'])
return df
data = calculate_bollinger_bands(data)
interval = '120T'
bar_times = data.resample(interval).first().dropna()
if bar_times.empty:
bar_times = data.resample(interval).first().ffill()
if bar_times.empty:
raise ValueError("Resampling skapade en tom dataframe! Kontrollera din data.")
bar_prices = bar_times['price'].dropna()
bar_prices.index = range(len(bar_prices))
slope, intercept, _, _, _ = linregress(bar_prices.index, bar_prices.values)
trend_line = intercept + slope * np.array(bar_prices.index)
matching_bollinger = data.reindex(bar_times.index).dropna()
min_length = min(len(matching_bollinger.index), len(bar_prices))
bar_prices = bar_prices.iloc[:min_length]
matching_bollinger = matching_bollinger.iloc[:min_length]
trend_line = trend_line[:min_length]
breakout = any(
(trend_line > matching_bollinger['upper band']).values |
(trend_line < matching_bollinger['lower band']).values
)
print("Längd på matching_bollinger.index:", len(matching_bollinger.index))
print("Längd på bar_prices:", len(bar_prices))
print(f"Breakout detected: {breakout}")
plt.figure(figsize=(12, 6))
plt.plot(data.index, data['price'], label='Price', color='blue', alpha=0.5)
plt.plot(data.index, data['upper band'], label='Upper BB', linestyle='dashed', color='red')
plt.plot(data.index, data['lower band'], label='Lower BB', linestyle='dashed', color='red')
plt.scatter(matching_bollinger.index, bar_prices, color='black', label='Two-hour Bars', zorder=3)
plt.plot(matching_bollinger.index, trend_line, label='Trend Line', color='green', linewidth=2)
plt.legend()
plt.title(f'Breakout Detected: {breakout}')
plt.xlabel('Time')
plt.ylabel('Price')
plt.xticks(rotation=45)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment