File size: 2,140 Bytes
cec6d9e |
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 |
# 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() |