|
|
|
import pandas as pd |
|
from xgboost import XGBRegressor |
|
from sklearn.model_selection import train_test_split |
|
import requests |
|
import os |
|
|
|
|
|
def fetch_data_from_api(query, geo_locations): |
|
url = f"https://graph.facebook.com/v17.0/act_597540533213624/targetingsearch" |
|
params = { |
|
"q": query, |
|
"geo_locations[countries]": geo_locations, |
|
"access_token": os.getenv('ACCESS_TOKEN') |
|
} |
|
response = requests.get(url, params=params) |
|
if response.status_code == 200: |
|
return response.json() |
|
else: |
|
raise Exception(f"Failed to fetch data from API. Status code: {response.status_code}") |
|
|
|
|
|
def generate_synthetic_metrics(data): |
|
IMPRESSION_RATE = 0.10 |
|
CTR = 0.05 |
|
CONVERSION_RATE = 0.02 |
|
CPM = 5 |
|
REVENUE_PER_CONVERSION = 50 |
|
|
|
data['impressions'] = data['audience_size_lower_bound'] * IMPRESSION_RATE |
|
data['clicks'] = data['impressions'] * CTR |
|
data['conversions'] = data['clicks'] * CONVERSION_RATE |
|
data['ad_spend'] = (data['impressions'] / 1000) * CPM |
|
data['revenue'] = data['conversions'] * REVENUE_PER_CONVERSION |
|
data['roi'] = (data['revenue'] - data['ad_spend']) / data['ad_spend'] |
|
|
|
return data |
|
|
|
|
|
def train_and_save_model(): |
|
|
|
response_data = fetch_data_from_api('Fitness', 'NG') |
|
data = pd.DataFrame(response_data['data']) |
|
|
|
|
|
data = generate_synthetic_metrics(data) |
|
|
|
|
|
X = data[['ad_spend', 'impressions', 'clicks', 'conversions']] |
|
y = data['roi'] |
|
|
|
|
|
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) |
|
model = XGBRegressor(n_estimators=100, max_depth=3, n_jobs=-1) |
|
model.fit(X_train, y_train) |
|
|
|
|
|
model.save_model('model.json') |
|
print("Model saved to 'model.json'.") |
|
|
|
if __name__ == '__main__': |
|
train_and_save_model() |