Last active
February 10, 2025 21:48
-
-
Save bernardoVale/6d9448582b49d99cf422c2db146123d2 to your computer and use it in GitHub Desktop.
DividendFlow
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 bt | |
import pandas as pd | |
class DividendFlow(bt.Algo): | |
def __init__(self, dividends: pd.DataFrame): | |
self.dividends = dividends | |
self.initialized = False | |
self.last_date = None | |
self.payments = {} | |
self.windows = set() | |
super(DividendFlow, self).__init__() | |
def __call__(self, target: bt.Strategy): | |
# skip first execution where we don't have anything allocated, so no dividends to reinvest | |
if not self.initialized: | |
self.initialized = True | |
self.last_date = target.now | |
return True | |
start_window = self.last_date.strftime('%Y-%m-%d') | |
end_window = target.now.strftime('%Y-%m-%d') | |
dividends_range: pd.DataFrame = self.dividends.loc[start_window:end_window] | |
self.last_date = target.now | |
for date, loc in dividends_range.iterrows(): | |
if date in self.windows: | |
continue | |
else: | |
self.windows.add(date) | |
for ticker, dividend in loc.items(): | |
try: | |
stock_amount = target.positions[ticker][date] # check if we had this stock at this date | |
except KeyError: | |
continue | |
try: | |
cash = dividend * stock_amount | |
except KeyError: | |
break | |
if cash > 0: | |
target.adjust(cash, flow=False) | |
return True | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment