Created
February 16, 2024 00:08
-
-
Save fsndzomga/b5d0576f2c5c608e2a9520bb61470da6 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
import yfinance as yfinance | |
import pandas as data_frame | |
import numpy as numerical | |
def retrieve_stock_data(symbol, begin_date, finish_date): | |
""" | |
Obtain historical stock data from Yahoo Finance. | |
""" | |
historical_data = yfinance.download(symbol, start=begin_date, end=finish_date) | |
return historical_data | |
def compute_returns(historical_data, time_frames): | |
""" | |
Compute returns for specified time frames. | |
""" | |
outcome = {} | |
for time_frame in time_frames: | |
# Compute returns for the given time frame | |
historical_data[f'returns_{time_frame}'] = historical_data['Adj Close'].pct_change(periods=time_frame).shift(-time_frame) | |
# Add to outcome dictionary | |
outcome[time_frame] = historical_data[f'returns_{time_frame}'] | |
return outcome | |
def evaluate_strategies(symbols, begin_date, finish_date, intervals): | |
""" | |
Evaluate different investment strategies and compute potential returns across multiple symbols. | |
""" | |
for symbol in symbols: | |
print(f"Evaluating {symbol}...") | |
try: | |
# Retrieve stock data | |
historical_data = retrieve_stock_data(symbol, begin_date, finish_date) | |
# Compute returns | |
outcomes = compute_returns(historical_data, intervals) | |
# Display summary statistics for each interval | |
for interval, returns_data in outcomes.items(): | |
print(f"Investment strategy for {symbol}: Hold for {interval} days") | |
print(returns_data.describe()) | |
print("\n") | |
except Exception as error: | |
print(f"Failed to evaluate {symbol} due to: {error}") | |
# Specify tickers for evaluation | |
symbols = ['AAPL', 'MSFT', 'GOOGL', 'META'] # Update with real symbols | |
# Set analysis period | |
begin_date = '2010-01-01' | |
finish_date = '2023-01-01' | |
# Define intervals for holding in days (from 2 weeks to 5 years) | |
intervals = [14, 28, 60, 180, 365, 730, 1095, 1460, 1825] | |
evaluate_strategies(symbols, begin_date, finish_date, intervals) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment