forked from dgoodburn/Project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
initialImport.py
242 lines (159 loc) · 7.94 KB
/
initialImport.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
__author__ = 'emmaachberger'
import pandas as pd
import numpy as np
from sqlalchemy import create_engine
import sqlqueries
import stockPricesImport
from mintTransactions import Mint
from helperfunctions import convert
import FXImport
engine = create_engine('sqlite:///money.db')
demo = True # turns on demo transactions
mintacct = False # turns on mint account download
pd.options.mode.chained_assignment = None # turns off warning for chained indexing
def initialStartup():
importDatesTable()
importBankAccounts()
budgetimport()
categoryimport()
importStockTransactions()
stockPricesImport.getStockPrices()
stockPricesImport.stockbalances()
importBankTransactions()
fximport()
totalbalances()
NIFX()
def initialdataimport():
### run without stockprices
importStockTransactions()
stockPricesImport.stockbalances()
importBankTransactions()
fximport()
totalbalances()
NIFX()
def importBankAccounts():
if demo: ## only used to demo account to add dummy data. Is turned on above.
df = pd.read_csv('DemoData/BankAccounts.csv')
else:
df = pd.read_csv('CSVs/BankAccounts.csv')
df.to_sql('bankaccounts', engine, if_exists = 'replace', index=False)
def importStockTransactions():
if demo: ## only used to demo account to add dummy data. Is turned on above.
df = pd.read_csv('DemoData/StockTransactions.csv', parse_dates = ['transdate'])
else:
df = pd.read_csv('CSVs/StockTransactions.csv', parse_dates = ['transdate'])
df.to_sql('stocktransactions', engine, if_exists = 'replace', index = False)
def importBankTransactions():
### imports old transactions, Emma/Dan mint transactions, appends together and inserts into database
if demo: ## only used to demo account to add dummy data. Is turned on above.
df = pd.read_csv('DemoData/demotransactions.csv', parse_dates = ['transdate'])
else:
df = pd.read_csv('CSVs/oldtransactions.csv', parse_dates = ['transdate'])
df_accrual = pd.read_csv('CSVs/accrual.csv', parse_dates = ['transdate'])
df = df.append(df_accrual)
df = df.append(mintImport())
df = df.append(stockPricesImport.stockincome())
df = df.sort('transdate')
df.to_sql('transactions', engine, if_exists = 'replace', index=False)
def mintImport():
import instance
mintAccounts = instance.mintaccounts()
if mintacct:
for key, accounts in mintAccounts.iteritems():
try:
mint = Mint(email = accounts[0], password = accounts[1])
mint.initiate_account_refresh()
df = mint.get_transactions()
df.to_csv('CSVs/' + accounts[2])
print accounts[0] + " accepted correctly."
except:
print accounts[0] + " was not accepted."
else:
print "Mint accounts intentionally not imported. Change 'mintacct' variable to 'True'."
df = pd.DataFrame()
columns = ['id','transdate','description','originaldescription','amount','debitcredit','category','accountname','labels','notes']
for key, accounts in mintAccounts.iteritems():
df2 = pd.read_csv('CSVs/' + accounts[2], parse_dates = ['Date'])
df2.columns = columns
if df.empty:
df = df2
else:
df = df.append(df2)
df.drop('id',axis=1,inplace=True)
df.loc[df['debitcredit'] == 'debit', ['amount']] *= -1 # reverses sign for 'debit' transactions
df.reset_index(level=0, inplace=True)
df.columns = ['id','transdate','description','originaldescription','amount','debitcredit','category','accountname','labels','notes']
df = df[['id','transdate','description','amount','category','accountname']]
return df
def importDatesTable():
### creates table of dates for all dates from date specified until today + 400 days
from helperfunctions import table_of_dates
tableofdates = table_of_dates(2006,1,1,'D')
tableofdates.reset_index(inplace=True)
tableofdates.to_sql('datestable', engine, if_exists = 'replace', index=False)
def fximport():
if not demo:
FXImport.fximport()
df = pd.read_csv('Common/FX rates.csv', parse_dates = ['FXDate'])
df.to_sql('fxrates', engine, if_exists = 'replace')
def budgetimport():
if demo: ## only used to demo account to add dummy data. Is turned on above.
df = pd.read_csv('DemoData/budget.csv')
else:
df = pd.read_csv('CSVs/budget.csv')
df.to_sql('budget', engine, if_exists = 'replace')
def categoryimport():
df = pd.read_csv('Common/categories.csv')
df.to_sql('categories', engine, if_exists = 'replace')
def totalbalances():
### inserts daily balance data for all accounts to database
from datetime import datetime
a = sqlqueries.sqltotalbalances() ### bankaccounts, transactions, dates, fxrates
df = pd.read_sql(a, engine, parse_dates='transdate')
df['amount'] = df['amount'].fillna(0)
df['balance'] = np.cumsum(df.groupby(['AccountName'])['amount']) # adds column of running total balances
df = df[df['balance'] != 0 ] # removes zero balances which should be balances before account started
df = df.sort('transdate')
df = df[df['transdate'] <= datetime.today()] # removes any future dates
df['USDAmount'] = df.apply(lambda row: convert(row['balance'],row['Currency'],row['Rate']), axis=1)
df['CADAmount'] = df.USDAmount * df.Rate
df.balance = df.balance.round(2)
df.USDAmount = df.USDAmount.round(2)
df.CADAmount = df.CADAmount.round(2)
df.to_sql('balances', engine, if_exists = 'replace', index=False)
def NIFX():
FXquery = sqlqueries.FXquery()
df = pd.read_sql(FXquery, engine, parse_dates='transdate')
df = findFX(df)
spendingQuery = sqlqueries.spendingQuery()
df2 = pd.read_sql(spendingQuery, engine, parse_dates='Date')
df = df.append(df2).sort('Date')
df['USD Amount'] = np.round(df['USD Amount'],decimals=2)
df['CAD Amount'] = np.round(df['CAD Amount'],decimals=2)
df['Date'] = pd.DatetimeIndex(df['Date']) + pd.offsets.MonthEnd(0)
df = pd.pivot_table(df, index=['Date','Owner'],values=["USD Amount","CAD Amount"],columns=['Category'],fill_value=0).reset_index()
df.columns = df.columns.droplevel()
df.columns = ['Date','Owner','USD FX Gain/Loss','USD Investments','USD Income','CAD FX Gain/Loss','CAD Investments','CAD Income']
df.to_sql('googlechartsmonthlynetincome', engine, if_exists = 'replace', index=False)
def findFX(df):
df[['nativebalance','USbalance','CAbalance']] = np.cumsum(df.groupby(['Owner','Currency'])[['Native Amount','USD Amount','CAD Amount']])
### total of (all transactions in native currency multiplied by transaction date rate)
df['USDbalance'] = df.apply(lambda row: convert(row['nativebalance'], row['Currency'], row['Rate']), axis=1)
df['CADbalance'] = df['USDbalance'] * df['Rate']
## total of all transactions in native currency converted at ending rate
df['USFX'] = df.USDbalance - df.USbalance
df['CADFX'] = df.CADbalance - df.CAbalance
df = df[['transdate','Owner','Currency','USFX','CADFX']]
df['transdate'] = pd.DatetimeIndex(df['transdate'])
df['PrevDate'] = pd.DatetimeIndex(df['transdate']) + pd.offsets.MonthEnd(-1)
df.iloc[0:4,3:5] = 0.0 ### change first three balances to zero. Needed for pad filling step below.
df = df.sort(['Owner','Currency','transdate','PrevDate']).fillna(method='pad')
df = pd.merge(df, df, how='left', left_on=['PrevDate','Owner','Currency'], right_on=['transdate','Owner','Currency'])
df['FXUSD'] = df.USFX_x - df.USFX_y
df['FXCAD'] = df.CADFX_x - df.CADFX_y
df = df[['transdate_x','Owner','Currency','FXUSD','FXCAD']]
df = df.sort(['Owner','Currency','transdate_x']).fillna(method='pad')
df['Category'] = "FX Gain/Loss"
df.columns = ['Date','Owner','Currency','USD Amount','CAD Amount','Category']
df = df.groupby(['Date','Owner','Category'])['USD Amount','CAD Amount'].sum().reset_index()
return df