yoursdvniel commited on
Commit
c33867e
·
verified ·
1 Parent(s): 14b6a24

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +23 -4
main.py CHANGED
@@ -116,15 +116,17 @@ def predict_metric():
116
 
117
  for doc in income_query:
118
  transaction = doc.to_dict()
119
- date_str = transaction["date"]
120
  amount = transaction["amountDue"]
121
  income_data[date_str] = income_data.get(date_str, 0) + amount
 
122
 
123
  for doc in expense_query:
124
  transaction = doc.to_dict()
125
- date_str = transaction["date"]
126
  amount = transaction["amountDue"]
127
  expense_data[date_str] = expense_data.get(date_str, 0) + amount
 
128
 
129
  # Calculate net profit for each date
130
  for date, income in income_data.items():
@@ -138,8 +140,9 @@ def predict_metric():
138
  engagement_data = {}
139
  for doc in income_query:
140
  transaction = doc.to_dict()
141
- date_str = transaction["date"]
142
  engagement_data[date_str] = engagement_data.get(date_str, 0) + 1
 
143
 
144
  for date, count in engagement_data.items():
145
  data.append({"date": date, "amountDue": count})
@@ -147,20 +150,33 @@ def predict_metric():
147
  # Create DataFrame from the aggregated data
148
  df = pd.DataFrame(data)
149
 
 
 
 
150
  # Ensure 'date' column is datetime
151
- df['date'] = pd.to_datetime(df['date'])
152
  df['date'] = df['date'].dt.tz_localize(None)
153
 
 
 
 
 
 
 
154
  # Set 'date' as index
155
  df = df.sort_values("date").set_index("date")
156
 
157
  # Resample daily to ensure regular intervals (fill missing dates)
158
  df = df.resample("D").sum().reset_index()
159
 
 
 
 
160
  df.columns = ["ds", "y"] # ds: date, y: target
161
 
162
  # Check if there's enough data to train the model
163
  if df.shape[0] < 10:
 
164
  return jsonify({"error": "Not enough data for prediction"})
165
 
166
  # Initialize and fit the Prophet model
@@ -175,6 +191,9 @@ def predict_metric():
175
  forecast_data = forecast[['ds', 'yhat']].tail(interval)
176
  predictions = [{"date": row['ds'].strftime('%Y-%m-%d'), "value": row['yhat']} for _, row in forecast_data.iterrows()]
177
 
 
 
 
178
  # Return predictions in JSON format
179
  return jsonify({"predictedData": predictions})
180
 
 
116
 
117
  for doc in income_query:
118
  transaction = doc.to_dict()
119
+ date_str = transaction["date"].toDate() # Convert Firestore Timestamp to DateTime
120
  amount = transaction["amountDue"]
121
  income_data[date_str] = income_data.get(date_str, 0) + amount
122
+ print(f"Income transaction - Date: {date_str}, Amount: {amount}")
123
 
124
  for doc in expense_query:
125
  transaction = doc.to_dict()
126
+ date_str = transaction["date"].toDate() # Convert Firestore Timestamp to DateTime
127
  amount = transaction["amountDue"]
128
  expense_data[date_str] = expense_data.get(date_str, 0) + amount
129
+ print(f"Expense transaction - Date: {date_str}, Amount: {amount}")
130
 
131
  # Calculate net profit for each date
132
  for date, income in income_data.items():
 
140
  engagement_data = {}
141
  for doc in income_query:
142
  transaction = doc.to_dict()
143
+ date_str = transaction["date"].toDate() # Convert Firestore Timestamp to DateTime
144
  engagement_data[date_str] = engagement_data.get(date_str, 0) + 1
145
+ print(f"Engagement transaction - Date: {date_str}")
146
 
147
  for date, count in engagement_data.items():
148
  data.append({"date": date, "amountDue": count})
 
150
  # Create DataFrame from the aggregated data
151
  df = pd.DataFrame(data)
152
 
153
+ # Log the DataFrame before further processing
154
+ print("Data before processing:", df)
155
+
156
  # Ensure 'date' column is datetime
157
+ df['date'] = pd.to_datetime(df['date'], errors='coerce')
158
  df['date'] = df['date'].dt.tz_localize(None)
159
 
160
+ # Log DataFrame after date conversion
161
+ print("Data after date conversion:", df)
162
+
163
+ # Drop rows where 'date' could not be parsed
164
+ df = df.dropna(subset=['date'])
165
+
166
  # Set 'date' as index
167
  df = df.sort_values("date").set_index("date")
168
 
169
  # Resample daily to ensure regular intervals (fill missing dates)
170
  df = df.resample("D").sum().reset_index()
171
 
172
+ # Log DataFrame after resampling
173
+ print("Data after resampling:", df)
174
+
175
  df.columns = ["ds", "y"] # ds: date, y: target
176
 
177
  # Check if there's enough data to train the model
178
  if df.shape[0] < 10:
179
+ print("Not enough data for prediction")
180
  return jsonify({"error": "Not enough data for prediction"})
181
 
182
  # Initialize and fit the Prophet model
 
191
  forecast_data = forecast[['ds', 'yhat']].tail(interval)
192
  predictions = [{"date": row['ds'].strftime('%Y-%m-%d'), "value": row['yhat']} for _, row in forecast_data.iterrows()]
193
 
194
+ # Log the predictions before returning
195
+ print("Predictions:", predictions)
196
+
197
  # Return predictions in JSON format
198
  return jsonify({"predictedData": predictions})
199