سرویس Pastebin (نسخه آزمایشی)
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv('data.csv', parse_dates=['Date'], index_col='Date')
data['Close'] = data['Close'].astype(float)
short_window = 20
long_window = 50
data['SMA_short'] = data['Close'].rolling(window=short_window).mean()
data['SMA_long'] = data['Close'].rolling(window=long_window).mean()
data['Signal'] = 0
data.loc[data['SMA_short'] > data['SMA_long'], 'Signal'] = 1 # سیگنال خرید
data.loc[data['SMA_short'] <= data['SMA_long'], 'Signal'] = -1 # سیگنال فروش
plt.figure(figsize=(14, 7))
plt.plot(data['Close'], label='Close Price', color='blue', alpha=0.5)
plt.plot(data['SMA_short'], label=f'{short_window}-Day SMA', color='green')
plt.plot(data['SMA_long'], label=f'{long_window}-Day SMA', color='red')
buy_signals = data[data['Signal'] == 1]
sell_signals = data[data['Signal'] == -1]
plt.scatter(buy_signals.index, buy_signals['Close'], label='Buy Signal', marker='^', color='green', alpha=1)
plt.scatter(sell_signals.index, sell_signals['Close'], label='Sell Signal', marker='v', color='red', alpha=1)
plt.title('Moving Average Crossover Strategy')
plt.xlabel('Date')
plt.ylabel('Close Price')
plt.legend()
plt.grid()
plt.show()