# app.py import pandas as pd from xgboost import XGBRegressor from sklearn.model_selection import train_test_split import requests import os # Fetch data from Facebook API 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}") # Generate synthetic metrics def generate_synthetic_metrics(data): IMPRESSION_RATE = 0.10 # 10% of audience sees the ad CTR = 0.05 # 5% of impressions result in clicks CONVERSION_RATE = 0.02 # 2% of clicks result in conversions CPM = 5 # $5 per 1000 impressions REVENUE_PER_CONVERSION = 50 # $50 per conversion 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 # Train and save the model def train_and_save_model(): # Fetch data response_data = fetch_data_from_api('Fitness', 'NG') data = pd.DataFrame(response_data['data']) # Generate synthetic metrics data = generate_synthetic_metrics(data) # Features and target X = data[['ad_spend', 'impressions', 'clicks', 'conversions']] y = data['roi'] # Train the model 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) # Save the model model.save_model('model.json') print("Model saved to 'model.json'.") if __name__ == '__main__': train_and_save_model()