コード例 #1
0
    def get_ads_insight(self, account_id, report_date):
        """
        Pull insights from the Insight edge and return an array of
        insight report

        Params:

        * `account_id` is your Facebook AdAccount id
        * `report_date` is the date for the insight report

        For more information see the [Ads Insights doc](
        https://developers.facebook.com/docs/marketing-api/insights-api)
        """
        ad_account = AdAccount(fbid=account_id)
        limit = 10
        fields = [
            'campaign_name', 'adset_name', 'adset_id', 'impressions',
            'website_clicks', 'app_store_clicks', 'deeplink_clicks', 'spend',
            'reach', 'actions', 'action_values'
        ]
        params = {
            'time_range': {
                'since': report_date,
                'until': report_date
            },
            'action_attribution_windows': ['28d_click'],
            'breakdowns': ['impression_device', 'placement'],
            'level': 'adset',
            'limit': limit if limit > 0 else None
        }

        insights = ad_account.get_insights(fields, params)
        insights_value = self.get_insights_value(insights, report_date, limit)

        return insights_value
コード例 #2
0
def export_report_facebook(config):
    #pull report thru facebook api
    # Get insights stats for this account id
    account_id = config[0]
    param = config[1]
    count = config[-1]
    account = AdAccount(account_id)
    async_job = account.get_insights(params=param, async=True)
    async_job.remote_read()
    while async_job[AdReportRun.Field.async_percent_completion] < 100:
        time.sleep(20)
        print(AdReportRun.Field.async_percent_completion)
        async_job.remote_read()
        #print(async_job)
    #read file in bulk
    #pd.read_csv("""https://www.facebook.com/ads/ads_insights/export_report/?report_run_id=%s"""%async_job['report_run_id']+"&name=myreport&format=csv&access_token=" + my_access_token,chunksize=10**5)
    download_address = """https://www.facebook.com/ads/ads_insights/export_report/?report_run_id=%s""" % async_job[
        'report_run_id'] + "&format=csv&access_token=" + my_access_token
    chunksize = 10**5
    downloadpath = path + "\\raw_data\\" + subdirectory
    for chunk in pd.read_csv(download_address, chunksize=chunksize):
        chunk.ix[chunk["Placement"] == 'Instagram Feed on Mobile Devices',
                 "Placement"] = 'Instagram'
        chunk.ix[chunk["Placement"] != 'Instagram', "Placement"] = 'Facebook'
        chunk = chunk[[
            'Reporting Starts', 'Reporting Ends', "Placement", 'Campaign Name',
            'Ad Name', 'Ad Set Name', 'Clicks (All)', 'Impressions',
            'Amount Spent (USD)', "Website Purchases"
        ]]
        chunk.to_csv(downloadpath + "\\facebook_%s.csv" % (count), index=False)
コード例 #3
0
 def get_ads_insight(
     self,
     account_id,
 ):
     """
     Pull insights from the Insight edge and return an array of
     insight report
     Params:
     * `account_id` is fb AdAccount id
     """
     ad_account = AdAccount(fbid = account_id)
     insights = ad_account.get_insights()
     return insights
コード例 #4
0
def get_account_ad_performance_for_single_day(
        ad_account: AdAccount, single_date: datetime) -> Insights:
    """Downloads the ad performance for an ad account for a given day
    https://developers.facebook.com/docs/marketing-api/insights

    Args:
        ad_account: An ad account to download.
        single_date: A single date as a datetime object

    Returns:
        A list containing dictionaries with the ad performance from the report

    """
    logging.info(
        'download Facebook ad performance of act_{ad_account_id} on {single_date}'
        .format(ad_account_id=ad_account['account_id'],
                single_date=single_date.strftime('%Y-%m-%d')))

    ad_insights = ad_account.get_insights(
        # https://developers.facebook.com/docs/marketing-api/insights/fields
        fields=[
            'date_start', 'ad_id', 'impressions', 'actions', 'spend',
            'action_values'
        ],
        # https://developers.facebook.com/docs/marketing-api/insights/parameters
        params={
            'action_attribution_windows': ['28d_click'],
            # https://developers.facebook.com/docs/marketing-api/insights/action-breakdowns
            'action_breakdowns': ['action_type'],
            # https://developers.facebook.com/docs/marketing-api/insights/breakdowns
            'breakdowns': ['impression_device', 'placement'],
            'level': 'ad',
            'limit': 1000,
            'time_range': {
                'since': single_date.strftime('%Y-%m-%d'),
                'until': single_date.strftime('%Y-%m-%d')
            }
        })

    return ad_insights
コード例 #5
0
from facebookads.objects import AdAccount, AsyncJob
from facebookads.api import FacebookAdsApi
import time
import os
import json

this_dir = os.path.dirname(__file__)
config_filename = os.path.join(this_dir, 'config.json')
config_file = open(config_filename)
config = json.load(config_file)
config_file.close()

api = FacebookAdsApi.init(access_token=config['access_token'])
account_id = config['act_id']

account = AdAccount(account_id)

# Both Insights and Reportstats
i_async_job = account.get_insights(params={'level': 'ad'}, async=True)

# Insights
while True:
    job = i_async_job.remote_read()
    print("Percent done: " + str(job[AsyncJob.Field.async_percent_completion]))
    time.sleep(1)
    if job:
        # print "Done!"
        break

print(i_async_job.get_result())
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

from facebookads import test_config

ad_account_id = test_config.account_id

# _DOC open [ADACCOUNT_GET_INSIGHTS_FILTERING_BREAKDOWN]
# _DOC vars [ad_account_id:s]
from facebookads.objects import AdAccount, Insights

ad_account = AdAccount(ad_account_id)
params = {
    'breakdowns': [
        Insights.Breakdown.age,
        Insights.Breakdown.gender
    ],
    'filtering': [{
        'field': 'campaign.name',
        'operator': 'CONTAIN',
        'value': '18-25'
    }]
}

stats = ad_account.get_insights(params=params)
print(stats)
# _DOC close [ADACCOUNT_GET_INSIGHTS_FILTERING_BREAKDOWN]
コード例 #7
0
ファイル: get_ad_insight.py プロジェクト: odidere/insights

########################## function ends ##########################

########################## main ##########################
# get all ad campaign from an ad account
con = mdb.connect(db_host, db_username, db_password, db_name)
with con:
    deleteAdSetsInsight(con, report_date)
    for my_ad_account_id in my_ad_account_ids:
        ad_account = AdAccount(my_ad_account_id)
        fields = [
            'campaign_group_name', 'campaign_name', 'campaign_id',
            'impressions', 'clicks', 'spend', 'reach', 'actions',
            'action_values'
        ]
        params = {
            'time_range': {
                'since': report_date,
                'until': report_date
            },
            'action_attribution_windows': ['28d_click'],
            'breakdowns': ['impression_device', 'placement'],
            'level': 'campaign',
            'limit': 100000
        }
        ad_insights = ad_account.get_insights(fields, params)

        for ad_insight in ad_insights:
            writeAdInsight(ad_insight, con, report_date)
コード例 #8
0
account = AdAccount(ad_account_id)

params = {
    'action_breakdowns':
    Insights.ActionBreakdown.action_video_type,
    'date_preset':
    Insights.Preset.last_30_days,
    'fields': [
        Insights.Field.actions,
        Insights.Field.video_avg_pct_watched_actions,
        Insights.Field.video_complete_watched_actions,
    ],
}

stats = account.get_insights(params=params)
print(stats)
# _DOC close [ADACCOUNT_GET_INSIGHTS_VIDEO_VIEWS]

# _DOC open [ADACCOUNT_GET_INSIGHTS_CAROUSEL_BREAKDOWNS]
# _DOC vars [ad_account_id:s]
from facebookads.objects import AdAccount, Insights

account = AdAccount(ad_account_id)

params = {
    'action_breakdowns': [
        Insights.ActionBreakdown.action_type,
        Insights.ActionBreakdown.action_carousel_card_id,
    ],
    'fields': [
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

from facebookads import test_config

ad_account_id = test_config.account_id

# _DOC open [ADACCOUNT_GET_INSIGHTS_DYNAMIC_PRODUCT_ADS]
# _DOC vars [ad_account_id:s]
from facebookads.objects import AdAccount, Insights

account = AdAccount(ad_account_id)

fields = [
    Insights.Field.account_name,
    Insights.Field.impressions,
    Insights.Field.actions,
    Insights.Field.product_id,
]

params = {
    'date_preset': 'last_week',
    'actions_group_by': ['action_type'],
}

stats = account.get_insights(fields=fields, params=params)
# _DOC close [ADACCOUNT_GET_INSIGHTS_DYNAMIC_PRODUCT_ADS]
コード例 #10
0
ファイル: get_ad_insight.py プロジェクト: arunsingh/insights
con = mdb.connect(db_host, db_username, db_password, db_name)
with con:
    deleteAdSetsInsight(con, report_date)
    for my_ad_account_id in my_ad_account_ids:
        ad_account = AdAccount(my_ad_account_id)
        fields = [
            'campaign_group_name',
            'campaign_name',
            'campaign_id',
            'impressions',
            'clicks',
            'spend',
            'reach',
            'actions',
            'action_values'
        ]
        params = {
            'time_range': {
                'since': report_date,
                'until': report_date
            },
            'action_attribution_windows': ['28d_click'],
            'breakdowns': ['impression_device', 'placement'],
            'level': 'campaign',
            'limit': 100000
        }
        ad_insights = ad_account.get_insights(fields, params)

        for ad_insight in ad_insights:
            writeAdInsight(ad_insight, con, report_date)
コード例 #11
0
account = AdAccount("act_596901567069013")
print account

### Get DataFrames
import numpy as np
import pandas as pd

since = raw_input("Since YYYY-MM-DD:  ")
until = raw_input("Until YYYY-MM-DD:  ")

##1. insights dataframe (key: adgroup_id)
fields = ["adgroup_id", "campaign_name", "impressions", "clicks", "spend"]
params = {"level": "adgroup", "time_range": {"since": since, "until": until}, "time_increment": 1}

# get iterator
insights = account.get_insights(params=params, fields=fields)  # class 'facebookads.objects.EdgeIterator'
# into list
insights_list = list(insights)
# into DataFrame
insights_df = pd.DataFrame(insights_list)
# save as csv
insights_df.to_csv(until + "insights.csv", index=False, encoding="utf-8")


##2. creatives dataframe (key: creative_id)
c_fields = ["creative", "adgroup_id", "campaign_name"]

c_params = {"time_range": {"since": since, "until": until}, "time_increment": 1}

creatives = account.get_ad_groups(fields=c_fields, params=c_params)
# into list