-
-
Save quantra-go-algo/a5efe73752e8b263da21765140d593e4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 1) IMPORT LIBRARIES | |
| import yfinance as yf # to fetch historical market data | |
| import pandas as pd # for DataFrame operations | |
| import matplotlib.pyplot as plt # for plotting | |
| # 2) DOWNLOAD Apple DATA AND BUILD INITIAL DF | |
| # We directly assign the downloaded DataFrame to `df` | |
| df = yf.download( | |
| tickers='AAPL', | |
| start='2020-01-01', | |
| end='2025-04-01', | |
| progress=False | |
| ) | |
| # 3) KEEP ONLY CLOSE PRICE | |
| df = df[['Close']].rename(columns={'Close':'close'}) | |
| # Now df has one column: 'close' | |
| # 4) CALCULATE MOVING AVERAGES IN-PLACE | |
| df['sma5'] = df['close'].rolling(window=5).mean() # fast | |
| df['sma10'] = df['close'].rolling(window=10).mean() # medium | |
| df['sma15'] = df['close'].rolling(window=15).mean() # slow | |
| df = df.dropna() | |
| # GENERATE ENTRY/EXIT SIGNALS | |
| df['signal'] = 0 | |
| # fast > med & fast > slow → potential buy zone | |
| long_zone = (df['sma5'] > df['sma10']) & (df['sma5'] > df['sma15']) & (df['sma10'] > df['sma15']) | |
| # fast < med & fast < slow → potential sell zone | |
| short_zone = (df['sma5'] < df['sma10']) & (df['sma5'] < df['sma15']) & (df['sma10'] < df['sma15']) | |
| # when zone turns True from False → signal | |
| df.loc[ long_zone & ~long_zone.shift(1).fillna(False), 'signal'] = 1 | |
| df.loc[short_zone & ~short_zone.shift(1).fillna(False), 'signal'] = -1 | |
| # CALCULATE RETURNS | |
| df['market_ret'] = df['close'].pct_change() # daily market return | |
| df['strategy_ret'] = df['signal'].shift(1) * df['market_ret'] # apply yesterday’s signal today | |
| # CUMULATIVE RETURNS | |
| df['cum_market'] = (1 + df['market_ret']).cumprod() | |
| df['cum_strategy'] = (1 + df['strategy_ret']).cumprod() | |
| # PLOT PRICE & SMAs | |
| plt.figure(figsize=(14, 6)) | |
| plt.plot(df.index, df['close'], label='Close', color='black', linewidth=1) | |
| plt.plot(df.index, df['sma5'], label='5-day SMA', color='red', linewidth=1) | |
| plt.plot(df.index, df['sma10'], label='10-day SMA', color='green', linewidth=1) | |
| plt.plot(df.index, df['sma15'], label='15-day SMA', color='purple',linewidth=1) | |
| plt.title('AAPL Price & Triple SMA Crossover (5/10/15)') | |
| plt.xlabel('Date'); plt.ylabel('Price (USD)') | |
| plt.legend(); plt.grid(True); plt.tight_layout() | |
| plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment