Fred808 commited on
Commit
cec6d9e
·
verified ·
1 Parent(s): 462fc46

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -0
app.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ import pandas as pd
3
+ from xgboost import XGBRegressor
4
+ from sklearn.model_selection import train_test_split
5
+ import requests
6
+ import os
7
+
8
+ # Fetch data from Facebook API
9
+ def fetch_data_from_api(query, geo_locations):
10
+ url = f"https://graph.facebook.com/v17.0/act_597540533213624/targetingsearch"
11
+ params = {
12
+ "q": query,
13
+ "geo_locations[countries]": geo_locations,
14
+ "access_token": os.getenv('ACCESS_TOKEN')
15
+ }
16
+ response = requests.get(url, params=params)
17
+ if response.status_code == 200:
18
+ return response.json()
19
+ else:
20
+ raise Exception(f"Failed to fetch data from API. Status code: {response.status_code}")
21
+
22
+ # Generate synthetic metrics
23
+ def generate_synthetic_metrics(data):
24
+ IMPRESSION_RATE = 0.10 # 10% of audience sees the ad
25
+ CTR = 0.05 # 5% of impressions result in clicks
26
+ CONVERSION_RATE = 0.02 # 2% of clicks result in conversions
27
+ CPM = 5 # $5 per 1000 impressions
28
+ REVENUE_PER_CONVERSION = 50 # $50 per conversion
29
+
30
+ data['impressions'] = data['audience_size_lower_bound'] * IMPRESSION_RATE
31
+ data['clicks'] = data['impressions'] * CTR
32
+ data['conversions'] = data['clicks'] * CONVERSION_RATE
33
+ data['ad_spend'] = (data['impressions'] / 1000) * CPM
34
+ data['revenue'] = data['conversions'] * REVENUE_PER_CONVERSION
35
+ data['roi'] = (data['revenue'] - data['ad_spend']) / data['ad_spend']
36
+
37
+ return data
38
+
39
+ # Train and save the model
40
+ def train_and_save_model():
41
+ # Fetch data
42
+ response_data = fetch_data_from_api('Fitness', 'NG')
43
+ data = pd.DataFrame(response_data['data'])
44
+
45
+ # Generate synthetic metrics
46
+ data = generate_synthetic_metrics(data)
47
+
48
+ # Features and target
49
+ X = data[['ad_spend', 'impressions', 'clicks', 'conversions']]
50
+ y = data['roi']
51
+
52
+ # Train the model
53
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
54
+ model = XGBRegressor(n_estimators=100, max_depth=3, n_jobs=-1)
55
+ model.fit(X_train, y_train)
56
+
57
+ # Save the model
58
+ model.save_model('model.json')
59
+ print("Model saved to 'model.json'.")
60
+
61
+ if __name__ == '__main__':
62
+ train_and_save_model()