import os
import pandas as pd
from datetime import datetime
import openpyxl
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
local_file_name = 'income/output/My Account_updated.xlsx'
# Constants
DIVIDEND_ACTION_TEXT = "דבידנד תשלום" # Hebrew text for "Dividend Payment"
def read_file(file_name):
relevant_cols = ["תאריך נכונות", "סוג פעולה", "סכום עיסקה נטו מט\"ח", "סימבול OSI"]
available_cols = pd.read_excel(file_name, nrows=0).columns
missing_cols = [col for col in relevant_cols if col not in available_cols]
if missing_cols:
raise KeyError(f"The following required columns are missing in the file: {missing_cols}")
data = pd.read_excel(file_name, usecols=relevant_cols)
data.rename(columns={'תאריך נכונות': 'date', 'סוג פעולה': 'action', 'סכום עיסקה נטו מט\"ח': 'amount', 'סימבול OSI': 'stock'}, inplace=True)
# print(data)
data['date'] = pd.to_datetime(data['date'], format='%d/%m/%Y')
print('number of rows loaded: ' + str(len(data)))
data = data[(data.amount > 0) & (data.action == DIVIDEND_ACTION_TEXT) & (data.date >= datetime(2025, 1, 1))]
print('number of rows after filtering: ' + str(len(data)))
# print(data)
return data
# Press the green button in the gutter to run the script.
def update_data(dividends_received, input_file_path):
# open the Excel file
workbook = openpyxl.load_workbook(input_file_path)
# select the sheet to modify
if 'Dividends' not in workbook.sheetnames:
raise KeyError("The sheet 'Dividends' is missing in the Excel file.")
sheet = workbook['Dividends']
header_row = sheet[1]
for index, row in dividends_received.iterrows():
# find column to update
company_col = None
month_row = None
for column_cell in header_row:
if column_cell.value == row['stock']:
company_col = column_cell.column
# print('company: ' + str(row['stock']) + ', column: ' + str(column_cell))
break
if company_col is None:
print('Error: Column not found for company: ' + str(row['stock']))
continue
# find row to update
div_month = pd.to_datetime(row['date'], format='%d/%m/%Y').month_name().lower()
for rowNumber in range(3, 15):
if div_month == str(sheet.cell(row=rowNumber, column=1).value).lower():
month_row = rowNumber
# print('month: ' + div_month + ', row: ' + str(month_row))
break
if month_row is None:
print('HELP!!! Could not find row for month: ' + div_month)
continue
target_cell = sheet.cell(row=month_row, column=company_col)
prev_value = target_cell.value
if prev_value is None:
target_cell.value = row['amount']
print(row['stock'], "Updated cell", month_row, ":", company_col, "from value: None to new value:", row['amount'])
elif prev_value != row['amount']:
print(row['stock'], "ERR: DID NOT Update cell", month_row, ":", company_col, "from value: ", prev_value, "to new value:", row['amount'])
else:
pass
workbook.save(local_file_name)
def upload_to_drive():
gauth = GoogleAuth()
# This method opens a local web server for authentication.
# Ensure that your firewall or network settings allow this operation.
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)
drive_file_name = 'My Account_{date}.xlsx'.format(date=datetime.now().strftime('%Y-%m-%d'))
f = drive.CreateFile({'title': drive_file_name})
f.SetContentFile(local_file_name)
f.Upload()
# Due to a known bug in pydrive if we
# don't empty the variable used to
# upload the files to Google Drive the
# file stays open in memory and causes a
# Explicitly setting f to None to avoid memory leaks due to a known bug in PyDrive.
# Check if this bug has been resolved in newer versions of PyDrive.
f = None
print('File uploaded successfully to Google Drive as:', drive_file_name)
if __name__ == '__main__':
dividends_received = read_file('income/input/ביצועים היסטוריים.xlsx')
update_data(dividends_received, 'income/input/My Account.xlsx')
upload_to_drive()