Created
April 29, 2022 18:45
-
-
Save intrinio-gists/9424ea1cdf3530197480af16ac787a8c to your computer and use it in GitHub Desktop.
SMA Full Code Walkthrough
This file contains 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
import requests | |
import numpy as np | |
import pandas as pd | |
intrinio_api_key = "YOUR_INTRINIO_API_KEY_HERE" | |
def _stock_prices_dataset(ticker): | |
res = requests.get(f"https://api-v2.intrinio.com/securities/{ticker}/prices?page_size=10000&api_key={intrinio_api_key}") | |
stock_prices_dataset = pd.DataFrame(res.json().get("stock_prices")) | |
stock_prices_dataset = stock_prices_dataset[["date", "adj_close"]][::-1].reset_index(drop=True) | |
stock_prices_dataset["returns"] = np.log(stock_prices_dataset["adj_close"]).diff() | |
stock_prices_dataset["returns"] = stock_prices_dataset["returns"].shift(-1) | |
return stock_prices_dataset | |
def _sma_stock_prices_dataset(stock_prices_dataset, long_sma = 200, short_sma = 50): | |
stock_prices_dataset[f"{long_sma}_day_sma"] = stock_prices_dataset["adj_close"].rolling(long_sma).mean() | |
stock_prices_dataset[f"{short_sma}_day_sma"] = stock_prices_dataset["adj_close"].rolling(short_sma).mean() | |
stock_prices_dataset = stock_prices_dataset.dropna() | |
stock_prices_dataset = stock_prices_dataset.reset_index(drop=True) | |
return stock_prices_dataset | |
def _sma_crossover_dataset(sma_stock_prices_dataset, long_sma = 200, short_sma = 50): | |
sma_crossover_datalist = [] | |
sma_stock_prices_dataset["crossover_signal"] = np.where(sma_stock_prices_dataset[f"{short_sma}_day_sma"] >= sma_stock_prices_dataset[f"{long_sma}_day_sma"], 1, 0) | |
sma_stock_prices_dataset["prev_crossover_signal"] = sma_stock_prices_dataset["crossover_signal"].shift(1, fill_value=0) | |
sma_stock_prices_dataset["buy"] = (sma_stock_prices_dataset["crossover_signal"] == 1) & (sma_stock_prices_dataset["prev_crossover_signal"] == 0) | |
sma_stock_prices_dataset["buy"] = sma_stock_prices_dataset["buy"] .replace({True: 1, False: 0}) | |
sma_stock_prices_dataset["sell"] = (sma_stock_prices_dataset["crossover_signal"] == 0) & (sma_stock_prices_dataset["prev_crossover_signal"] == 1) | |
sma_stock_prices_dataset["sell"] = sma_stock_prices_dataset["sell"] .replace({True: 1, False: 0}) | |
holding = False | |
for sma_stock_prices in sma_stock_prices_dataset.to_dict("records"): | |
if holding and sma_stock_prices.get("sell") == 1: | |
holding = False | |
if not holding and sma_stock_prices.get("buy") == 1: | |
holding = True | |
sma_stock_prices["hold"] = holding | |
sma_crossover_datalist.append(sma_stock_prices) | |
sma_crossover_dataset = pd.DataFrame(sma_crossover_datalist) | |
return sma_crossover_dataset | |
def _sma_returns_data(sma_crossover_dataset): | |
sma_crossover_dataset["algo_returns"] = sma_crossover_dataset["returns"] * sma_crossover_dataset["hold"] | |
sma_return = round(sma_crossover_dataset["algo_returns"].sum() * 100, 3) | |
buy_and_hold_return = round(sma_crossover_dataset["returns"].sum() * 100, 3) | |
total_entries = sma_crossover_dataset["buy"].sum() | |
return sma_return, buy_and_hold_return, total_entries | |
def sma_handler(ticker, long_sma = 200, short_sma = 50): | |
stock_prices_dataset = _stock_prices_dataset(ticker) | |
start_date = stock_prices_dataset.iloc[0]['date'] | |
sma_stock_prices_dataset = _sma_stock_prices_dataset(stock_prices_dataset, long_sma, short_sma) | |
sma_crossover_dataset = _sma_crossover_dataset(sma_stock_prices_dataset, long_sma, short_sma) | |
sma_return, buy_and_hold_return, total_entries = _sma_returns_data(sma_crossover_dataset) | |
print(f"Start Date: {start_date}") | |
print(f"SMA Return: {sma_return}") | |
print(f"Buy and Hold Return: {buy_and_hold_return}") | |
print(f"Total Entries: {total_entries}") | |
sma_handler("PLTR") | |
# Start Date: 2020-09-30 | |
# SMA Return: -15.29 | |
# Buy and Hold Return: -66.865 | |
# Total Entries: 2 | |
sma_handler("AAPL") | |
# Start Date: 1982-09-16 | |
# SMA Return: 429.385 | |
# Buy and Hold Return: 685.877 | |
# Total Entries: 26 | |
sma_handler("GME") | |
# Start Date: 2002-02-13 | |
# SMA Return: 345.54 | |
# Buy and Hold Return: 303.315 | |
# Total Entries: 16 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment