Skip to content

Instantly share code, notes, and snippets.

@fsndzomga
Created February 15, 2024 23:56
Show Gist options
  • Save fsndzomga/96bb3d33da49972f580087c160017c47 to your computer and use it in GitHub Desktop.
Save fsndzomga/96bb3d33da49972f580087c160017c47 to your computer and use it in GitHub Desktop.
import yfinance as yf
import pandas as pd
import numpy as np
def fetch_stock_data(ticker, start_date, end_date):
"""
Fetch historical stock data from Yahoo Finance.
"""
stock_data = yf.download(ticker, start=start_date, end=end_date)
return stock_data
def calculate_returns(data, periods):
"""
Calculate stock returns for different holding periods.
"""
returns = {}
for period in periods:
# Calculate returns for each period
data[f'return_{period}'] = data['Adj Close'].pct_change(periods=period).shift(-period)
# Store in dictionary
returns[period] = data[f'return_{period}']
return returns
def backtest_strategies(ticker, start_date, end_date, holding_periods):
"""
Backtest different investment strategies and calculate potential returns.
"""
# Fetch stock data
stock_data = fetch_stock_data(ticker, start_date, end_date)
# Calculate returns
returns = calculate_returns(stock_data, holding_periods)
# Print summary statistics for each holding period
for period, return_data in returns.items():
print(f"Strategy: Hold for {period} days")
print(return_data.describe())
print("\n")
# Define the stock ticker, start date, and end date
ticker = 'AAPL' # Example: Apple Inc.
start_date = '2010-01-01'
end_date = '2023-01-01'
# Define holding periods in days (approximations for 2 weeks to 5 years)
holding_periods = [14, 28, 60, 180, 365, 730, 1095, 1460, 1825]
backtest_strategies(ticker, start_date, end_date, holding_periods)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment