-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScript.py
More file actions
42 lines (36 loc) · 1.27 KB
/
Script.py
File metadata and controls
42 lines (36 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
# Load data
ticker = 'BTC-USD' # or 'SPY' for S&P 500
data = yf.download(ticker, start='2020-01-01', end='2024-12-31')
data = data[['Close']]
print(data.head())
# Compute moving averages
data['SMA50'] = data['Close'].rolling(window=50).mean()
data['SMA200'] = data['Close'].rolling(window=200).mean()
# Create signals
data['Position'] = 0
#data['Position'][data['SMA50'] > data['SMA200']] = 1
#data['Position'][data['SMA50'] < data['SMA200']] = -1
#data['Signal'] = data['Position'].diff()
for i, r in data.iterrows():
if r['SMA50'] > r['SMA200']:
data.at[r[0], 'Position'] = 1
else:
data.at[r[0], 'Position'] = -1
# Calculate returns
data['Market Return'] = data['Close'].pct_change()
data['Strategy Return'] = data['Market Return'] * data['Position'].shift(1)
# Plot signals
plt.figure(figsize=(14,6))
plt.plot(data['Close'], label='Price', alpha=0.5)
plt.plot(data['SMA50'], label='SMA50', alpha=0.75)
plt.plot(data['SMA200'], label='SMA200', alpha=0.75)
plt.legend()
plt.title(f"{ticker} SMA Crossover Strategy")
plt.show()
# Strategy performance
cumulative_return = (1 + data['Strategy Return']).cumprod()
cumulative_return.plot(figsize=(14,6), title="Strategy Cumulative Return")
plt.show()