Cycles/test_bbrsi.py

121 lines
4.8 KiB
Python
Raw Normal View History

2025-05-20 18:28:53 +08:00
import logging
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
from cycles.utils.storage import Storage
from cycles.utils.data_utils import aggregate_to_daily
from cycles.Analysis.strategies import Strategy
2025-05-20 18:28:53 +08:00
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.FileHandler("backtest.log"),
logging.StreamHandler()
]
)
config_minute = {
"start_date": "2023-01-01",
"stop_date": "2024-01-01",
2025-05-20 18:28:53 +08:00
"data_file": "btcusd_1-min_data.csv"
}
config_day = {
"start_date": "2023-01-01",
"stop_date": "2024-01-01",
2025-05-20 18:28:53 +08:00
"data_file": "btcusd_1-day_data.csv"
}
config_strategy = {
"bb_width": 0.05,
"bb_period": 20,
"rsi_period": 14,
"trending": {
"rsi_threshold": [30, 70],
"bb_std_dev_multiplier": 2.5,
},
"sideways": {
"rsi_threshold": [40, 60],
"bb_std_dev_multiplier": 1.8,
},
"strategy_name": "MarketRegimeStrategy",
"SqueezeStrategy": True
}
2025-05-20 18:28:53 +08:00
IS_DAY = False
2025-05-20 18:28:53 +08:00
if __name__ == "__main__":
storage = Storage(logging=logging)
if IS_DAY:
config = config_day
else:
config = config_minute
data = storage.load_data(config["data_file"], config["start_date"], config["stop_date"])
strategy = Strategy(config=config_strategy, logging=logging)
processed_data = strategy.run(data.copy(), config_strategy["strategy_name"])
2025-05-20 18:28:53 +08:00
buy_condition = processed_data.get('BuySignal', pd.Series(False, index=processed_data.index)).astype(bool)
sell_condition = processed_data.get('SellSignal', pd.Series(False, index=processed_data.index)).astype(bool)
2025-05-20 18:28:53 +08:00
buy_signals = processed_data[buy_condition]
sell_signals = processed_data[sell_condition]
2025-05-20 18:28:53 +08:00
# plot the data with seaborn library
if processed_data is not None and not processed_data.empty:
2025-05-20 18:28:53 +08:00
# Create a figure with two subplots, sharing the x-axis
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(16, 8), sharex=True)
2025-05-20 18:28:53 +08:00
# Plot 1: Close Price and Bollinger Bands
sns.lineplot(x=processed_data.index, y='close', data=processed_data, label='Close Price', ax=ax1)
sns.lineplot(x=processed_data.index, y='UpperBand', data=processed_data, label='Upper Band (BB)', ax=ax1)
sns.lineplot(x=processed_data.index, y='LowerBand', data=processed_data, label='Lower Band (BB)', ax=ax1)
2025-05-20 18:28:53 +08:00
# Plot Buy/Sell signals on Price chart
if not buy_signals.empty:
ax1.scatter(buy_signals.index, buy_signals['close'], color='green', marker='o', s=20, label='Buy Signal', zorder=5)
if not sell_signals.empty:
ax1.scatter(sell_signals.index, sell_signals['close'], color='red', marker='o', s=20, label='Sell Signal', zorder=5)
ax1.set_title('Price and Bollinger Bands with Signals')
ax1.set_ylabel('Price')
ax1.legend()
ax1.grid(True)
# Plot 2: RSI
if 'RSI' in processed_data.columns:
sns.lineplot(x=processed_data.index, y='RSI', data=processed_data, label='RSI (' + str(config_strategy["rsi_period"]) + ')', ax=ax2, color='purple')
ax2.axhline(config_strategy["trending"]["rsi_threshold"][1], color='red', linestyle='--', linewidth=0.8, label='Overbought (' + str(config_strategy["trending"]["rsi_threshold"][1]) + ')')
ax2.axhline(config_strategy['trending']['rsi_threshold'][0], color='green', linestyle='--', linewidth=0.8, label='Oversold (' + str(config_strategy['trending']['rsi_threshold'][0]) + ')')
2025-05-20 18:28:53 +08:00
# Plot Buy/Sell signals on RSI chart
if not buy_signals.empty:
ax2.scatter(buy_signals.index, buy_signals['RSI'], color='green', marker='o', s=20, label='Buy Signal (RSI)', zorder=5)
if not sell_signals.empty:
ax2.scatter(sell_signals.index, sell_signals['RSI'], color='red', marker='o', s=20, label='Sell Signal (RSI)', zorder=5)
ax2.set_title('Relative Strength Index (RSI) with Signals')
ax2.set_ylabel('RSI Value')
ax2.set_ylim(0, 100) # RSI is typically bounded between 0 and 100
ax2.legend()
ax2.grid(True)
else:
logging.info("RSI data not available for plotting.")
# Plot 3: BB Width
sns.lineplot(x=processed_data.index, y='BBWidth', data=processed_data, label='BB Width', ax=ax3)
sns.lineplot(x=processed_data.index, y='MarketRegime', data=processed_data, label='Market Regime (Sideways: 1, Trending: 0)', ax=ax3)
ax3.set_title('Bollinger Bands Width')
ax3.set_ylabel('BB Width')
ax3.legend()
ax3.grid(True)
2025-05-20 18:28:53 +08:00
plt.xlabel('Date') # Common X-axis label
fig.tight_layout() # Adjust layout to prevent overlapping titles/labels
plt.show()
else:
logging.info("No data to plot.")