7.2 KiB
This code downloads historical stock data for TLT, computes log returns, and analyzes mean returns by calendar day of the month. It visualizes these mean returns to identify any calendar effects. The code also simulates a simple trading strategy of buying near month-end and selling at month-start. It evaluates the strategy's performance by aggregating and plotting returns over time. This analysis helps in identifying potential trading opportunities based on calendar effects.
import pandas as pd import numpy as np import yfinance as yf
Download historical stock data for TLT from Yahoo Finance
tlt = yf.download("TLT", start="2002-01-01", end="2022-06-30")
Compute log returns for the adjusted closing prices
tlt["log_return"] = np.log(tlt["Adj Close"] / tlt["Adj Close"].shift(1))
Add a column indicating the day of the month for each data entry
tlt["day_of_month"] = tlt.index.day
Add a column indicating the year for each data entry
tlt["year"] = tlt.index.year
Group the data by the day of the month and compute the mean log returns
grouped_by_day = tlt.groupby("day_of_month").log_return.mean()
Plot the mean log returns by calendar day of the month
grouped_by_day.plot.bar(title="Mean Log Returns by Calendar Day of Month")
Initialize a simple trading strategy of buying before month-end and selling at month-start
# Set initial returns for the first week of the month to zero tlt["first_week_returns"] = 0.0
# Assign log returns to the first week of the month tlt.loc[tlt.day_of_month <= 7, "first_week_returns"] = tlt[tlt.day_of_month <= 7].log_return
# Set initial returns for the last week of the month to zero tlt["last_week_returns"] = 0.0
# Assign log returns to the last week of the month tlt.loc[tlt.day_of_month >= 23, "last_week_returns"] = tlt[tlt.day_of_month >= 23].log_return
Compute the difference between last week returns and first week returns to simulate the strategy
tlt["last_week_less_first_week"] = tlt.last_week_returns - tlt.first_week_returns
Group the data by year and plot the mean returns of the strategy for each year
( tlt.groupby("year") .last_week_less_first_week.mean() .plot.bar(title="Mean Log Strategy Returns by Year") )
Group the data by year, compute cumulative sum of returns, and plot it
( tlt.groupby("year") .last_week_less_first_week.sum() .cumsum() .plot(title="Cumulative Sum of Returns By Year") )
Compute and plot the cumulative sum of returns by day
tlt.last_week_less_first_week.cumsum().plot(title="Cumulative Sum of Returns By Day")
PyQuant News is where finance practitioners level up with Python for quant finance, algorithmic trading, and market data analysis. Looking to get started? Check out the fastest growing, top-selling course to get started with Python for quant finance. For educational purposes. Not investment advise. Use at your own risk.
