import facebook
import pandas as pd
# Set up Facebook Ads API connection
access_token = 'your_access_token'
ad_account_id = 'your_ad_account_id'
graph = facebook.GraphAPI(access_token=access_token)
campaign_id = 'your_campaign_id'
adset_id = 'your_adset_id'
# Create a new ad
ad = graph.create_ad(
ad_account_id=ad_account_id,
name='New Ad',
adset_id=adset_id,
creative={
'object_story_spec': {
'page_id': 'your_page_id',
'link_data': {
'call_to_action': {
'type': 'INSTALL_MOBILE_APP',
'value': {
'link': 'your_app_download_url'
}
},
'image_hash': 'your_image_hash',
'message': 'your_message'
}
}
}
)
# Target specific audiences
audiences = ['audience_1', 'audience_2', 'audience_3']
for audience in audiences:
graph.create_custom_audience(
ad_account_id=ad_account_id,
name=audience,
description='Target audience for CPA campaign',
subtype='CUSTOM',
customer_file_source='USER_PROVIDED_ONLY',
data=[{
'schema': 'EMAIL_SHA256',
'data': pd.read_csv(f'{audience}.csv').apply(lambda x: x['email'].encode('utf-8')).apply(lambda x: hashlib.sha256(x).hexdigest()).tolist()
}]
)
# Track performance of the campaign
insights = graph.get_connections(
id=f'act_{ad_account_id}',
connection_name='insights',
fields='account_id, impressions, spend, clicks, actions'
)
# Generate reports
report_data = []
for insight in insights['data']:
report_data.append({
'account_id': insight['account_id'],
'impressions': insight['impressions'],
'spend': insight['spend'],
'clicks': insight['clicks'],
'actions': insight['actions']
})
report = pd.DataFrame(report_data)
# Analyze the data collected from the campaign
total_spend = report['spend'].sum()
total_actions = report['actions'].sum()
cpa = total_spend / total_actions
print(f'Total spend: ${total_spend}')
print(f'Total actions: {total_actions}')
print(f'CPA: ${cpa}')