示例#1
0
    def stats(self):
        if not self.cached_stats:
            sitc_swaps = {"eublx":"eubel"}
            if self.attr.id in sitc_swaps:
                attr = attrs.Country.query.get(sitc_swaps[self.attr.id])
            else:
                attr = self.attr
            start_year = earliest_data.get(attr.id, 1980)
            if self.attr.id == "xxwld":
                all_stats = [("export_val", _('Exports')), ("population", _('Population')), ("gdp", _('GDP')), ("gdp_pc_current_ppp", _('GDP Per Capita'))]
            else:
                all_stats = [("eci", _('Econ Complexity')), ("export_val", _('Exports')), ("import_val", _('Imports')), ("gdp_pc_current_ppp", _('GDP Per Capita'))]
            for s, s_title in all_stats:
                if "val" in s:
                    if self.attr.id == "xxwld":
                        yo_historic = db.session.query(func.sum(self.models.Yo.export_val)).group_by(self.models.Yo.year).filter(self.models.Yo.year >= start_year).all()
                        this_yo = {s: db.session.query(func.sum(self.models.Yo.export_val)).filter_by(year = self.year).first()}
                        # raise Exception(yo_historic)
                    else:
                        yo_historic = db_data.sitc_models.Yo.query.filter_by(country=attr).filter(db_data.sitc_models.Yo.year >= start_year).all()
                        # raise Exception([x.export_val for x in yo_historic])
                        yo_base_q = self.models.Yo.query.filter_by(year=self.year)
                        this_yo = yo_base_q.filter_by(country=attr).first()
                else:
                    start_year = max(1990, start_year) if "gdp" in s else start_year
                    yo_historic = attrs.Yo.query.filter_by(country=attr).filter(attrs.Yo.year >= start_year).all()
                    # raise Exception([x.population for x in yo_historic])
                    yo_base_q = attrs.Yo.query.filter_by(year=self.year)
                    this_yo = yo_base_q.filter_by(country=attr).first()

                if isinstance(this_yo, dict):
                    val = this_yo[s][0]
                    sparkline = [float(yh[0]) if yh[0] is not None else 0 for yh in yo_historic]
                else:
                    val = getattr(this_yo, s, None)
                    sparkline = [float(getattr(yh, s)) if getattr(yh, s) is not None else 0 for yh in yo_historic]

                if val:
                    my_stat = {"key":s, "title":s_title, \
                                "val":val, "sparkline":{
                                    "start": start_year, \
                                    "end": available_years["country"][-1], \
                                    "val": sparkline
                                }
                              }
                    if self.attr.id != "xxwld":
                        res = yo_base_q.order_by(desc(s)).all()
                        my_stat["rank"] = res.index(this_yo)+1
                        my_stat["total"] = 126 if s == "eci" else len(res)

                    self.cached_stats.append(my_stat)
        return self.cached_stats
示例#2
0
文件: models.py 项目: EricPutland/oec
    def stats(self):
        if not self.cached_stats:
            sitc_swaps = {"eublx":"eubel"}
            if self.attr.id in sitc_swaps:
                attr = attrs.Country.query.get(sitc_swaps[self.attr.id])
            else:
                attr = self.attr
            start_year = earliest_data.get(attr.id, 1980)
            if self.attr.id == "xxwld":
                all_stats = [("export_val", _('Exports')), ("population", _('Population')), ("gdp", _('GDP')), ("gdp_pc_current_ppp", _('GDP Per Capita'))]
            else:
                all_stats = [("eci", _('Econ Complexity')), ("export_val", _('Exports')), ("import_val", _('Imports')), ("gdp_pc_current_ppp", _('GDP Per Capita'))]
            for s, s_title in all_stats:
                if "val" in s:
                    if self.attr.id == "xxwld":
                        yo_historic = db.session.query(func.sum(self.models.Yo.export_val)).group_by(self.models.Yo.year).filter(self.models.Yo.year >= start_year).all()
                        this_yo = {s: db.session.query(func.sum(self.models.Yo.export_val)).filter_by(year = self.year).first()}
                        # raise Exception(yo_historic)
                    else:
                        yo_historic = db_data.sitc_models.Yo.query.filter_by(country=attr).filter(db_data.sitc_models.Yo.year >= start_year).all()
                        # raise Exception([x.export_val for x in yo_historic])
                        yo_base_q = self.models.Yo.query.filter_by(year=self.year)
                        this_yo = yo_base_q.filter_by(country=attr).first()
                else:
                    start_year = max(1990, start_year) if "gdp" in s else start_year
                    yo_historic = attrs.Yo.query.filter_by(country=attr).filter(attrs.Yo.year >= start_year).all()
                    # raise Exception([x.population for x in yo_historic])
                    yo_base_q = attrs.Yo.query.filter_by(year=self.year)
                    this_yo = yo_base_q.filter_by(country=attr).first()

                if isinstance(this_yo, dict):
                    val = this_yo[s][0]
                    sparkline = [float(yh[0]) if yh[0] is not None else 0 for yh in yo_historic]
                else:
                    val = getattr(this_yo, s, None)
                    sparkline = [float(getattr(yh, s)) if getattr(yh, s) is not None else 0 for yh in yo_historic]

                if val:
                    my_stat = {"key":s, "title":s_title, \
                                "val":val, "sparkline":{
                                    "start": start_year, "end": available_years["sitc"][-1], \
                                    "val": sparkline
                                }
                              }
                    if self.attr.id != "xxwld":
                        res = yo_base_q.order_by(desc(s)).all()
                        my_stat["rank"] = res.index(this_yo)+1
                        my_stat["total"] = len(res)

                    self.cached_stats.append(my_stat)
        return self.cached_stats
示例#3
0
    def stats(self):
        if not self.cached_stats:
            sitc_swaps = {"eublx": "eubel"}
            if self.attr.id in sitc_swaps:
                attr = attrs.Country.query.get(sitc_swaps[self.attr.id])
            else:
                attr = self.attr
            start_year = earliest_data.get(attr.id, 1980)
            all_stats = [("eci", _('Econ Complexity')),
                         ("export_val", _('Exports')),
                         ("import_val", _('Imports')),
                         ("gdp_pc_current_ppp", _('GDP Per Capita'))]
            for s, s_title in all_stats:
                if "val" in s:
                    yo_historic = db_data.sitc_models.Yo.query.filter_by(
                        country=attr).filter(
                            db_data.sitc_models.Yo.year >= start_year).all()
                    # raise Exception([x.export_val for x in yo_historic])
                    yo_base_q = self.models.Yo.query.filter_by(year=self.year)
                    this_yo = yo_base_q.filter_by(country=attr).first()
                else:
                    start_year = max(1990,
                                     start_year) if "gdp" in s else start_year
                    yo_historic = attrs.Yo.query.filter_by(
                        country=attr).filter(
                            attrs.Yo.year >= start_year).all()
                    # raise Exception([x.population for x in yo_historic])
                    yo_base_q = attrs.Yo.query.filter_by(year=self.year)
                    this_yo = yo_base_q.filter_by(country=attr).first()

                res = yo_base_q.order_by(desc(s)).all()
                val = getattr(this_yo, s, None)
                if val:
                    my_stat = {"key":s, "rank":res.index(this_yo)+1, "total":len(res), "title":s_title, \
                                "val":val, "sparkline":{
                                    "start": start_year, "end": available_years["sitc"][-1], \
                                    "val": [float(getattr(yh, s)) if getattr(yh, s) is not None else 0 for yh in yo_historic]
                                }
                              }
                    self.cached_stats.append(my_stat)
        return self.cached_stats
示例#4
0
文件: models.py 项目: ablascoa/oec
    def sections(self):
        sections = []
        ''' Trade Section
        '''

        if self.attr.id == "xxwld":

            export_tmap = Build("tree_map", "hs92", "export", self.attr, "all",
                                "show", self.year)
            this_yo = self.models.Yo.query.filter_by(year=self.year).all()

            export_val = sum([o.export_val for o in this_yo])
            export_subtitle = _(
                u"The total world trade in %(year)s was %(export_val)s.",
                year=self.year,
                export_val=num_format(export_val, "export_val"))
            export_subtitle += u" "

            past_yr = self.year - 5
            past_yo = self.models.Yo.query.filter_by(year=past_yr).all()
            growth_val = median([o.export_val_growth_pct_5 for o in this_yo])
            chg = "increased" if growth_val >= 0 else "decreased"
            export_subtitle += _(u"During the last five years exports have %(increased_decreased)s at a median annualized rate of %(change_rate)s%%, from $%(past_export_val)s in %(past_year)s to $%(current_export_val)s in %(current_year)s.",
                                    increased_decreased=chg, change_rate=num_format(growth_val*100), \
                                    past_export_val=num_format(sum([o.export_val for o in past_yo])), past_year=past_yr, current_export_val=num_format(export_val), current_year=self.year)
            export_subtitle += u" "

            top_exports = self.models.Yp.query.filter_by(
                year=self.year,
                hs92_id_len=6).order_by(desc("export_val")).limit(2).all()
            export_subtitle += _(u"The most recent exports are led by %(top_export)s which represent %(top_export_pct)s%% of the total products exported, followed by %(second_export)s, which account for %(second_export_pct)s%%.",
                                    top_export=top_exports[0].product.get_profile_link(), top_export_pct=num_format((top_exports[0].export_val/export_val)*100), \
                                    second_export=top_exports[1].product.get_profile_link(), second_export_pct=num_format((top_exports[1].export_val/export_val)*100))

            origins_tmap = Build("tree_map", "hs92", "import", self.attr,
                                 "show", "all", self.year)
            yo_exp = self.models.Yo.query.filter_by(year=self.year).order_by(
                desc("export_val")).limit(5).all()
            origin_list = self.stringify_items(yo_exp, "export_val", "country")
            origin_subtitle = _(u"The top exporters globally are %(origins)s.",
                                origins=origin_list)

            trade_section = {
                "builds": [
                    {
                        "title": _(u"Exports"),
                        "build": export_tmap,
                        "subtitle": export_subtitle
                    },
                    {
                        "title": _(u"Origins"),
                        "build": origins_tmap,
                        "subtitle": origin_subtitle
                    },
                ]
            }

        else:
            export_subtitle, import_subtitle, dest_subtitle, origin_subtitle = [
                None
            ] * 4

            export_tmap = Build("tree_map", "hs92", "export", self.attr, "all",
                                "show", self.year)
            import_tmap = Build("tree_map", "hs92", "import", self.attr, "all",
                                "show", self.year)

            yop_base = self.models.Yop.query.filter_by(year=self.year,
                                                       origin=self.attr,
                                                       hs92_id_len=6)
            # get growth
            past_yr = self.year - 5
            past_yo = self.models.Yo.query.filter_by(
                year=past_yr, country=self.attr).first()
            this_yo = self.models.Yo.query.filter_by(
                year=self.year, country=self.attr).first()
            exp_val_stat = filter(lambda s: s["key"] == "export_val",
                                  self.stats())
            if exp_val_stat and this_yo:
                exp_val_stat = exp_val_stat.pop()
                export_subtitle = ""
                if self.attr.id != "xxwld":
                    exp_rank = num_format(
                        exp_val_stat["rank"],
                        "ordinal") if exp_val_stat["rank"] > 1 else ""
                    export_subtitle += _(
                        u"In %(year)s %(country)s exported $%(export_val)s, making it the %(export_rank)s largest exporter in the world.",
                        year=self.year,
                        country=self.attr.get_name(article=True),
                        export_val=num_format(exp_val_stat["val"]),
                        export_rank=exp_rank)
                    export_subtitle += u" "
                if past_yo and this_yo.export_val_growth_pct_5:
                    chg = "increased" if this_yo.export_val_growth_pct_5 >= 0 else "decreased"
                    export_subtitle += _(u"During the last five years the exports %(of_country)s have %(increased_decreased)s at an annualized rate of %(change_rate)s%%, from $%(past_export_val)s in %(past_year)s to $%(current_export_val)s in %(current_year)s.",
                                            of_country=self.attr.get_name(article="of"), increased_decreased=chg, change_rate=num_format(this_yo.export_val_growth_pct_5*100), \
                                            past_export_val=num_format(past_yo.export_val), past_year=past_yr, current_export_val=num_format(this_yo.export_val), current_year=self.year)
                    export_subtitle += u" "
                top_exports = yop_base.order_by(
                    desc("export_val")).limit(2).all()
                if top_exports:
                    # raise Exception(top_exports[0].product.get_profile_link(), num_format((top_exports[0].export_val/exp_val_stat["val"])*100), self.attr.get_name(article="of"), top_exports[1].product.get_profile_link(), num_format((top_exports[1].export_val/exp_val_stat["val"])*100))
                    export_subtitle += _(u"The most recent exports are led by %(top_export)s which represent %(top_export_pct)s%% of the total exports %(of_country)s, followed by %(second_export)s, which account for %(second_export_pct)s%%.",
                                            top_export=top_exports[0].product.get_profile_link(), top_export_pct=num_format((top_exports[0].export_val/exp_val_stat["val"])*100), \
                                            of_country=self.attr.get_name(article="of"), second_export=top_exports[1].product.get_profile_link(), second_export_pct=num_format((top_exports[1].export_val/exp_val_stat["val"])*100))
            imp_val_stat = filter(lambda s: s["key"] == "import_val",
                                  self.stats())
            if imp_val_stat and this_yo:
                imp_val_stat = imp_val_stat.pop()
                import_subtitle = ""
                if self.attr.id != "xxwld":
                    imp_rank = num_format(
                        imp_val_stat["rank"],
                        "ordinal") if imp_val_stat["rank"] > 1 else ""
                    import_subtitle += _(
                        u"In %(year)s %(country)s imported $%(import_val)s, making it the %(import_rank)s largest importer in the world.",
                        year=self.year,
                        country=self.attr.get_name(article=True),
                        import_val=num_format(imp_val_stat["val"]),
                        import_rank=imp_rank)
                    import_subtitle += u" "
                if past_yo and this_yo.import_val_growth_pct_5:
                    chg = "increased" if this_yo.import_val_growth_pct_5 >= 0 else "decreased"
                    import_subtitle += _(u"During the last five years the imports %(of_country)s have %(increased_decreased)s at an annualized rate of %(change_rate)s%%, from $%(past_import_val)s in %(past_year)s to $%(current_import_val)s in %(current_year)s.",
                                            of_country=self.attr.get_name(article="of"), increased_decreased=chg, change_rate=num_format(this_yo.import_val_growth_pct_5*100), \
                                            past_import_val=num_format(past_yo.import_val), past_year=past_yr, current_import_val=num_format(this_yo.import_val), current_year=self.year)
                    import_subtitle += u" "
                top_imports = yop_base.order_by(
                    desc("import_val")).limit(2).all()
                if top_imports:
                    import_subtitle += _(u"The most recent imports are led by %(top_import)s which represent %(top_import_pct)s%% of the total imports %(of_country)s, followed by %(second_import)s, which account for %(second_import_pct)s%%.",
                                            top_import=top_imports[0].product.get_profile_link(), top_import_pct=num_format((top_imports[0].import_val/imp_val_stat["val"])*100), \
                                            of_country=self.attr.get_name(article="of"), second_import=top_imports[1].product.get_profile_link(), second_import_pct=num_format((top_imports[1].import_val/imp_val_stat["val"])*100))

            dests_tmap = Build("tree_map", "hs92", "export", self.attr, "show",
                               "all", self.year)
            yod_exp = self.models.Yod.query.filter_by(
                year=self.year,
                origin=self.attr).order_by(desc("export_val")).limit(5).all()
            if yod_exp:
                dest_list = self.stringify_items(yod_exp, "export_val", "dest")
                dest_subtitle = _(
                    u"The top export destinations %(of_country)s are %(destinations)s.",
                    of_country=self.attr.get_name(article="of"),
                    destinations=dest_list)

            origins_tmap = Build("tree_map", "hs92", "import", self.attr,
                                 "show", "all", self.year)
            yod_imp = self.models.Yod.query.filter_by(
                year=self.year,
                dest=self.attr).order_by(desc("export_val")).limit(5).all()
            if yod_imp:
                origin_list = self.stringify_items(yod_imp, "export_val",
                                                   "origin")
                origin_subtitle = _(
                    u"The top import origins %(of_country)s are %(origins)s.",
                    of_country=self.attr.get_name(article="of"),
                    origins=origin_list)

            # trade balance viz --
            first_yo = self.models.Yo.query.filter_by(
                year=available_years["hs92"][-1], country=self.attr).first()
            tb_subtitle = ""
            tb_build = Build("line", "hs92", "show", self.attr, "all", "all",
                             available_years["hs92"])
            if first_yo:
                net_trade = this_yo.export_val - this_yo.import_val
                trade_balance = _("positive") if net_trade >= 0 else _(
                    "negative")
                trade_direction = _("exports") if net_trade >= 0 else _(
                    "imports")
                tb_subtitle = _(
                    u"As of %(year)s %(country)s had a %(positive_negative)s trade balance of $%(net_trade)s in net %(exports_imports)s.",
                    year=self.year,
                    country=self.attr.get_name(article=True),
                    positive_negative=trade_balance,
                    net_trade=num_format(abs(net_trade)),
                    exports_imports=trade_direction)
                old_yo = self.models.Yo.query.filter_by(
                    year=available_years["hs92"][0],
                    country=self.attr).first()
                if old_yo:
                    old_net_trade = old_yo.export_val - old_yo.import_val
                    old_trade_balance = _(
                        "positive") if old_net_trade >= 0 else _("negative")
                    old_trade_direction = _(
                        "exports") if old_net_trade >= 0 else _("imports")
                    is_diff = True if old_trade_balance != trade_balance else False
                    still_or_not = _(
                        "still") if old_trade_balance == trade_balance else ""
                    tb_subtitle += u" "
                    tb_subtitle += _(
                        u"As compared to their trade balance in %(year)s when they %(still)s had a %(positive_negative)s trade balance of $%(net_trade)s in net %(exports_imports)s.",
                        year=available_years["hs92"][0],
                        still=still_or_not,
                        positive_negative=old_trade_balance,
                        net_trade=num_format(abs(old_net_trade)),
                        exports_imports=old_trade_direction)

            trade_section = {
                "builds": [
                    {
                        "title": _(u"Exports"),
                        "build": export_tmap,
                        "subtitle": export_subtitle,
                        "tour": "This is just a test",
                        "seq": 5
                    },
                    {
                        "title": _(u"Imports"),
                        "build": import_tmap,
                        "subtitle": import_subtitle
                    },
                    {
                        "title": _(u"Trade Balance"),
                        "build": tb_build,
                        "subtitle": tb_subtitle
                    },
                    {
                        "title": _(u"Destinations"),
                        "build": dests_tmap,
                        "subtitle": dest_subtitle
                    },
                    {
                        "title": _(u"Origins"),
                        "build": origins_tmap,
                        "subtitle": origin_subtitle
                    },
                ]
            }

        sections.append(trade_section)
        ''' Product Space Section
        '''
        subtitle = False
        if self.attr.id != "xxwld":
            num_exports_w_rca = db.session.query(func.count(self.models.Yop.hs92_id)) \
                        .filter_by(year = self.year, origin = self.attr) \
                        .filter(self.models.Yop.export_rca >= 1) \
                        .filter(func.char_length(self.models.Yop.hs92_id)==6) \
                        .scalar()
            this_attr_yo = attrs.Yo.query.filter_by(year=self.year,
                                                    country=self.attr).first()
            if this_attr_yo:
                eci = this_attr_yo.eci
                eci_rank = this_attr_yo.eci_rank
                if eci_rank:
                    subtitle = _(
                        u"The economy %(of_country)s has an Economic Complexity Index (ECI) of %(eci)s making it the %(eci_rank)s most complex country.",
                        of_country=self.attr.get_name(article="of"),
                        eci=num_format(eci),
                        eci_rank=num_format(eci_rank, "ordinal"))
                    subtitle += u" "
                else:
                    subtitle = ""
                subtitle += _(u"%(country)s exports %(num_of_exports)s products with revealed comparative advantage " \
                    u"(meaning that its share of global exports is larger than what " \
                    u"would be expected from the size of its export economy " \
                    u"and from the size of a product’s global market).",
                    country=self.attr.get_name(article=True), num_of_exports=num_exports_w_rca)
        product_space = Build("network", "hs92", "export", self.attr, "all",
                              "show", self.year)
        ps_text = _(
            u"The product space is a network connecting products that are likely to be co-exported and can be used to predict the evolution of a country’s export structure."
        )
        if subtitle:
            ps_text = u"{}</p><p>{}".format(ps_text, subtitle)
        ps_section = {
            "title":
            _(u"Economic Complexity %(of_country)s",
              of_country=self.attr.get_name(article="of")),
            "builds": [{
                "title": _(u"Product Space"),
                "build": product_space,
                "subtitle": ps_text,
                "tour": "The product space...",
                "seq": 6
            }]
        }
        ''' PGI Section
        '''
        if self.attr.id != "xxwld":
            pgi_product_space = Build("network", "sitc", "pgi", self.attr,
                                      "all", "show",
                                      available_years["sitc"][-1])
            subtitle = _(
                "In this version of the product space products are colored according to their Product Gini Index, or PGI. The PGI of a product is the level of income inequality that we expect for the countries that export a product. For more information see: %(paper1)s and %(paper2)s.",
                country=self.attr.get_name(article=True),
                paper1=
                "<a target='_blank' href='https://arxiv.org/abs/1505.07907'>Linking Economic Complexity, Institutions and Income Inequality</a>",
                paper2=
                "<a target='_blank' href='https://arxiv.org/abs/1701.03770'>The structural constraints of income inequality in Latin America</a>"
            )
            ps_section["builds"].append({
                "title":
                _(u"Complexity and Income Inequality"),
                "build":
                pgi_product_space,
                "subtitle":
                subtitle
            })
        ''' ECI Ranking Section
        '''
        if self.attr.id == "xxwld":
            line_rankings = Build(
                "line", "sitc", "eci", "show", "all", "all",
                [y for y in available_years["sitc"] if y >= 1964])
            start_year = 1980
            start_year = max(1964, start_year) if start_year != 1980 else 1964
            year_range = self.year - start_year
            subtitle = _(
                "The Economic Complexity of each country visualized over the past %(year_range)s years.",
                year_range=year_range)
            ps_section["builds"].append({
                "title":
                _(u"Economic Complexity Ranking"),
                "build":
                line_rankings,
                "subtitle":
                subtitle
            })

        elif this_attr_yo and this_attr_yo.eci != None:
            line_rankings = Build(
                "line", "sitc", "eci", "show", self.attr, "all",
                [y for y in available_years["sitc"] if y >= 1964])
            start_year = earliest_data.get(self.attr.id, 1980)
            start_year = max(1964, start_year) if start_year != 1980 else 1964
            year_range = self.year - start_year

            attr_yo_historic = attrs.Yo.query.filter_by(
                country=self.attr).filter(attrs.Yo.year == start_year).first()
            if attr_yo_historic and attr_yo_historic.eci_rank != None and this_attr_yo.eci_rank != None:
                eci_delta = this_attr_yo.eci_rank - attr_yo_historic.eci_rank
                inc_dec = _('increased') if eci_delta < 0 else _('decreased')
                subtitle = _(
                    "The Economic Complexity ranking %(of_country)s has %(increased_or_decreased)s by %(rank_delta)s places over the past %(year_range)s years from %(old_eci)s in %(old_year)s to %(current_eci)s in %(current_year)s.",
                    of_country=self.attr.get_name(article="of"),
                    increased_or_decreased=inc_dec,
                    rank_delta=abs(eci_delta),
                    year_range=year_range,
                    old_eci=num_format(attr_yo_historic.eci_rank, "ordinal"),
                    old_year=start_year,
                    current_eci=num_format(this_attr_yo.eci_rank, "ordinal"),
                    current_year=self.year)
            ps_section["builds"].append({
                "title":
                _(u"Economic Complexity Ranking"),
                "build":
                line_rankings,
                "subtitle":
                subtitle
            })
        sections.append(ps_section)

        sections.append({
            "title":
            _(u"More on %(country)s from our other sites",
              country=self.attr.get_name(article=True)),
            "source":
            "sisters"
        })
        ''' DataViva
        '''
        # dv_section = make_dv_section(self)
        # sections.append(dv_section)
        ''' Data USA
        '''
        if self.attr.id == "nausa":
            us_section = make_us_section()
            sections.append(us_section)
        ''' Data Africa
        '''
        if any(country[0] == self.attr.id
               for country in data_africa_countries):
            da_country = filter(lambda x: x[0] == self.attr.id,
                                data_africa_countries)
            africa_section = make_africa_section(self, da_country[0])
            sections.append(africa_section)
            # raise Exception("found dataafrican country: {}".format(da_country[0]))
        ''' Pantheon
        '''
        pantheon_id = "all" if self.attr.id == "xxwld" else self.attr.id_2char
        if pantheon_id:
            if self.attr.id != "xxwld":
                pantheon_id = pantheon_id.upper()

            pantheon_section = make_pantheon_section(pantheon_id, self.attr)
            sections.append(pantheon_section)

        return sections
示例#5
0
    def sections(self):
        sections = []
        ''' Trade Section
        '''

        if self.attr.id == "xxwld":

            export_tmap = Build("tree_map", "hs92", "export", self.attr, "all", "show", self.year)
            this_yo = self.models.Yo.query.filter_by(year = self.year).all()

            export_val = sum([o.export_val for o in this_yo])
            export_subtitle = _(u"The total world trade in %(year)s was %(export_val)s. ", year=self.year, export_val=num_format(export_val, "export_val"))

            past_yr = self.year - 5
            past_yo = self.models.Yo.query.filter_by(year = past_yr).all()
            growth_val = median([o.export_val_growth_pct_5 for o in this_yo])
            chg = "increased" if growth_val >= 0 else "decreased"
            export_subtitle += _(u"During the last five years exports have %(increased_decreased)s at a median annualized rate of %(change_rate)s%%, from $%(past_export_val)s in %(past_year)s to $%(current_export_val)s in %(current_year)s. ",
                                    increased_decreased=chg, change_rate=num_format(growth_val*100), \
                                    past_export_val=num_format(sum([o.export_val for o in past_yo])), past_year=past_yr, current_export_val=num_format(export_val), current_year=self.year)

            top_exports = self.models.Yp.query.filter_by(year = self.year, hs92_id_len=6).order_by(desc("export_val")).limit(2).all()
            export_subtitle += _(u"The most recent exports are led by %(top_export)s which represent %(top_export_pct)s%% of the total products exported, followed by %(second_export)s, which account for %(second_export_pct)s%%. ",
                                    top_export=top_exports[0].product.get_profile_link(), top_export_pct=num_format((top_exports[0].export_val/export_val)*100), \
                                    second_export=top_exports[1].product.get_profile_link(), second_export_pct=num_format((top_exports[1].export_val/export_val)*100))

            origins_tmap = Build("tree_map", "hs92", "import", self.attr, "show", "all", self.year)
            yo_exp = self.models.Yo.query.filter_by(year = self.year).order_by(desc("export_val")).limit(5).all()
            origin_list = self.stringify_items(yo_exp, "export_val", "country")
            origin_subtitle = _(u"The top exporters globally are %(origins)s.", origins=origin_list)

            trade_section = {
                "builds": [
                    {"title": _(u"Exports"), "build": export_tmap, "subtitle": export_subtitle, "tour":"This is just a test", "seq":5},
                    {"title": _(u"Origins"), "build": origins_tmap, "subtitle": origin_subtitle},
                ]
            }

        else:

            export_subtitle, import_subtitle, dest_subtitle, origin_subtitle = [None]*4

            export_tmap = Build("tree_map", "hs92", "export", self.attr, "all", "show", self.year)
            import_tmap = Build("tree_map", "hs92", "import", self.attr, "all", "show", self.year)

            yop_base = self.models.Yop.query.filter_by(year = self.year, origin = self.attr, hs92_id_len=6)
            # get growth
            past_yr = self.year - 5
            past_yo = self.models.Yo.query.filter_by(year = past_yr, country = self.attr).first()
            this_yo = self.models.Yo.query.filter_by(year = self.year, country = self.attr).first()
            exp_val_stat = filter(lambda s: s["key"] == "export_val", self.stats())
            if exp_val_stat:
                exp_val_stat = exp_val_stat.pop()
                export_subtitle = ""
                if self.attr.id != "xxwld":
                    exp_rank = num_format(exp_val_stat["rank"], "ordinal") if exp_val_stat["rank"] > 1 else ""
                    export_subtitle += _(u"In %(year)s %(country)s exported $%(export_val)s, making it the %(export_rank)s largest exporter in the world. ",
                                        year=self.year, country=self.attr.get_name(article=True), export_val=num_format(exp_val_stat["val"]), export_rank=exp_rank)
                if past_yo:
                    chg = "increased" if this_yo.export_val_growth_pct_5 >= 0 else "decreased"
                    export_subtitle += _(u"During the last five years the exports %(of_country)s have %(increased_decreased)s at an annualized rate of %(change_rate)s%%, from $%(past_export_val)s in %(past_year)s to $%(current_export_val)s in %(current_year)s. ",
                                            of_country=self.attr.get_name(article="of"), increased_decreased=chg, change_rate=num_format(this_yo.export_val_growth_pct_5*100), \
                                            past_export_val=num_format(past_yo.export_val), past_year=past_yr, current_export_val=num_format(this_yo.export_val), current_year=self.year)
                top_exports = yop_base.order_by(desc("export_val")).limit(2).all()
                if top_exports:
                    # raise Exception(top_exports[0].product.get_profile_link(), num_format((top_exports[0].export_val/exp_val_stat["val"])*100), self.attr.get_name(article="of"), top_exports[1].product.get_profile_link(), num_format((top_exports[1].export_val/exp_val_stat["val"])*100))
                    export_subtitle += _(u"The most recent exports are led by %(top_export)s which represent %(top_export_pct)s%% of the total exports %(of_country)s, followed by %(second_export)s, which account for %(second_export_pct)s%%.",
                                            top_export=top_exports[0].product.get_profile_link(), top_export_pct=num_format((top_exports[0].export_val/exp_val_stat["val"])*100), \
                                            of_country=self.attr.get_name(article="of"), second_export=top_exports[1].product.get_profile_link(), second_export_pct=num_format((top_exports[1].export_val/exp_val_stat["val"])*100))
            imp_val_stat = filter(lambda s: s["key"] == "import_val", self.stats())
            if imp_val_stat:
                imp_val_stat = imp_val_stat.pop()
                import_subtitle = ""
                if self.attr.id != "xxwld":
                    imp_rank = num_format(imp_val_stat["rank"], "ordinal") if imp_val_stat["rank"] > 1 else ""
                    import_subtitle += _(u"In %(year)s %(country)s imported $%(import_val)s, making it the %(import_rank)s largest importer in the world. ",
                                        year=self.year, country=self.attr.get_name(article=True), import_val=num_format(imp_val_stat["val"]), import_rank=imp_rank)
                if past_yo:
                    chg = "increased" if this_yo.import_val_growth_pct_5 >= 0 else "decreased"
                    import_subtitle += _(u"During the last five years the imports %(of_country)s have %(increased_decreased)s at an annualized rate of %(change_rate)s%%, from $%(past_import_val)s in %(past_year)s to $%(current_import_val)s in %(current_year)s. ",
                                            of_country=self.attr.get_name(article="of"), increased_decreased=chg, change_rate=num_format(this_yo.import_val_growth_pct_5*100), \
                                            past_import_val=num_format(past_yo.import_val), past_year=past_yr, current_import_val=num_format(this_yo.import_val), current_year=self.year)
                top_imports = yop_base.order_by(desc("import_val")).limit(2).all()
                if top_imports:
                    import_subtitle += _(u"The most recent imports are led by %(top_import)s which represent %(top_import_pct)s%% of the total imports %(of_country)s, followed by %(second_import)s, which account for %(second_import_pct)s%%.",
                                            top_import=top_imports[0].product.get_profile_link(), top_import_pct=num_format((top_imports[0].import_val/imp_val_stat["val"])*100), \
                                            of_country=self.attr.get_name(article="of"), second_import=top_imports[1].product.get_profile_link(), second_import_pct=num_format((top_imports[1].import_val/imp_val_stat["val"])*100))

            dests_tmap = Build("tree_map", "hs92", "export", self.attr, "show", "all", self.year)
            yod_exp = self.models.Yod.query.filter_by(year = self.year, origin = self.attr).order_by(desc("export_val")).limit(5).all()
            if yod_exp:
                dest_list = self.stringify_items(yod_exp, "export_val", "dest")
                dest_subtitle = _(u"The top export destinations %(of_country)s are %(destinations)s.", of_country=self.attr.get_name(article="of"), destinations=dest_list)

            origins_tmap = Build("tree_map", "hs92", "import", self.attr, "show", "all", self.year)
            yod_imp = self.models.Yod.query.filter_by(year = self.year, dest = self.attr).order_by(desc("export_val")).limit(5).all()
            if yod_imp:
                origin_list = self.stringify_items(yod_imp, "export_val", "origin")
                origin_subtitle = _(u"The top import origins %(of_country)s are %(origins)s.", of_country=self.attr.get_name(article="of"), origins=origin_list)

            # trade balance viz --
            first_yo = self.models.Yo.query.filter_by(year = available_years["hs92"][-1], country = self.attr).first()
            tb_subtitle = ""
            tb_build = Build("line", "hs92", "show", self.attr, "all", "all", available_years["hs92"])
            if first_yo:
                net_trade = this_yo.export_val - this_yo.import_val
                trade_balance = _("positive") if net_trade >= 0 else _("negative")
                trade_direction = _("exports") if net_trade >= 0 else _("imports")
                tb_subtitle = _(u"As of %(year)s %(country)s had a %(positive_negative)s trade balance of $%(net_trade)s in net %(exports_imports)s.",
                                year=self.year, country=self.attr.get_name(article=True), positive_negative=trade_balance, net_trade=num_format(abs(net_trade)), exports_imports=trade_direction)
                old_yo = self.models.Yo.query.filter_by(year = available_years["hs92"][0], country = self.attr).first()
                if old_yo:
                    old_net_trade = old_yo.export_val - old_yo.import_val
                    old_trade_balance = _("positive") if old_net_trade >= 0 else _("negative")
                    old_trade_direction = _("exports") if old_net_trade >= 0 else _("imports")
                    is_diff = True if old_trade_balance != trade_balance else False
                    still_or_not = _("still") if old_trade_balance == trade_balance else ""
                    tb_subtitle += _(u" As compared to their trade balance in %(year)s when they %(still)s had a %(positive_negative)s trade balance of $%(net_trade)s in net %(exports_imports)s.",
                                    year=available_years["hs92"][0], still=still_or_not, positive_negative=old_trade_balance, net_trade=num_format(abs(old_net_trade)), exports_imports=old_trade_direction)

            trade_section = {
                "builds": [
                    {"title": _(u"Exports"), "build": export_tmap, "subtitle": export_subtitle, "tour":"This is just a test", "seq":5},
                    {"title": _(u"Imports"), "build": import_tmap, "subtitle": import_subtitle},
                    {"title": _(u"Trade Balance"), "build": tb_build, "subtitle": tb_subtitle},
                    {"title": _(u"Destinations"), "build": dests_tmap, "subtitle": dest_subtitle},
                    {"title": _(u"Origins"), "build": origins_tmap, "subtitle": origin_subtitle},
                ]
            }

        sections.append(trade_section)

        ''' Product Space Section
        '''
        subtitle = False
        if self.attr.id != "xxwld":
            num_exports_w_rca = db.session.query(func.count(self.models.Yop.hs92_id)) \
                        .filter_by(year = self.year, origin = self.attr) \
                        .filter(self.models.Yop.export_rca >= 1) \
                        .filter(func.char_length(self.models.Yop.hs92_id)==6) \
                        .scalar()
            this_attr_yo = attrs.Yo.query.filter_by(year = self.year, country = self.attr).first()
            if this_attr_yo:
                eci = this_attr_yo.eci
                eci_rank = this_attr_yo.eci_rank
                if eci_rank:
                    subtitle = _(u"The economy %(of_country)s has an Economic Complexity Index (ECI) of %(eci)s making it the %(eci_rank)s most complex country. ",
                                of_country=self.attr.get_name(article="of"), eci=num_format(eci), eci_rank=num_format(eci_rank, "ordinal"))
                else:
                    subtitle = ""
                subtitle += _(u"%(country)s exports %(num_of_exports)s products with revealed comparative advantage " \
                    u"(meaning that its share of global exports is larger than what " \
                    u"would be expected from the size of its export economy " \
                    u"and from the size of a product’s global market).",
                    country=self.attr.get_name(article=True), num_of_exports=num_exports_w_rca)
        product_space = Build("network", "hs92", "export", self.attr, "all", "show", self.year)
        ps_text = _(u"The product space is a network connecting products that are likely to be co-exported and can be used to predict the evolution of a country’s export structure.")
        if subtitle:
            ps_text = u"{}</p><p>{}".format(ps_text, subtitle)
        ps_section = {
            "title": _(u"Economic Complexity %(of_country)s", of_country=self.attr.get_name(article="of")),
            "builds": [
                {"title": _(u"Product Space"), "build": product_space, "subtitle": ps_text, "tour":"The product space...", "seq":6}
            ]
        }

        ''' ECI Ranking Section
        '''
        if self.attr.id == "xxwld":
            line_rankings = Build("line", "sitc", "eci", "show", "all", "all", [y for y in available_years["sitc"] if y >= 1964])
            start_year = 1980
            start_year = max(1964, start_year) if start_year != 1980 else 1964
            year_range = self.year - start_year
            subtitle = _("""The Economic Complexities of each country visualized over the past %(year_range)s years.""", year_range=year_range)
            ps_section["builds"].append({"title": _(u"Economic Complexity Ranking"), "build": line_rankings, "subtitle": subtitle})

        elif this_attr_yo and this_attr_yo.eci != None:
            line_rankings = Build("line", "sitc", "eci", "show", self.attr, "all", [y for y in available_years["sitc"] if y >= 1964])
            start_year = earliest_data.get(self.attr.id, 1980)
            start_year = max(1964, start_year) if start_year != 1980 else 1964
            year_range = self.year - start_year

            attr_yo_historic = attrs.Yo.query.filter_by(country=self.attr).filter(attrs.Yo.year == start_year).first()
            if attr_yo_historic.eci_rank:
                eci_delta = this_attr_yo.eci_rank - attr_yo_historic.eci_rank
                inc_dec = _('increased') if eci_delta < 0 else _('decreased')
                subtitle = _("""The Economic Complexity ranking %(of_country)s has %(increased_or_decreased)s by %(rank_delta)s places
                    over the past %(year_range)s years from %(old_eci)s in %(old_year)s to %(current_eci)s in %(current_year)s.""",
                    of_country=self.attr.get_name(article="of"), increased_or_decreased=inc_dec,
                    rank_delta=abs(eci_delta), year_range=year_range, old_eci=num_format(attr_yo_historic.eci_rank, "ordinal"),
                    old_year=start_year, current_eci=num_format(this_attr_yo.eci_rank, "ordinal"), current_year=self.year)
            ps_section["builds"].append({"title": _(u"Economic Complexity Ranking"), "build": line_rankings, "subtitle": subtitle})
        sections.append(ps_section)

        sections.append({
            "title": _(u"More on %(country)s from our sister sites", country=self.attr.get_name(article=True)),
            "source": "sisters"
        })

        ''' DataViva
        '''
        if self.attr.id == "xxwld":
            dv_munic_dest_iframe = "http://dataviva.info/apps/embed/tree_map/secex/all/all/all/bra/?size=import_val&controls=false"
            dv_munic_dest_subtitle = _(u"""
                This treemap shows the municipalities in Brazil that imported products internationally.<br /><br />
                DataViva is a visualization tool that provides official data on trade, industries, and education throughout Brazil. If you would like more info or to create a similar site get in touch with us at <a href='mailto:[email protected]'>[email protected]</a>.
                </p><p><a target='_blank' href='http://dataviva.info/apps/builder/tree_map/secex/all/all/all/bra/?size=import_val&controls=false'>Explore on DataViva <i class='fa fa-external-link'></i></a>
                """, country=self.attr.get_name(article=True))
            dv_section = {
                "title": u"<a href='http://dataviva.info/' target='_blank'><img src='http://en.dataviva.info/static/img/nav/DataViva.png' /></a>",
                "source": "dataviva",
                "builds": [
                    {"title": _(u"Imports of Brazil by Municipality"), "iframe": dv_munic_dest_iframe, "subtitle": dv_munic_dest_subtitle, "tour":"Profile pages also contain visualizations from other websites created by member of the OEC team. The following are 2 embeded visualization from DataViva, a similar visualization platorm centered around Brazilian data.", "seq":7}
                ]
            }
        elif self.attr.id == "sabra":
            dv_geo_map = "http://en.dataviva.info/apps/embed/geo_map/secex/all/all/all/bra/?color=export_val&controls=false&year=2013"
            dv_wages = "http://en.dataviva.info/apps/embed/bar/rais/all/all/all/bra/?controls=false&year=2013"
            dv_geo_map_subtitle = _(u"""
                This map shows the exports of Brazil by state.<br /><br />
                DataViva is a visualization tool that provides official data on trade, industries, and education throughout Brazil. If you would like more info or to create a similar site get in touch with us at <a href='mailto:[email protected]'>[email protected]</a>.
                </p><p><a target='_blank' href='http://en.dataviva.info/apps/builder/geo_map/secex/all/all/all/bra/?color=export_val&controls=false&year=2013'>Explore on DataViva <i class='fa fa-external-link'></i></a>
                """)
            dv_wages_subtitle = _(u"""
                This bar chart shows the wage distribution for the working population in Brazil.
                </p><p><a target='_blank' href='http://en.dataviva.info/apps/builder/bar/rais/all/all/all/bra/?controls=false&year=2013'>Explore on DataViva <i class='fa fa-external-link'></i></a>
                """)
            dv_section = {
                "title": u"<a href='http://dataviva.info/' target='_blank'><img src='http://en.dataviva.info/static/img/nav/DataViva.png' /></a>",
                "source": "dataviva",
                "builds": [
                    {"title": _(u"State Exports"), "iframe": dv_geo_map, "subtitle": dv_geo_map_subtitle, "tour":"Profile pages also contain visualizations from other websites created by member of the OEC team. The following are 2 embeded visualization from DataViva, a similar visualization platorm centered around Brazilian data.", "seq":7},
                    {"title": _(u"Wage Distribution"), "iframe": dv_wages, "subtitle": dv_wages_subtitle},
                ]
            }
        else:
            dv_country_id = "asrus" if self.attr.id == "eurus" else self.attr.id
            dv_munic_dest_iframe = "http://dataviva.info/apps/embed/tree_map/secex/all/all/{}/bra/?size=import_val&controls=false".format(dv_country_id)
            dv_munic_origin_iframe = "http://dataviva.info/apps/embed/tree_map/secex/all/all/{}/bra/?size=export_val&controls=false".format(dv_country_id)
            dv_munic_dest_subtitle = _(u"""
                This treemap shows the municipalities in Brazil that imported products from %(country)s.<br /><br />
                DataViva is a visualization tool that provides official data on trade, industries, and education throughout Brazil. If you would like more info or to create a similar site get in touch with us at <a href='mailto:[email protected]'>[email protected]</a>.
                </p><p><a target='_blank' href='http://dataviva.info/apps/builder/tree_map/secex/all/all/%(dv_country_id)s/bra/?size=import_val&controls=false'>Explore on DataViva <i class='fa fa-external-link'></i></a>
                """, country=self.attr.get_name(article=True), dv_country_id=dv_country_id)
            dv_munic_origin_subtitle = _(u"""
                This treemap shows the municipalities in Brazil that exported products to %(country)s.
                </p><p><a target='_blank' href='http://dataviva.info/apps/builder/tree_map/secex/all/all/%(dv_country_id)s/bra/?size=export_val&controls=false'>Explore on DataViva <i class='fa fa-external-link'></i></a>
                """, country=self.attr.get_name(article=True), dv_country_id=dv_country_id)
            dv_section = {
                "title": u"<a href='http://dataviva.info/' target='_blank'><img src='http://en.dataviva.info/static/img/nav/DataViva.png' /></a>",
                "source": "dataviva",
                "builds": [
                    {"title": _(u"Brazilian Municipalities that import from %(country)s", country=self.attr.get_name(article=True)), "iframe": dv_munic_dest_iframe, "subtitle": dv_munic_dest_subtitle, "tour":"Profile pages also contain visualizations from other websites created by member of the OEC team. The following are 2 embeded visualization from DataViva, a similar visualization platorm centered around Brazilian data.", "seq":7},
                    {"title": _(u"Brazilian Municipalities that export to %(country)s", country=self.attr.get_name(article=True)), "iframe": dv_munic_origin_iframe, "subtitle": dv_munic_origin_subtitle},
                ]
            }
        sections.append(dv_section)

        ''' Pantheon
        '''
        pantheon_id = "all" if self.attr.id == "xxwld" else self.attr.id_2char
        if pantheon_id:
            if self.attr.id != "xxwld":
                pantheon_id = pantheon_id.upper()
            pantheon_iframe_fields = "http://pantheon.media.mit.edu/treemap/country_exports/{}/all/-4000/2010/H15/pantheon/embed".format(pantheon_id)
            pantheon_link_fields = "<a target='_blank' href='http://pantheon.media.mit.edu/treemap/country_exports/{}/all/-4000/2010/H15/pantheon/'>Explore on Pantheon <i class='fa fa-external-link'></i></a>".format(pantheon_id)
            pantheon_iframe_cities = "http://pantheon.media.mit.edu/treemap/country_by_city/all/{}/-4000/2010/H15/pantheon/embed".format(pantheon_id)
            pantheon_link_cities = "<a target='_blank' href='http://pantheon.media.mit.edu/treemap/country_by_city/{}/all/-4000/2010/H15/pantheon/'>Explore on Pantheon <i class='fa fa-external-link'></i></a>".format(pantheon_id)
            pantheon_section = {
                "title": "<a target='_blank' href='http://pantheon.media.mit.edu'><img src='http://pantheon.media.mit.edu/pantheon_logo.png' />",
                "source": "pantheon",
                "builds": [
                    {"title": _(u"Globally Famous People %(of_country)s", of_country=self.attr.get_name(article="of")),
                    "iframe": pantheon_iframe_fields,
                    "subtitle": _(u"This treemap shows the cultural exports %(of_country)s, as proxied by the production of globally famous historical characters.</p><p>%(pantheon_link)s", of_country=self.attr.get_name(article="of"), pantheon_link=pantheon_link_fields),
                    "tour":"Pantheon...", "seq":8
                    },
                    {"title": _(u"Globally Famous People %(of_country)s by City", of_country=self.attr.get_name(article="of")),
                    "iframe": pantheon_iframe_cities,
                    "subtitle": _(u"This treemap shows the cultural exports %(of_country)s by city, as proxied by the production of globally famous historical characters.</p><p>%(pantheon_link)s", of_country=self.attr.get_name(article="of"), pantheon_link=pantheon_link_cities)
                    },
                ]
            }
            sections.append(pantheon_section)

        return sections
示例#6
0
    def sections(self):
        sections = []
        ''' Trade Section
        '''
        export_subtitle, import_subtitle, dest_subtitle, origin_subtitle = [
            None
        ] * 4

        export_tmap = Build("tree_map", "hs92", "export", self.attr, "all",
                            "show", self.year)
        import_tmap = Build("tree_map", "hs92", "import", self.attr, "all",
                            "show", self.year)

        yop_base = self.models.Yop.query.filter_by(year=self.year,
                                                   origin=self.attr,
                                                   hs92_id_len=6)
        # get growth
        past_yr = self.year - 5
        past_yo = self.models.Yo.query.filter_by(year=past_yr,
                                                 country=self.attr).first()
        this_yo = self.models.Yo.query.filter_by(year=self.year,
                                                 country=self.attr).first()
        exp_val_stat = filter(lambda s: s["key"] == "export_val", self.stats())
        if exp_val_stat:
            exp_val_stat = exp_val_stat.pop()
            exp_rank = num_format(
                exp_val_stat["rank"],
                "ordinal") if exp_val_stat["rank"] > 1 else ""
            export_subtitle = _(
                u"In %(year)s %(country)s exported $%(export_val)s, making it the %(export_rank)s largest exporter in the world. ",
                year=self.year,
                country=self.attr.get_name(article=True),
                export_val=num_format(exp_val_stat["val"]),
                export_rank=exp_rank)
            if past_yo:
                chg = "increased" if this_yo.export_val_growth_pct_5 >= 0 else "decreased"
                export_subtitle += _(u"During the last five years the exports %(of_country)s have %(increased_decreased)s at an annualized rate of %(change_rate)s%%, from $%(past_export_val)s in %(past_year)s to $%(current_export_val)s in %(current_year)s. ",
                                        of_country=self.attr.get_name(article="of"), increased_decreased=chg, change_rate=num_format(this_yo.export_val_growth_pct_5*100), \
                                        past_export_val=num_format(past_yo.export_val), past_year=past_yr, current_export_val=num_format(this_yo.export_val), current_year=self.year)
            top_exports = yop_base.order_by(desc("export_val")).limit(2).all()
            if top_exports:
                # raise Exception(top_exports[0].product.get_profile_link(), num_format((top_exports[0].export_val/exp_val_stat["val"])*100), self.attr.get_name(article="of"), top_exports[1].product.get_profile_link(), num_format((top_exports[1].export_val/exp_val_stat["val"])*100))
                export_subtitle += _(u"The most recent exports are led by %(top_export)s which represent %(top_export_pct)s%% of the total exports %(of_country)s, followed by %(second_export)s, which account for %(second_export_pct)s%%.",
                                        top_export=top_exports[0].product.get_profile_link(), top_export_pct=num_format((top_exports[0].export_val/exp_val_stat["val"])*100), \
                                        of_country=self.attr.get_name(article="of"), second_export=top_exports[1].product.get_profile_link(), second_export_pct=num_format((top_exports[1].export_val/exp_val_stat["val"])*100))
        imp_val_stat = filter(lambda s: s["key"] == "import_val", self.stats())
        if imp_val_stat:
            imp_val_stat = imp_val_stat.pop()
            imp_rank = num_format(
                imp_val_stat["rank"],
                "ordinal") if imp_val_stat["rank"] > 1 else ""
            import_subtitle = _(
                u"In %(year)s %(country)s imported $%(import_val)s, making it the %(import_rank)s largest importer in the world. ",
                year=self.year,
                country=self.attr.get_name(article=True),
                import_val=num_format(imp_val_stat["val"]),
                import_rank=imp_rank)
            if past_yo:
                chg = "increased" if this_yo.import_val_growth_pct_5 >= 0 else "decreased"
                import_subtitle += _(u"During the last five years the imports %(of_country)s have %(increased_decreased)s at an annualized rate of %(change_rate)s%%, from $%(past_import_val)s in %(past_year)s to $%(current_import_val)s in %(current_year)s. ",
                                        of_country=self.attr.get_name(article="of"), increased_decreased=chg, change_rate=num_format(this_yo.import_val_growth_pct_5*100), \
                                        past_import_val=num_format(past_yo.import_val), past_year=past_yr, current_import_val=num_format(this_yo.import_val), current_year=self.year)
            top_imports = yop_base.order_by(desc("import_val")).limit(2).all()
            if top_imports:
                import_subtitle += _(u"The most recent imports are led by %(top_import)s which represent %(top_import_pct)s%% of the total imports %(of_country)s, followed by %(second_import)s, which account for %(second_import_pct)s%%.",
                                        top_import=top_imports[0].product.get_profile_link(), top_import_pct=num_format((top_imports[0].import_val/imp_val_stat["val"])*100), \
                                        of_country=self.attr.get_name(article="of"), second_import=top_imports[1].product.get_profile_link(), second_import_pct=num_format((top_imports[1].import_val/imp_val_stat["val"])*100))

        dests_tmap = Build("tree_map", "hs92", "export", self.attr, "show",
                           "all", self.year)
        yod_exp = self.models.Yod.query.filter_by(
            year=self.year,
            origin=self.attr).order_by(desc("export_val")).limit(5).all()
        if yod_exp:
            dest_list = self.stringify_items(yod_exp, "export_val", "dest")
            dest_subtitle = _(
                u"The top export destinations %(of_country)s are %(destinations)s.",
                of_country=self.attr.get_name(article="of"),
                destinations=dest_list)

        origins_tmap = Build("tree_map", "hs92", "import", self.attr, "show",
                             "all", self.year)
        yod_imp = self.models.Yod.query.filter_by(
            year=self.year,
            dest=self.attr).order_by(desc("export_val")).limit(5).all()
        if yod_imp:
            origin_list = self.stringify_items(yod_imp, "export_val", "origin")
            origin_subtitle = _(
                u"The top import origins %(of_country)s are %(origins)s.",
                of_country=self.attr.get_name(article="of"),
                origins=origin_list)

        # trade balance viz --
        first_yo = self.models.Yo.query.filter_by(
            year=available_years["hs92"][-1], country=self.attr).first()
        tb_subtitle = ""
        tb_build = Build("line", "hs92", "show", self.attr, "all", "all",
                         available_years["hs92"])
        if first_yo:
            net_trade = this_yo.export_val - this_yo.import_val
            trade_balance = _("positive") if net_trade >= 0 else _("negative")
            trade_direction = _("exports") if net_trade >= 0 else _("imports")
            tb_subtitle = _(
                u"As of %(year)s %(country)s had a %(positive_negative)s trade balance of $%(net_trade)s in net %(exports_imports)s.",
                year=self.year,
                country=self.attr.get_name(article=True),
                positive_negative=trade_balance,
                net_trade=num_format(abs(net_trade)),
                exports_imports=trade_direction)
            old_yo = self.models.Yo.query.filter_by(
                year=available_years["hs92"][0], country=self.attr).first()
            if old_yo:
                old_net_trade = old_yo.export_val - old_yo.import_val
                old_trade_balance = _("positive") if old_net_trade >= 0 else _(
                    "negative")
                old_trade_direction = _(
                    "exports") if old_net_trade >= 0 else _("imports")
                is_diff = True if old_trade_balance != trade_balance else False
                still_or_not = _(
                    "still") if old_trade_balance == trade_balance else ""
                tb_subtitle += _(
                    u" As compared to their trade balance in %(year)s when they %(still)s had a %(positive_negative)s trade balance of $%(net_trade)s in net %(exports_imports)s.",
                    year=available_years["hs92"][0],
                    still=still_or_not,
                    positive_negative=old_trade_balance,
                    net_trade=num_format(abs(old_net_trade)),
                    exports_imports=old_trade_direction)

        trade_section = {
            "builds": [
                {
                    "title": _(u"Exports"),
                    "build": export_tmap,
                    "subtitle": export_subtitle,
                    "tour": "This is just a test",
                    "seq": 5
                },
                {
                    "title": _(u"Imports"),
                    "build": import_tmap,
                    "subtitle": import_subtitle
                },
                {
                    "title": _(u"Trade Balance"),
                    "build": tb_build,
                    "subtitle": tb_subtitle
                },
                {
                    "title": _(u"Destinations"),
                    "build": dests_tmap,
                    "subtitle": dest_subtitle
                },
                {
                    "title": _(u"Origins"),
                    "build": origins_tmap,
                    "subtitle": origin_subtitle
                },
            ]
        }
        sections.append(trade_section)
        ''' Product Space Section
        '''
        num_exports_w_rca = db.session.query(func.count(self.models.Yop.hs92_id)) \
                    .filter_by(year = self.year, origin = self.attr) \
                    .filter(self.models.Yop.export_rca >= 1) \
                    .filter(func.char_length(self.models.Yop.hs92_id)==6) \
                    .scalar()
        this_attr_yo = attrs.Yo.query.filter_by(year=self.year,
                                                country=self.attr).first()
        if this_attr_yo:
            eci = this_attr_yo.eci
            eci_rank = this_attr_yo.eci_rank
            if eci_rank:
                subtitle = _(
                    u"The economy %(of_country)s has an Economic Complexity Index (ECI) of %(eci)s making it the %(eci_rank)s most complex country. ",
                    of_country=self.attr.get_name(article="of"),
                    eci=num_format(eci),
                    eci_rank=num_format(eci_rank, "ordinal"))
            else:
                subtitle = ""
            subtitle += _(u"%(country)s exports %(num_of_exports)s products with revealed comparative advantage " \
                u"(meaning that its share of global exports is larger than what " \
                u"would be expected from the size of its export economy " \
                u"and from the size of a product’s global market).",
                country=self.attr.get_name(article=True), num_of_exports=num_exports_w_rca)
        else:
            subtitle = ""
        product_space = Build("network", "hs92", "export", self.attr, "all",
                              "show", self.year)
        ps_text = _(
            u"The product space is a network connecting products that are likely to be co-exported and can be used to predict the evolution of a country’s export structure."
        )
        ps_text = u"{}</p><p>{}".format(ps_text, subtitle)
        ps_section = {
            "title":
            _(u"Economic Complexity %(of_country)s",
              of_country=self.attr.get_name(article="of")),
            "builds": [{
                "title": _(u"Product Space"),
                "build": product_space,
                "subtitle": ps_text,
                "tour": "The product space...",
                "seq": 6
            }]
        }
        ''' ECI Ranking Section
        '''
        if this_attr_yo and this_attr_yo.eci != None:
            line_rankings = Build(
                "line", "sitc", "eci", "show", self.attr, "all",
                [y for y in available_years["sitc"] if y >= 1964])
            start_year = earliest_data.get(self.attr.id, 1980)
            start_year = max(1964, start_year) if start_year != 1980 else 1964
            year_range = self.year - start_year
            attr_yo_historic = attrs.Yo.query.filter_by(
                country=self.attr).filter(attrs.Yo.year == start_year).first()
            if attr_yo_historic.eci_rank:
                eci_delta = this_attr_yo.eci_rank - attr_yo_historic.eci_rank
                inc_dec = _('increased') if eci_delta < 0 else _('decreased')
                subtitle = _(
                    """The Economic Complexity ranking %(of_country)s has %(increased_or_decreased)s by %(rank_delta)s places
                    over the past %(year_range)s years from %(old_eci)s in %(old_year)s to %(current_eci)s in %(current_year)s.""",
                    of_country=self.attr.get_name(article="of"),
                    increased_or_decreased=inc_dec,
                    rank_delta=abs(eci_delta),
                    year_range=year_range,
                    old_eci=num_format(attr_yo_historic.eci_rank, "ordinal"),
                    old_year=start_year,
                    current_eci=num_format(this_attr_yo.eci_rank, "ordinal"),
                    current_year=self.year)
                ps_section["builds"].append({
                    "title":
                    _(u"Economic Complexity Ranking"),
                    "build":
                    line_rankings,
                    "subtitle":
                    subtitle
                })
        sections.append(ps_section)

        sections.append({
            "title":
            _(u"More on %(country)s from our sister sites",
              country=self.attr.get_name(article=True)),
            "source":
            "sisters"
        })
        ''' DataViva
        '''
        if self.attr.id == "sabra":
            dv_geo_map = "http://en.dataviva.info/apps/embed/geo_map/secex/all/all/all/bra/?color=export_val&controls=false&year=2013"
            dv_wages = "http://en.dataviva.info/apps/embed/bar/rais/all/all/all/bra/?controls=false&year=2013"
            dv_geo_map_subtitle = _(u"""
                This map shows the exports of Brazil by state.<br /><br />
                DataViva is a visualization tool that provides official data on trade, industries, and education throughout Brazil. If you would like more info or to create a similar site get in touch with us at <a href='mailto:[email protected]'>[email protected]</a>.
                </p><p><a target='_blank' href='http://en.dataviva.info/apps/builder/geo_map/secex/all/all/all/bra/?color=export_val&controls=false&year=2013'>Explore on DataViva <i class='fa fa-external-link'></i></a>
                """)
            dv_wages_subtitle = _(u"""
                This bar chart shows the wage distribution for the working population in Brazil.
                </p><p><a target='_blank' href='http://en.dataviva.info/apps/builder/bar/rais/all/all/all/bra/?controls=false&year=2013'>Explore on DataViva <i class='fa fa-external-link'></i></a>
                """)
            dv_section = {
                "title":
                u"<a href='http://dataviva.info/' target='_blank'><img src='http://en.dataviva.info/static/img/nav/DataViva.png' /></a>",
                "source":
                "dataviva",
                "builds": [
                    {
                        "title": _(u"State Exports"),
                        "iframe": dv_geo_map,
                        "subtitle": dv_geo_map_subtitle,
                        "tour":
                        "Profile pages also contain visualizations from other websites created by member of the OEC team. The following are 2 embeded visualization from DataViva, a similar visualization platorm centered around Brazilian data.",
                        "seq": 7
                    },
                    {
                        "title": _(u"Wage Distribution"),
                        "iframe": dv_wages,
                        "subtitle": dv_wages_subtitle
                    },
                ]
            }
        else:
            dv_country_id = "asrus" if self.attr.id == "eurus" else self.attr.id
            dv_munic_dest_iframe = "http://dataviva.info/apps/embed/tree_map/secex/all/all/{}/bra/?size=import_val&controls=false".format(
                dv_country_id)
            dv_munic_origin_iframe = "http://dataviva.info/apps/embed/tree_map/secex/all/all/{}/bra/?size=export_val&controls=false".format(
                dv_country_id)
            dv_munic_dest_subtitle = _(
                u"""
                This treemap shows the municipalities in Brazil that imported products from %(country)s.<br /><br />
                DataViva is a visualization tool that provides official data on trade, industries, and education throughout Brazil. If you would like more info or to create a similar site get in touch with us at <a href='mailto:[email protected]'>[email protected]</a>.
                </p><p><a target='_blank' href='http://dataviva.info/apps/builder/tree_map/secex/all/all/%(dv_country_id)s/bra/?size=import_val&controls=false'>Explore on DataViva <i class='fa fa-external-link'></i></a>
                """,
                country=self.attr.get_name(article=True),
                dv_country_id=dv_country_id)
            dv_munic_origin_subtitle = _(
                u"""
                This treemap shows the municipalities in Brazil that exported products to %(country)s.
                </p><p><a target='_blank' href='http://dataviva.info/apps/builder/tree_map/secex/all/all/%(dv_country_id)s/bra/?size=export_val&controls=false'>Explore on DataViva <i class='fa fa-external-link'></i></a>
                """,
                country=self.attr.get_name(article=True),
                dv_country_id=dv_country_id)
            dv_section = {
                "title":
                u"<a href='http://dataviva.info/' target='_blank'><img src='http://en.dataviva.info/static/img/nav/DataViva.png' /></a>",
                "source":
                "dataviva",
                "builds": [
                    {
                        "title":
                        _(u"Brazilian Municipalities that import from %(country)s",
                          country=self.attr.get_name(article=True)),
                        "iframe":
                        dv_munic_dest_iframe,
                        "subtitle":
                        dv_munic_dest_subtitle,
                        "tour":
                        "Profile pages also contain visualizations from other websites created by member of the OEC team. The following are 2 embeded visualization from DataViva, a similar visualization platorm centered around Brazilian data.",
                        "seq":
                        7
                    },
                    {
                        "title":
                        _(u"Brazilian Municipalities that export to %(country)s",
                          country=self.attr.get_name(article=True)),
                        "iframe":
                        dv_munic_origin_iframe,
                        "subtitle":
                        dv_munic_origin_subtitle
                    },
                ]
            }
        sections.append(dv_section)
        ''' Pantheon
        '''
        if self.attr.id_2char:
            pantheon_iframe_fields = "http://pantheon.media.mit.edu/treemap/country_exports/{}/all/-4000/2010/H15/pantheon/embed".format(
                self.attr.id_2char.upper())
            pantheon_link_fields = "<a target='_blank' href='http://pantheon.media.mit.edu/treemap/country_exports/{}/all/-4000/2010/H15/pantheon/'>Explore on Pantheon <i class='fa fa-external-link'></i></a>".format(
                self.attr.id_2char.upper())
            pantheon_iframe_cities = "http://pantheon.media.mit.edu/treemap/country_by_city/all/{}/-4000/2010/H15/pantheon/embed".format(
                self.attr.id_2char.upper())
            pantheon_link_cities = "<a target='_blank' href='http://pantheon.media.mit.edu/treemap/country_by_city/{}/all/-4000/2010/H15/pantheon/'>Explore on Pantheon <i class='fa fa-external-link'></i></a>".format(
                self.attr.id_2char.upper())
            pantheon_section = {
                "title":
                "<a target='_blank' href='http://pantheon.media.mit.edu'><img src='http://pantheon.media.mit.edu/pantheon_logo.png' />",
                "source":
                "pantheon",
                "builds": [
                    {
                        "title":
                        _(u"Globally Famous People %(of_country)s",
                          of_country=self.attr.get_name(article="of")),
                        "iframe":
                        pantheon_iframe_fields,
                        "subtitle":
                        _(u"This treemap shows the cultural exports %(of_country)s, as proxied by the production of globally famous historical characters.</p><p>%(pantheon_link)s",
                          of_country=self.attr.get_name(article="of"),
                          pantheon_link=pantheon_link_fields),
                        "tour":
                        "Pantheon...",
                        "seq":
                        8
                    },
                    {
                        "title":
                        _(u"Globally Famous People %(of_country)s by City",
                          of_country=self.attr.get_name(article="of")),
                        "iframe":
                        pantheon_iframe_cities,
                        "subtitle":
                        _(u"This treemap shows the cultural exports %(of_country)s by city, as proxied by the production of globally famous historical characters.</p><p>%(pantheon_link)s",
                          of_country=self.attr.get_name(article="of"),
                          pantheon_link=pantheon_link_cities)
                    },
                ]
            }
            sections.append(pantheon_section)

        return sections
示例#7
0
    def sections(self):
        sections = []
        ''' Trade Section
        '''

        if self.attr.id == "xxwld":

            export_tmap = Build("tree_map", "hs92", "export", self.attr, "all", "show", self.year)
            this_yo = self.models.Yo.query.filter_by(year = self.year).all()

            export_val = sum([o.export_val for o in this_yo])
            export_subtitle = _(u"The total world trade in %(year)s was %(export_val)s.", year=self.year, export_val=num_format(export_val, "export_val"))
            export_subtitle += u" "

            past_yr = self.year - 5
            past_yo = self.models.Yo.query.filter_by(year = past_yr).filter(self.models.Yo.export_val.isnot(None)).all()
            growth_val = median([o.export_val_growth_pct_5 for o in this_yo])
            chg = "increased" if growth_val >= 0 else "decreased"
            export_subtitle += _(u"During the last five years exports have %(increased_decreased)s at a median annualized rate of %(change_rate)s%%, from $%(past_export_val)s in %(past_year)s to $%(current_export_val)s in %(current_year)s.",
                                    increased_decreased=chg, change_rate=num_format(growth_val*100), \
                                    past_export_val=num_format(sum([o.export_val for o in past_yo])), past_year=past_yr, current_export_val=num_format(export_val), current_year=self.year)
            export_subtitle += u" "

            top_exports = self.models.Yp.query.filter_by(year = self.year, hs92_id_len=6).order_by(desc("export_val")).limit(2).all()
            export_subtitle += _(u"The most recent exports are led by %(top_export)s which represent %(top_export_pct)s%% of the total products exported, followed by %(second_export)s, which account for %(second_export_pct)s%%.",
                                    top_export=top_exports[0].product.get_profile_link(), top_export_pct=num_format((top_exports[0].export_val/export_val)*100), \
                                    second_export=top_exports[1].product.get_profile_link(), second_export_pct=num_format((top_exports[1].export_val/export_val)*100))

            origins_tmap = Build("tree_map", "hs92", "import", self.attr, "show", "all", self.year)
            yo_exp = self.models.Yo.query.filter_by(year = self.year).order_by(desc("export_val")).limit(5).all()
            origin_list = self.stringify_items(yo_exp, "export_val", "country")
            origin_subtitle = _(u"The top exporters globally are %(origins)s.", origins=origin_list)

            trade_section = {
                "builds": [
                    {"title": _(u"Exports"), "build": export_tmap, "subtitle": export_subtitle},
                    {"title": _(u"Origins"), "build": origins_tmap, "subtitle": origin_subtitle},
                ]
            }

        else:
            export_subtitle, import_subtitle, dest_subtitle, origin_subtitle = [None]*4

            export_tmap = Build("tree_map", "hs92", "export", self.attr, "all", "show", self.year)
            import_tmap = Build("tree_map", "hs92", "import", self.attr, "all", "show", self.year)

            yop_base = self.models.Yop.query.filter_by(year = self.year, origin = self.attr, hs92_id_len=6)
            # get growth
            past_yr = self.year - 5
            past_yo = self.models.Yo.query.filter_by(year = past_yr, country = self.attr).first()
            this_yo = self.models.Yo.query.filter_by(year = self.year, country = self.attr).first()
            exp_val_stat = filter(lambda s: s["key"] == "export_val", self.stats())
            if exp_val_stat and this_yo:
                exp_val_stat = exp_val_stat.pop()
                export_subtitle = ""
                if self.attr.id != "xxwld":
                    exp_rank = num_format(exp_val_stat["rank"], "ordinal") if exp_val_stat["rank"] > 1 else ""
                    export_subtitle += _(u"In %(year)s %(country)s exported $%(export_val)s, making it the %(export_rank)s largest exporter in the world.",
                                        year=self.year, country=self.attr.get_name(article=True), export_val=num_format(exp_val_stat["val"]), export_rank=exp_rank)
                    export_subtitle += u" "
                if past_yo and this_yo.export_val_growth_pct_5:
                    chg = "increased" if this_yo.export_val_growth_pct_5 >= 0 else "decreased"
                    export_subtitle += _(u"During the last five years the exports %(of_country)s have %(increased_decreased)s at an annualized rate of %(change_rate)s%%, from $%(past_export_val)s in %(past_year)s to $%(current_export_val)s in %(current_year)s.",
                                            of_country=self.attr.get_name(article="of"), increased_decreased=chg, change_rate=num_format(this_yo.export_val_growth_pct_5*100), \
                                            past_export_val=num_format(past_yo.export_val), past_year=past_yr, current_export_val=num_format(this_yo.export_val), current_year=self.year)
                    export_subtitle += u" "
                top_exports = yop_base.order_by(desc("export_val")).limit(2).all()
                if top_exports:
                    # raise Exception(top_exports[0].product.get_profile_link(), num_format((top_exports[0].export_val/exp_val_stat["val"])*100), self.attr.get_name(article="of"), top_exports[1].product.get_profile_link(), num_format((top_exports[1].export_val/exp_val_stat["val"])*100))
                    export_subtitle += _(u"The most recent exports are led by %(top_export)s which represent %(top_export_pct)s%% of the total exports %(of_country)s, followed by %(second_export)s, which account for %(second_export_pct)s%%.",
                                            top_export=top_exports[0].product.get_profile_link(), top_export_pct=num_format((top_exports[0].export_val/exp_val_stat["val"])*100), \
                                            of_country=self.attr.get_name(article="of"), second_export=top_exports[1].product.get_profile_link(), second_export_pct=num_format((top_exports[1].export_val/exp_val_stat["val"])*100))
            imp_val_stat = filter(lambda s: s["key"] == "import_val", self.stats())
            if imp_val_stat and this_yo:
                imp_val_stat = imp_val_stat.pop()
                import_subtitle = ""
                if self.attr.id != "xxwld":
                    imp_rank = num_format(imp_val_stat["rank"], "ordinal") if imp_val_stat["rank"] > 1 else ""
                    import_subtitle += _(u"In %(year)s %(country)s imported $%(import_val)s, making it the %(import_rank)s largest importer in the world.",
                                        year=self.year, country=self.attr.get_name(article=True), import_val=num_format(imp_val_stat["val"]), import_rank=imp_rank)
                    import_subtitle += u" "
                if past_yo and this_yo.import_val_growth_pct_5:
                    chg = "increased" if this_yo.import_val_growth_pct_5 >= 0 else "decreased"
                    import_subtitle += _(u"During the last five years the imports %(of_country)s have %(increased_decreased)s at an annualized rate of %(change_rate)s%%, from $%(past_import_val)s in %(past_year)s to $%(current_import_val)s in %(current_year)s.",
                                            of_country=self.attr.get_name(article="of"), increased_decreased=chg, change_rate=num_format(this_yo.import_val_growth_pct_5*100), \
                                            past_import_val=num_format(past_yo.import_val), past_year=past_yr, current_import_val=num_format(this_yo.import_val), current_year=self.year)
                    import_subtitle += u" "
                top_imports = yop_base.order_by(desc("import_val")).limit(2).all()
                if top_imports:
                    import_subtitle += _(u"The most recent imports are led by %(top_import)s which represent %(top_import_pct)s%% of the total imports %(of_country)s, followed by %(second_import)s, which account for %(second_import_pct)s%%.",
                                            top_import=top_imports[0].product.get_profile_link(), top_import_pct=num_format((top_imports[0].import_val/imp_val_stat["val"])*100), \
                                            of_country=self.attr.get_name(article="of"), second_import=top_imports[1].product.get_profile_link(), second_import_pct=num_format((top_imports[1].import_val/imp_val_stat["val"])*100))

            dests_tmap = Build("tree_map", "hs92", "export", self.attr, "show", "all", self.year)
            yod_exp = self.models.Yod.query.filter_by(year = self.year, origin = self.attr).order_by(desc("export_val")).limit(5).all()
            if yod_exp:
                dest_list = self.stringify_items(yod_exp, "export_val", "dest")
                dest_subtitle = _(u"The top export destinations %(of_country)s are %(destinations)s.", of_country=self.attr.get_name(article="of"), destinations=dest_list)

            origins_tmap = Build("tree_map", "hs92", "import", self.attr, "show", "all", self.year)
            yod_imp = self.models.Yod.query.filter_by(year = self.year, dest = self.attr).order_by(desc("export_val")).limit(5).all()
            if yod_imp:
                origin_list = self.stringify_items(yod_imp, "export_val", "origin")
                origin_subtitle = _(u"The top import origins %(of_country)s are %(origins)s.", of_country=self.attr.get_name(article="of"), origins=origin_list)

            # trade balance viz --
            first_yo = self.models.Yo.query.filter_by(year = available_years["hs92"][-1], country = self.attr).first()
            tb_subtitle = ""
            tb_build = Build("line", "hs92", "show", self.attr, "all", "all", available_years["hs92"])
            if first_yo:
                net_trade = this_yo.export_val - this_yo.import_val
                trade_balance = _("positive") if net_trade >= 0 else _("negative")
                trade_direction = _("exports") if net_trade >= 0 else _("imports")
                tb_subtitle = _(u"As of %(year)s %(country)s had a %(positive_negative)s trade balance of $%(net_trade)s in net %(exports_imports)s.",
                                year=self.year, country=self.attr.get_name(article=True), positive_negative=trade_balance, net_trade=num_format(abs(net_trade)), exports_imports=trade_direction)
                old_yo = self.models.Yo.query.filter_by(year = available_years["hs92"][0], country = self.attr).first()
                if old_yo:
                    old_net_trade = old_yo.export_val - old_yo.import_val
                    old_trade_balance = _("positive") if old_net_trade >= 0 else _("negative")
                    old_trade_direction = _("exports") if old_net_trade >= 0 else _("imports")
                    is_diff = True if old_trade_balance != trade_balance else False
                    still_or_not = _("still") if old_trade_balance == trade_balance else ""
                    tb_subtitle += u" "
                    tb_subtitle += _(u"As compared to their trade balance in %(year)s when they %(still)s had a %(positive_negative)s trade balance of $%(net_trade)s in net %(exports_imports)s.",
                                    year=available_years["hs92"][0], still=still_or_not, positive_negative=old_trade_balance, net_trade=num_format(abs(old_net_trade)), exports_imports=old_trade_direction)

            trade_section = {
                "builds": [
                    {"title": _(u"Exports"), "build": export_tmap, "subtitle": export_subtitle, "tour":"This is just a test", "seq":5},
                    {"title": _(u"Imports"), "build": import_tmap, "subtitle": import_subtitle},
                    {"title": _(u"Trade Balance"), "build": tb_build, "subtitle": tb_subtitle},
                    {"title": _(u"Destinations"), "build": dests_tmap, "subtitle": dest_subtitle},
                    {"title": _(u"Origins"), "build": origins_tmap, "subtitle": origin_subtitle},
                ]
            }

        sections.append(trade_section)

        ''' Product Space Section
        '''
        subtitle = False
        if self.attr.id != "xxwld":
            num_exports_w_rca = db.session.query(func.count(self.models.Yop.hs92_id)) \
                        .filter_by(year = self.year, origin = self.attr) \
                        .filter(self.models.Yop.export_rca >= 1) \
                        .filter(func.char_length(self.models.Yop.hs92_id)==6) \
                        .scalar()
            this_attr_yo = attrs.Yo.query.filter_by(year = self.year, country = self.attr).first()
            if this_attr_yo:
                eci = this_attr_yo.eci
                eci_rank = this_attr_yo.eci_rank
                if eci_rank:
                    subtitle = _(u"The economy %(of_country)s has an Economic Complexity Index (ECI) of %(eci)s making it the %(eci_rank)s most complex country.",
                                of_country=self.attr.get_name(article="of"), eci=num_format(eci), eci_rank=num_format(eci_rank, "ordinal"))
                    subtitle += u" "
                else:
                    subtitle = ""
                subtitle += _(u"%(country)s exports %(num_of_exports)s products with revealed comparative advantage " \
                    u"(meaning that its share of global exports is larger than what " \
                    u"would be expected from the size of its export economy " \
                    u"and from the size of a product’s global market).",
                    country=self.attr.get_name(article=True), num_of_exports=num_exports_w_rca)
        product_space = Build("network", "hs92", "export", self.attr, "all", "show", self.year)
        ps_text = _(u"The product space is a network connecting products that are likely to be co-exported and can be used to predict the evolution of a country’s export structure.")
        if subtitle:
            ps_text = u"{}</p><p>{}".format(ps_text, subtitle)
        ps_section = {
            "title": _(u"Economic Complexity %(of_country)s", of_country=self.attr.get_name(article="of")),
            "builds": [
                {"title": _(u"Product Space"), "build": product_space, "subtitle": ps_text, "tour":"The product space...", "seq":6}
            ]
        }

        ''' PGI Section
        '''
        if self.attr.id != "xxwld":
            pgi_product_space = Build("network", "sitc", "pgi", self.attr, "all", "show", available_years["sitc"][-1])
            subtitle = _("In this version of the product space products are colored according to their Product Gini Index, or PGI. The PGI of a product is the level of income inequality that we expect for the countries that export a product. For more information see: %(paper1)s and %(paper2)s.", country=self.attr.get_name(article=True), paper1="<a target='_blank' href='https://arxiv.org/abs/1505.07907'>Linking Economic Complexity, Institutions and Income Inequality</a>", paper2="<a target='_blank' href='https://arxiv.org/abs/1701.03770'>The structural constraints of income inequality in Latin America</a>")
            ps_section["builds"].append({"title": _(u"Complexity and Income Inequality"), "build": pgi_product_space, "subtitle": subtitle})

        ''' ECI Ranking Section
        '''
        if self.attr.id == "xxwld":
            line_rankings = Build("line", "sitc", "eci", "show", "all", "all", [y for y in available_years["sitc"] if y >= 1964])
            start_year = 1980
            start_year = max(1964, start_year) if start_year != 1980 else 1964
            year_range = self.year - start_year
            subtitle = _("The Economic Complexity of each country visualized over the past %(year_range)s years.", year_range=year_range)
            ps_section["builds"].append({"title": _(u"Economic Complexity Ranking"), "build": line_rankings, "subtitle": subtitle})

        elif this_attr_yo and this_attr_yo.eci != None:
            line_rankings = Build("line", "sitc", "eci", "show", self.attr, "all", [y for y in available_years["sitc"] if y >= 1964])
            start_year = earliest_data.get(self.attr.id, 1980)
            start_year = max(1964, start_year) if start_year != 1980 else 1964
            year_range = self.year - start_year

            attr_yo_historic = attrs.Yo.query.filter_by(country=self.attr).filter(attrs.Yo.year == start_year).first()
            if attr_yo_historic and attr_yo_historic.eci_rank != None and this_attr_yo.eci_rank != None:
                eci_delta = this_attr_yo.eci_rank - attr_yo_historic.eci_rank
                inc_dec = _('increased') if eci_delta < 0 else _('decreased')
                subtitle = _("The Economic Complexity ranking %(of_country)s has %(increased_or_decreased)s by %(rank_delta)s places over the past %(year_range)s years from %(old_eci)s in %(old_year)s to %(current_eci)s in %(current_year)s.",
                    of_country=self.attr.get_name(article="of"), increased_or_decreased=inc_dec,
                    rank_delta=abs(eci_delta), year_range=year_range, old_eci=num_format(attr_yo_historic.eci_rank, "ordinal"),
                    old_year=start_year, current_eci=num_format(this_attr_yo.eci_rank, "ordinal"), current_year=self.year)
            ps_section["builds"].append({"title": _(u"Economic Complexity Ranking"), "build": line_rankings, "subtitle": subtitle})
        sections.append(ps_section)

        sections.append({
            "title": _(u"More on %(country)s from our other sites", country=self.attr.get_name(article=True)),
            "source": "sisters"
        })

        ''' DataViva
        '''
        # dv_section = make_dv_section(self)
        # sections.append(dv_section)

        ''' Data USA
        '''
        if self.attr.id == "nausa":
            us_section = make_us_section()
            sections.append(us_section)

        ''' Data Africa
        '''
        if any(country[0] == self.attr.id for country in data_africa_countries):
            da_country = filter(lambda x:x[0]==self.attr.id, data_africa_countries)
            africa_section = make_africa_section(self, da_country[0])
            sections.append(africa_section)
            # raise Exception("found dataafrican country: {}".format(da_country[0]))

        ''' Pantheon
        '''
        pantheon_id = "all" if self.attr.id == "xxwld" else self.attr.id_2char
        if pantheon_id:
            if self.attr.id != "xxwld":
                pantheon_id = pantheon_id.upper()

            pantheon_section = make_pantheon_section(pantheon_id, self.attr)
            sections.append(pantheon_section)

        return sections