<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>Luis José Zapata Blog</title><link>https://luis-zapatabobadilla.netlify.app/</link><atom:link href="https://luis-zapatabobadilla.netlify.app/index.xml" rel="self" type="application/rss+xml"/><description>Luis José Zapata Blog</description><generator>Wowchemy (https://wowchemy.com)</generator><language>en-us</language><lastBuildDate>Wed, 12 Mar 2025 00:00:00 +0000</lastBuildDate><image><url>https://luis-zapatabobadilla.netlify.app/media/icon_hud7092cb2ef3850b88d56971ecbc6aabf_452_512x512_fill_lanczos_center_2.png</url><title>Luis José Zapata Blog</title><link>https://luis-zapatabobadilla.netlify.app/</link></image><item><title>Python basics</title><link>https://luis-zapatabobadilla.netlify.app/courses/example/python/</link><pubDate>Fri, 01 Jan 2021 00:00:00 +0000</pubDate><guid>https://luis-zapatabobadilla.netlify.app/courses/example/python/</guid><description>&lt;p>Build a foundation in Python.&lt;/p>
&lt;p>
&lt;i class="fas fa-clock pr-1 fa-fw">&lt;/i> 1-2 hours per week, for 8 weeks&lt;/p>
&lt;h2 id="learn">Learn&lt;/h2>
&lt;div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;">
&lt;iframe src="https://www.youtube.com/embed/rfscVS0vtbw" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border:0;" allowfullscreen title="YouTube Video">&lt;/iframe>
&lt;/div>
&lt;h2 id="quiz">Quiz&lt;/h2>
&lt;details class="spoiler " id="spoiler-2">
&lt;summary>What is the difference between lists and tuples?&lt;/summary>
&lt;p>&lt;p>Lists&lt;/p>
&lt;ul>
&lt;li>Lists are mutable - they can be changed&lt;/li>
&lt;li>Slower than tuples&lt;/li>
&lt;li>Syntax: &lt;code>a_list = [1, 2.0, 'Hello world']&lt;/code>&lt;/li>
&lt;/ul>
&lt;p>Tuples&lt;/p>
&lt;ul>
&lt;li>Tuples are immutable - they can&amp;rsquo;t be changed&lt;/li>
&lt;li>Tuples are faster than lists&lt;/li>
&lt;li>Syntax: &lt;code>a_tuple = (1, 2.0, 'Hello world')&lt;/code>&lt;/li>
&lt;/ul>
&lt;/p>
&lt;/details>
&lt;details class="spoiler " id="spoiler-3">
&lt;summary>Is Python case-sensitive?&lt;/summary>
&lt;p>Yes&lt;/p>
&lt;/details></description></item><item><title>Visualization</title><link>https://luis-zapatabobadilla.netlify.app/courses/example/visualization/</link><pubDate>Fri, 01 Jan 2021 00:00:00 +0000</pubDate><guid>https://luis-zapatabobadilla.netlify.app/courses/example/visualization/</guid><description>&lt;p>Learn how to visualize data with Plotly.&lt;/p>
&lt;p>
&lt;i class="fas fa-clock pr-1 fa-fw">&lt;/i> 1-2 hours per week, for 8 weeks&lt;/p>
&lt;h2 id="learn">Learn&lt;/h2>
&lt;div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;">
&lt;iframe src="https://www.youtube.com/embed/hSPmj7mK6ng" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border:0;" allowfullscreen title="YouTube Video">&lt;/iframe>
&lt;/div>
&lt;h2 id="quiz">Quiz&lt;/h2>
&lt;details class="spoiler " id="spoiler-2">
&lt;summary>When is a heatmap useful?&lt;/summary>
&lt;p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.&lt;/p>
&lt;/details>
&lt;details class="spoiler " id="spoiler-3">
&lt;summary>Write Plotly code to render a bar chart&lt;/summary>
&lt;p>&lt;pre>&lt;code class="language-python">import plotly.express as px
data_canada = px.data.gapminder().query(&amp;quot;country == 'Canada'&amp;quot;)
fig = px.bar(data_canada, x='year', y='pop')
fig.show()
&lt;/code>&lt;/pre>
&lt;/p>
&lt;/details></description></item><item><title>Statistics</title><link>https://luis-zapatabobadilla.netlify.app/courses/example/stats/</link><pubDate>Fri, 01 Jan 2021 00:00:00 +0000</pubDate><guid>https://luis-zapatabobadilla.netlify.app/courses/example/stats/</guid><description>&lt;p>Introduction to statistics for data science.&lt;/p>
&lt;p>
&lt;i class="fas fa-clock pr-1 fa-fw">&lt;/i> 1-2 hours per week, for 8 weeks&lt;/p>
&lt;h2 id="learn">Learn&lt;/h2>
&lt;p>The general form of the &lt;strong>normal&lt;/strong> probability density function is:&lt;/p>
&lt;p>$$
f(x) = \frac{1}{\sigma \sqrt{2\pi} } e^{-\frac{1}{2}\left(\frac{x-\mu}{\sigma}\right)^2}
$$&lt;/p>
&lt;div class="alert alert-note">
&lt;div>
The parameter $\mu$ is the mean or expectation of the distribution.
$\sigma$ is its standard deviation.
The variance of the distribution is $\sigma^{2}$.
&lt;/div>
&lt;/div>
&lt;h2 id="quiz">Quiz&lt;/h2>
&lt;details class="spoiler " id="spoiler-2">
&lt;summary>What is the parameter $\mu$?&lt;/summary>
&lt;p>The parameter $\mu$ is the mean or expectation of the distribution.&lt;/p>
&lt;/details></description></item><item><title>Using Python, SerpAPI, and GPT to Build a Smart Web Search Analyzer</title><link>https://luis-zapatabobadilla.netlify.app/project/openai-gpt-web-search-analyzer/</link><pubDate>Wed, 12 Mar 2025 00:00:00 +0000</pubDate><guid>https://luis-zapatabobadilla.netlify.app/project/openai-gpt-web-search-analyzer/</guid><description>&lt;h1 id="introduction">Introduction&lt;/h1>
&lt;p>In this blog post, I&amp;rsquo;ll walk through how to use modern tools like Python, SerpAPI, and OpenAI&amp;rsquo;s GPT models to build a modular search pipeline. The idea is to scrape Google Search results programmatically, analyze them using LLMs, and extract structured insights.&lt;/p>
&lt;h2 id="what-are-apis-and-why-are-we-using-them">What Are APIs, and Why Are We Using Them?&lt;/h2>
&lt;p>APIs (Application Programming Interfaces) are like bridges that allow one software to talk to another in a standardized way. Instead of building a search engine or a language model from scratch, developers can connect to existing services using APIs to request data, process information, or trigger tasks.&lt;/p>
&lt;p>In this project, we rely on two APIs:&lt;/p>
&lt;ul>
&lt;li>&lt;strong>SerpAPI&lt;/strong>: This is a powerful tool that lets us programmatically fetch Google search results. Instead of scraping raw HTML and fighting with unpredictable webpage structures, SerpAPI gives us clean, structured JSON data for any Google query &amp;mdash; including titles, URLs, and summaries.&lt;/li>
&lt;li>&lt;strong>OpenAI API&lt;/strong>: This allows us to access large language models (like GPT-4o) via code. By sending a structured prompt and some example text to OpenAI&amp;rsquo;s API, we receive intelligent summaries, classifications, or decisions in return &amp;mdash; perfect for analyzing search results at scale.&lt;/li>
&lt;/ul>
&lt;p>Together, these APIs let us build a small but powerful pipeline: search → filter → analyze &amp;mdash; all from Python.&lt;/p>
&lt;p>To keep things simple and general, our example will revolve around analyzing search results related to &lt;strong>shoes&lt;/strong>, rather than any specialized domain, but this project can easily be adapted to any other complex topic.&lt;/p>
&lt;p>We&amp;rsquo;ll break the process into four key parts:&lt;/p>
&lt;ol>
&lt;li>Fetching Google results using SerpAPI&lt;/li>
&lt;li>Cleaning and organizing the raw data&lt;/li>
&lt;li>Using GPT to extract structured insight from results&lt;/li>
&lt;li>Putting everything together in one function&lt;/li>
&lt;/ol>
&lt;h2 id="step-1-fetch-google-results-using-serpapi">Step 1: Fetch Google Results Using SerpAPI&lt;/h2>
&lt;p>We&amp;rsquo;ll start by querying SerpAPI. &lt;strong>SerpAPI&lt;/strong> is a commercial API that allows developers to access real-time, structured Google search results without the hassle of traditional web scraping. In this blog, SerpAPI is used to automate the collection of search result data for a given keyword or product &amp;mdash; for example, &amp;ldquo;shoes with waterproof soles&amp;rdquo; or &amp;ldquo;trail running sneakers.&amp;rdquo; Instead of manually performing searches and copying links, we send queries through SerpAPI and receive a JSON response containing the search titles, URLs, summaries, and even metadata like the publication date. This structured output is the foundation of our analysis pipeline, feeding directly into the next steps where we clean the data and evaluate relevance using language models.&lt;/p>
&lt;p>First, we&amp;rsquo;ll need a &lt;a href="https://serpapi.com/" target="_blank" rel="noopener">SerpAPI API key&lt;/a>.&lt;/p>
&lt;pre>&lt;code class="language-python">import requests
def fetch_google_results(query, api_key, start=0, num=10):
params = {
&amp;quot;q&amp;quot;: query,
&amp;quot;location&amp;quot;: &amp;quot;Los Angeles, California, United States&amp;quot;,
&amp;quot;start&amp;quot;: start,
&amp;quot;num&amp;quot;: num,
&amp;quot;hl&amp;quot;: &amp;quot;en&amp;quot;,
&amp;quot;gl&amp;quot;: &amp;quot;us&amp;quot;,
&amp;quot;engine&amp;quot;: &amp;quot;google&amp;quot;,
&amp;quot;api_key&amp;quot;: api_key
}
response = requests.get(&amp;quot;https://serpapi.com/search&amp;quot;, params=params)
results = response.json().get(&amp;quot;organic_results&amp;quot;, [])
return results
&lt;/code>&lt;/pre>
&lt;p>Example:&lt;/p>
&lt;pre>&lt;code class="language-python">import pandas as pd
serpapi_key = serapi_code
results = fetch_google_results(&amp;quot;best running shoes 2024&amp;quot;, serpapi_key)
print(pd.DataFrame(results).head())
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## position ... rich_snippet
## 0 1 ... NaN
## 1 2 ... NaN
## 2 3 ... NaN
## 3 4 ... NaN
## 4 5 ... NaN
##
## [5 rows x 13 columns]
&lt;/code>&lt;/pre>
&lt;p>Keep in mind that SerpAPI offers 100 free requests per month. If your project requires more extensive usage, you&amp;rsquo;ll need to upgrade to a paid plan. Additionally, SerpAPI supports other search engines (like Bing, DuckDuckGo, YouTube, and more), so you can adapt the same API logic to different platforms if needed.&lt;/p>
&lt;h2 id="step-2-clean-and-organize-the-raw-data">Step 2: Clean and Organize the Raw Data&lt;/h2>
&lt;p>Once we have the raw search results, we want to extract important fields and handle possible issues like missing data.&lt;/p>
&lt;pre>&lt;code class="language-python">import pandas as pd
import datetime
def clean_results(raw_results):
df = pd.DataFrame(raw_results)
df = df[[&amp;quot;position&amp;quot;, &amp;quot;title&amp;quot;, &amp;quot;link&amp;quot;, &amp;quot;snippet&amp;quot;]].rename(
columns={
&amp;quot;position&amp;quot;: &amp;quot;Rank&amp;quot;,
&amp;quot;title&amp;quot;: &amp;quot;Title&amp;quot;,
&amp;quot;link&amp;quot;: &amp;quot;URL&amp;quot;,
&amp;quot;snippet&amp;quot;: &amp;quot;Summary&amp;quot;
}
)
df[&amp;quot;Scrape Date&amp;quot;] = datetime.date.today().strftime(&amp;quot;%Y-%m-%d&amp;quot;)
return df
&lt;/code>&lt;/pre>
&lt;p>Example:&lt;/p>
&lt;pre>&lt;code class="language-python">df_cleaned = clean_results(results)
df_cleaned.head()
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## Rank ... Scrape Date
## 0 1 ... 2025-04-12
## 1 2 ... 2025-04-12
## 2 3 ... 2025-04-12
## 3 4 ... 2025-04-12
## 4 5 ... 2025-04-12
##
## [5 rows x 5 columns]
&lt;/code>&lt;/pre>
&lt;h2 id="step-3-use-gpt-to-analyze-the-results">Step 3: Use GPT to Analyze the Results&lt;/h2>
&lt;p>&lt;strong>OpenAI&amp;rsquo;s API&lt;/strong> provides access to advanced language models like GPT-4, which can process and understand natural language. In this project, we use the &lt;strong>Chat Completion API&lt;/strong> to enhance our search pipeline by analyzing each result retrieved from Google. For every link found, we prompt GPT to generate a &lt;strong>brief summary&lt;/strong> of the content and assign a &lt;strong>probability score&lt;/strong> that estimates how likely the link is to contain &lt;strong>useful shopping-related information&lt;/strong> &amp;mdash; such as detailed product reviews, buying guides, or comparisons. This allows us to automatically prioritize the most informative links without manual filtering, making it easier to identify high-value content in large batches of search results.&lt;/p>
&lt;pre>&lt;code class="language-python">from openai import OpenAI
import json
import time
client = OpenAI(api_key=openai_code)
def query_openai(df, keyword):
json_data = df[[&amp;quot;Rank&amp;quot;, &amp;quot;Title&amp;quot;, &amp;quot;URL&amp;quot;, &amp;quot;Summary&amp;quot;]].to_dict(orient=&amp;quot;records&amp;quot;)
prompt = f&amp;quot;&amp;quot;&amp;quot; You are an AI assistant helping to analyze search engine results for consumer products. Analyze the following JSON search results from Google. For each result, please:
1. Provide a short summary (max 150 characters) of the result.
2. Estimate the probability (from 0 to 1) that the result contains useful information such as reviews, comparisons, product specs, or guides relevant to the keyword '{keyword}'.
Return a JSON list under the key &amp;quot;results&amp;quot; with these fields:
- Rank
- URL
- Probability
- GPT_Summary
Ensure that the number of output rows matches the number of input rows. If any row has no relevant information, still return it with a low Probability.
####
Data:
{json.dumps(json_data, indent=2)}
####
&amp;quot;&amp;quot;&amp;quot;
response = client.chat.completions.create(
model=&amp;quot;gpt-4o&amp;quot;,
messages=[
{&amp;quot;role&amp;quot;: &amp;quot;system&amp;quot;, &amp;quot;content&amp;quot;: &amp;quot;You are an AI summarizer and classifier of search engine results.&amp;quot;},
{&amp;quot;role&amp;quot;: &amp;quot;user&amp;quot;, &amp;quot;content&amp;quot;: prompt}
],
response_format={
&amp;quot;type&amp;quot;: &amp;quot;json_schema&amp;quot;,
&amp;quot;json_schema&amp;quot;: {
&amp;quot;name&amp;quot;: &amp;quot;SearchEvaluation&amp;quot;,
&amp;quot;schema&amp;quot;: {
&amp;quot;type&amp;quot;: &amp;quot;object&amp;quot;,
&amp;quot;properties&amp;quot;: {
&amp;quot;Rank&amp;quot;: {&amp;quot;type&amp;quot;: &amp;quot;integer&amp;quot;},
&amp;quot;URL&amp;quot;: {&amp;quot;type&amp;quot;: &amp;quot;string&amp;quot;},
&amp;quot;Probability&amp;quot;: {&amp;quot;type&amp;quot;: &amp;quot;number&amp;quot;},
&amp;quot;GPT_Summary&amp;quot;: {&amp;quot;type&amp;quot;: &amp;quot;string&amp;quot;}
},
&amp;quot;required&amp;quot;: [
&amp;quot;Rank&amp;quot;,
&amp;quot;URL&amp;quot;,
&amp;quot;Probability&amp;quot;,
&amp;quot;GPT_Summary&amp;quot;
]
}
}
}
)
return json.loads(response.choices[0].message.content)[&amp;quot;results&amp;quot;]
&lt;/code>&lt;/pre>
&lt;p>We use the response_format option to ensure the output is returned as a structured JSON object, making parsing and downstream processing much easier. Be aware that the OpenAI API has usage quotas and token limits that depend on your subscription tier and the model in use. Occasionally, the API may experience outages or degraded performance &amp;mdash; always check OpenAI&amp;rsquo;s status page or the official documentation if things go wrong. For this project, we use the gpt-4o model, which offers faster responses and lower cost per token. Keep in mind that token limits and output behavior can vary across different models and versions.&lt;/p>
&lt;h2 id="step-4-full-pipeline-example">Step 4: Full Pipeline Example&lt;/h2>
&lt;p>Now let&amp;rsquo;s combine everything into one pipeline and try it out:&lt;/p>
&lt;pre>&lt;code class="language-python">query = &amp;quot;best waterproof trail running shoes&amp;quot;
raw = fetch_google_results(query, serpapi_key)
df = clean_results(raw)
response = query_openai(df, keyword=&amp;quot;trail running shoes&amp;quot;)
print(pd.DataFrame(response).head())
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## Rank ... GPT_Summary
## 0 1 ... Guide on top waterproof trail running shoes.
## 1 2 ... Listing of waterproof trail running shoes at REI.
## 2 3 ... Reddit discussion on waterproof trail running ...
## 3 4 ... Review of best waterproof trail running shoes ...
## 4 5 ... Tested reviews of top trail running shoes for ...
##
## [5 rows x 4 columns]
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">if response:
df_scores = pd.DataFrame(response)
final_df = pd.merge(df, df_scores, on=[&amp;quot;Rank&amp;quot;, &amp;quot;URL&amp;quot;],how=&amp;quot;inner&amp;quot;)
print(final_df[[&amp;quot;Rank&amp;quot;, &amp;quot;Title&amp;quot;, &amp;quot;Probability&amp;quot;,&amp;quot;GPT_Summary&amp;quot;]].head())
else:
print(&amp;quot;GPT analysis failed.&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## Rank ... GPT_Summary
## 0 1 ... Guide on top waterproof trail running shoes.
## 1 2 ... Listing of waterproof trail running shoes at REI.
## 2 3 ... Reddit discussion on waterproof trail running ...
## 3 4 ... Review of best waterproof trail running shoes ...
## 4 5 ... Tested reviews of top trail running shoes for ...
##
## [5 rows x 4 columns]
&lt;/code>&lt;/pre>
&lt;p>Im only going to use R for the final table, but you can use any other language to do it.&lt;/p>
&lt;pre>&lt;code class="language-r">knitr::kable(
py$final_df[, c(&amp;quot;Rank&amp;quot;, &amp;quot;URL&amp;quot;,&amp;quot;Title&amp;quot;, &amp;quot;Probability&amp;quot;, &amp;quot;GPT_Summary&amp;quot;)],
format = &amp;quot;html&amp;quot;,
caption = &amp;quot;GPT Analysis of Search Results&amp;quot;
)
&lt;/code>&lt;/pre>
&lt;table>
&lt;caption>&lt;span id="tab:unnamed-chunk-7">&lt;/span>Table 1: GPT Analysis of Search Results&lt;/caption>
&lt;thead>
&lt;tr>
&lt;th style="text-align:right;"> Rank &lt;/th>
&lt;th style="text-align:left;"> URL &lt;/th>
&lt;th style="text-align:left;"> Title &lt;/th>
&lt;th style="text-align:right;"> Probability &lt;/th>
&lt;th style="text-align:left;"> GPT_Summary &lt;/th>
&lt;/tr>
&lt;/thead>
&lt;tbody>
&lt;tr>
&lt;td style="text-align:right;"> 1 &lt;/td>
&lt;td style="text-align:left;"> https://runrepeat.com/guides/best-trail-waterproof-running-shoes &lt;/td>
&lt;td style="text-align:left;"> 7 Best Waterproof Trail Running Shoes in 2025 &lt;/td>
&lt;td style="text-align:right;"> 0.95 &lt;/td>
&lt;td style="text-align:left;"> Guide on top waterproof trail running shoes. &lt;/td>
&lt;/tr>
&lt;tr>
&lt;td style="text-align:right;"> 2 &lt;/td>
&lt;td style="text-align:left;"> https://www.rei.com/c/trail-running-shoes/f/f-waterproof &lt;/td>
&lt;td style="text-align:left;"> Waterproof Trail-Running Shoes | REI Co-op &lt;/td>
&lt;td style="text-align:right;"> 0.90 &lt;/td>
&lt;td style="text-align:left;"> Listing of waterproof trail running shoes at REI. &lt;/td>
&lt;/tr>
&lt;tr>
&lt;td style="text-align:right;"> 3 &lt;/td>
&lt;td style="text-align:left;"> https://www.reddit.com/r/trailrunning/comments/1adsza0/need_some_recommendations_for_waterproof_running/ &lt;/td>
&lt;td style="text-align:left;"> Need some recommendations for waterproof running ... &lt;/td>
&lt;td style="text-align:right;"> 0.75 &lt;/td>
&lt;td style="text-align:left;"> Reddit discussion on waterproof trail running shoe recommendations. &lt;/td>
&lt;/tr>
&lt;tr>
&lt;td style="text-align:right;"> 4 &lt;/td>
&lt;td style="text-align:left;"> https://www.livefortheoutdoors.com/trail-running/shoes/best-waterproof-trail-running-shoes/ &lt;/td>
&lt;td style="text-align:left;"> Best waterproof trail running shoes for 2025 | Tested and ... &lt;/td>
&lt;td style="text-align:right;"> 0.95 &lt;/td>
&lt;td style="text-align:left;"> Review of best waterproof trail running shoes for 2025. &lt;/td>
&lt;/tr>
&lt;tr>
&lt;td style="text-align:right;"> 5 &lt;/td>
&lt;td style="text-align:left;"> https://www.outdoorgearlab.com/topics/shoes-and-boots/best-trail-running-shoes-womens &lt;/td>
&lt;td style="text-align:left;"> The 9 Best Trail Running Shoes for Women | Tested &lt;/td>
&lt;td style="text-align:right;"> 0.85 &lt;/td>
&lt;td style="text-align:left;"> Tested reviews of top trail running shoes for women. &lt;/td>
&lt;/tr>
&lt;tr>
&lt;td style="text-align:right;"> 6 &lt;/td>
&lt;td style="text-align:left;"> https://www.brooksrunning.com/en_us/mens/shoes/trail-shoes/?srsltid=AfmBOoow-beP7iwwQgxtcrDarJJkMzB4EGLSRJQnxacCDaeJa8C2rU-a &lt;/td>
&lt;td style="text-align:left;"> Men's Trail Running Shoes &lt;/td>
&lt;td style="text-align:right;"> 0.80 &lt;/td>
&lt;td style="text-align:left;"> Brooks' men's trail shoes with GORE-TEX options. &lt;/td>
&lt;/tr>
&lt;tr>
&lt;td style="text-align:right;"> 7 &lt;/td>
&lt;td style="text-align:left;"> https://www.rei.com/learn/expert-advice/should-you-get-waterproof-trail-running-shoes.html &lt;/td>
&lt;td style="text-align:left;"> Should I Get Waterproof Trail-Running Shoes &lt;/td>
&lt;td style="text-align:right;"> 0.90 &lt;/td>
&lt;td style="text-align:left;"> Guide on deciding to purchase waterproof trail running shoes. &lt;/td>
&lt;/tr>
&lt;tr>
&lt;td style="text-align:right;"> 8 &lt;/td>
&lt;td style="text-align:left;"> https://www.trailandkale.com/roundups/best-trail-running-shoes-buyers-guide/ &lt;/td>
&lt;td style="text-align:left;"> The Best Trail Running Shoes In 2025 [Tried And Tested] &lt;/td>
&lt;td style="text-align:right;"> 0.95 &lt;/td>
&lt;td style="text-align:left;"> Comprehensive guide to best trail running shoes. &lt;/td>
&lt;/tr>
&lt;tr>
&lt;td style="text-align:right;"> 9 &lt;/td>
&lt;td style="text-align:left;"> https://singletrackworld.com/forum/off-topic/waterproof-trail-running-shoes-yay-or-nay/ &lt;/td>
&lt;td style="text-align:left;"> Waterproof trail running shoes – Yay or nay? – Chat Forum &lt;/td>
&lt;td style="text-align:right;"> 0.70 &lt;/td>
&lt;td style="text-align:left;"> User opinions on waterproof trail shoes in forum. &lt;/td>
&lt;/tr>
&lt;tr>
&lt;td style="text-align:right;"> 10 &lt;/td>
&lt;td style="text-align:left;"> https://lifehacker.com/health/waterproof-running-shoes-are-game-changer &lt;/td>
&lt;td style="text-align:left;"> I'm a Runner, and These Water-Resistant Running Shoes ... &lt;/td>
&lt;td style="text-align:right;"> 0.80 &lt;/td>
&lt;td style="text-align:left;"> Review of water-resistant running shoes for runners. &lt;/td>
&lt;/tr>
&lt;/tbody>
&lt;/table>
&lt;h1 id="conclusion">Conclusion&lt;/h1>
&lt;p>In this post, we built a modular and extensible web search analyzer using Python, SerpAPI, and OpenAI&amp;rsquo;s GPT. We demonstrated how to automatically retrieve search results, clean and structure the data, and use a large language model to generate useful summaries and rank the most relevant links based on probabilistic reasoning.&lt;/p>
&lt;p>This framework is highly adaptable:&lt;/p>
&lt;ul>
&lt;li>You can modify the &lt;strong>SerpAPI parameters&lt;/strong> to target different locations, languages, or result depths.&lt;/li>
&lt;li>You can enhance the &lt;strong>GPT prompt&lt;/strong> to fit specific domains &amp;mdash; whether it&amp;rsquo;s shopping, education, or scientific research.&lt;/li>
&lt;li>The structured outputs can be stored in CSVs, Excel files, or databases for further visualization or batch processing.&lt;/li>
&lt;li>You can even integrate this pipeline into larger workflows, such as product monitoring, competitive analysis, or content recommendation engines.&lt;/li>
&lt;/ul>
&lt;p>By abstracting complexity through APIs and combining them with thoughtful logic in Python, we enable powerful automation with very little code. This project is a good example of how language models and APIs can work together to extract meaning and prioritize knowledge at scale &amp;mdash; without writing a single web scraper.&lt;/p>
&lt;p>Happy exploring!&lt;/p></description></item><item><title>An Introduction to Regression Discontinuity Design (RDD)</title><link>https://luis-zapatabobadilla.netlify.app/project/regression-discontinuity-design-rdd/</link><pubDate>Thu, 06 Feb 2025 00:00:00 +0000</pubDate><guid>https://luis-zapatabobadilla.netlify.app/project/regression-discontinuity-design-rdd/</guid><description>&lt;h1 id="introduction">Introduction&lt;/h1>
&lt;p>Have you ever wondered how a government might evaluate the impact of a new scholarship program that only kicks in when a student’s GPA exceeds a specific threshold? Or how a policy change affecting tax rates for households above a certain income level actually influences economic behavior? These are just a couple of scenarios where Regression Discontinuity Design (RDD) comes into play—a powerful tool for causal inference when treatment assignment hinges on a cutoff.&lt;/p>
&lt;p>In this blog post, we’ll explore RDD by building a local linear regression from the ground up—no magic packages or black-box functions here! Instead, we’ll simulate data that features a clear jump at a predetermined cutoff and then walk through the entire estimation process step by step. You’ll see exactly how the treatment effect is estimated right at the threshold and how the confidence interval is constructed to quantify uncertainty.&lt;/p>
&lt;p>By starting from zero, we aim to demystify the inner workings of RDD, ensuring that you not only learn how to implement it but also understand the underlying logic behind the method. Whether you’re evaluating educational policies, economic interventions, or any scenario with a clear threshold effect, this hands-on guide is your first step toward mastering RDD.&lt;/p>
&lt;p>Regression Discontinuity Design (RDD) is a quasi-experimental method used to estimate causal effects when treatment assignment is determined by a cutoff in a continuous variable (the running variable). The key idea is that units just below and just above the cutoff are very similar, so a jump in the outcome at the cutoff can be interpreted as the causal effect of the treatment.&lt;/p>
&lt;p>Mathematically, let
$$
m(x) = E[Y \mid X=x]
$$&lt;/p>
&lt;p>be the conditional expectation of the outcome Y given the running variable X. Suppose that there is a discontinuity at x = c so that:
$$
m(x) = \begin{cases}
m_0(x), &amp;amp; x &amp;lt; c, \newline
m_1(x), &amp;amp; x \ge c.
\end{cases}
$$
The treatment effect at the cutoff is then estimated as:
$$
\hat{\tau} = m_1(c) - m_0(c).
$$&lt;/p>
&lt;p>The variance of the estimated effect is:
$$
\operatorname{Var}(\hat{\tau}) = \operatorname{Var}(m_1(c)) + \operatorname{Var}(m_0(c))
$$&lt;/p>
&lt;p>and the 95% confidence interval (CI) is given by:
$$
\hat{\tau} \pm z_{0.025} \sqrt{\operatorname{Var}(m_1(c)) + \operatorname{Var}(m_0(c))}
$$
with $ z_{0.025} \approx 1.96$.&lt;/p>
&lt;p>In the following sections, we illustrate these concepts with a simulated dataset.&lt;/p>
&lt;h1 id="1-simulated-data">1. Simulated Data&lt;/h1>
&lt;p>We simulate a dataset with 500 observations. The running variable x is drawn uniformly from [-10,10]. The outcome y is generated with a discontinuity (a jump) at x=0. In our simulation, for x &amp;lt; 0 we set:
$$
y = 5 + 0.3x + \varepsilon,
$$
and for $x \ge 0$:
$$
y = 7 + 0.3x + \varepsilon,
$$
with$\varepsilon \sim N(0,1)$.&lt;/p>
&lt;pre>&lt;code class="language-python">import numpy as np
import pandas as pd
# Set the seed for reproducibility
np.random.seed(42)
# Simulate 500 observations for the running variable x
N = 500
x = np.random.uniform(-10, 10, size=N)
# Generate noise
error = np.random.normal(0, 1, size=N)
# Generate outcome y with a jump at x = 0 (jump of 2 units)
y = np.where(x &amp;lt; 0, 5 + 0.3 * x, 7 + 0.3 * x) + error
# Create a DataFrame
data = pd.DataFrame({'x': x, 'y': y})
print(data.head())
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## x y
## 0 -2.509198 4.588997
## 1 9.014286 11.580457
## 2 4.639879 9.342387
## 3 1.973170 7.015047
## 4 -6.879627 2.037697
&lt;/code>&lt;/pre>
&lt;p>In this simulated example, the cutoff is at $x=0$.&lt;/p>
&lt;h1 id="2-epanechnikov-kernel">2. Epanechnikov Kernel&lt;/h1>
&lt;p>The Epanechnikov kernel is used to assign weights to observations based on their distance from the cutoff. Observations closer to the cutoff are given higher weights. The kernel is defined as:
$$
K(u) = \begin{cases}
0.75 (1 - u^2) &amp;amp; \text{if } |u| \le 1, \newline
0 &amp;amp; \text{otherwise.}
\end{cases}
$$
This topic is explained more deeply on my other blog post about &lt;a href="https://luis-zapatabobadilla.netlify.app/project/kernel-density-local-estimators/" target="_blank" rel="noopener">Kernel Density Estimation&lt;/a>.&lt;/p>
&lt;pre>&lt;code class="language-python">def epanechnikov_kernel(u):
&amp;quot;&amp;quot;&amp;quot;
Epanechnikov kernel function.
Returns:
K(u) = 0.75 * (1 - u^2) for |u| &amp;lt;= 1, and 0 otherwise.
&amp;quot;&amp;quot;&amp;quot;
if abs(u) &amp;lt;= 1:
return 0.75 * (1 - u**2)
else:
return 0
&lt;/code>&lt;/pre>
&lt;h2 id="3-local-linear-regression">3. Local Linear Regression&lt;/h2>
&lt;p>To estimate the outcome function on either side of the cutoff, we perform a weighted linear regression. We center the running variable at the cutoff $c=0$ so that:
$$
x_{\text{centered}} = x - c = x.
$$
The local linear regression model is:
$$
y = \beta_0 + \beta_1 x_{\text{centered}} + \varepsilon.
$$
At $x_{\text{centered}} = 0$, the predicted outcome is $\beta_0$, which estimates m(c).&lt;/p>
&lt;pre>&lt;code class="language-python">def local_linear_regression(df, y_variable, x_variable, cutoff, bandwidth, kernel_function):
&amp;quot;&amp;quot;&amp;quot;
Performs local linear regression on observations below and above the cutoff.
The running variable is centered at the cutoff:
$$ x_{centered} = x - c $$
so that the intercept represents the estimated outcome at the cutoff, i.e., $$ m(c) = \\beta_0 $$.
&amp;quot;&amp;quot;&amp;quot;
df_local = df.copy()
# Center the running variable at the cutoff (c = 0)
df_local['x_centered'] = df_local[x_variable] - cutoff
df_local['constant'] = 1
# Compute kernel weights based on the scaled distance from the cutoff
df_local['weights'] = df_local['x_centered'].apply(lambda x: kernel_function(x / bandwidth))
# Split data into observations below and above the cutoff
df_below = df_local[df_local['x_centered'] &amp;lt;= 0]
df_above = df_local[df_local['x_centered'] &amp;gt; 0]
def _weighted_regression(sub_df, y_var):
if sub_df.empty:
return np.array([np.nan, np.nan]), np.full((2, 2), np.nan)
X = sub_df[['constant', 'x_centered']].values
Y = sub_df[y_var].values
W = np.diag(sub_df['weights'].values)
try:
XTWX_inv = np.linalg.inv(X.T @ W @ X)
theta = XTWX_inv @ (X.T @ W @ Y)
residuals = Y - X @ theta
variance_matrix = XTWX_inv @ (X.T @ W @ np.diag(residuals**2) @ W @ X) @ XTWX_inv
except np.linalg.LinAlgError:
return np.array([np.nan, np.nan]), np.full((2, 2), np.nan)
return theta, variance_matrix
theta_below, var_below = _weighted_regression(df_below, y_variable)
theta_above, var_above = _weighted_regression(df_above, y_variable)
return theta_below, var_below, theta_above, var_above
&lt;/code>&lt;/pre>
&lt;ol start="4">
&lt;li>RDD Estimator&lt;/li>
&lt;/ol>
&lt;p>The RDD estimator computes the treatment effect as the difference in the predicted outcomes at the cutoff:
$$
\hat{\tau} = \hat{m}_1(0) - \hat{m}_0(0),
$$
where $\hat{m}_1(0)$ and $\hat{m}_0(0)$ are the intercepts from the regressions above and below the cutoff, respectively.
The variance of the treatment effect is:
$$
\operatorname{Var}(\hat{\tau}) = \operatorname{Var}(\hat{m}_1(0)) + \operatorname{Var}(\hat{m}_0(0)),
$$
and its standard error is the square root of this sum.&lt;/p>
&lt;pre>&lt;code class="language-python">def rdd_estimator(df, y_variable, x_variable, cutoff, bandwidth, kernel_function):
&amp;quot;&amp;quot;&amp;quot;
Estimates the RDD treatment effect as the difference in the predicted outcome at the cutoff.
Since the running variable is centered at the cutoff,
the predicted outcome is simply the intercept:
$$ \\hat{m}(c) = \\beta_0. $$
Thus, the treatment effect is:
$$ \\hat{\\tau} = \\hat{m}_1(c) - \\hat{m}_0(c). $$
&amp;quot;&amp;quot;&amp;quot;
theta_below, var_below, theta_above, var_above = local_linear_regression(
df, y_variable, x_variable, cutoff, bandwidth, kernel_function)
if np.any(np.isnan(theta_below)) or np.any(np.isnan(theta_above)):
return np.nan, np.nan
# Predicted outcome at the cutoff is the intercept (when x_centered = 0)
pred_below = theta_below[0]
pred_above = theta_above[0]
treatment_effect = pred_above - pred_below
# Variance of the intercept estimates (using the selector vector e0 = [1, 0])
e0 = np.array([1.0, 0.0])
se = np.sqrt(e0 @ (var_below + var_above) @ e0)
return treatment_effect, se
&lt;/code>&lt;/pre>
&lt;ol start="5">
&lt;li>Running the Analysis and Constructing the Confidence Interval&lt;/li>
&lt;/ol>
&lt;p>We now run the RDD estimator using a chosen bandwidth and compute the 95% confidence interval. Recall, the 95% CI is given by:
$$
CI_\text{95%} = \hat{\tau} \pm 1.96 \times SE(\hat{\tau}).
$$&lt;/p>
&lt;pre>&lt;code class="language-python">from scipy.stats import norm
# Choose a bandwidth (experiment with this value)
bandwidth = 2.0
# Run the RDD estimator on the simulated data. Here, the cutoff is 0.
treatment_effect, se = rdd_estimator(data, 'y', 'x', cutoff=0, bandwidth=bandwidth, kernel_function=epanechnikov_kernel)
if not np.isnan(treatment_effect):
print(&amp;quot;RDD Estimate (ATE): {:.4f}&amp;quot;.format(treatment_effect))
print(&amp;quot;Standard Error: {:.4f}&amp;quot;.format(se))
# Compute the 95% confidence interval.
alpha = 0.05
z = norm.ppf(1 - alpha/2) # Approximately 1.96 for a 95% CI.
ci_lower = treatment_effect - z * se
ci_upper = treatment_effect + z * se
print(&amp;quot;95% Confidence Interval: [{:.4f}, {:.4f}]&amp;quot;.format(ci_lower, ci_upper))
else:
print(&amp;quot;RDD estimation failed. Please check your data or bandwidth.&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## RDD Estimate (ATE): 1.9539
## Standard Error: 0.3026
## 95% Confidence Interval: [1.3607, 2.5470]
&lt;/code>&lt;/pre>
&lt;h1 id="6-graphical-representation-plotting-the-local-linear-fits-and-confidence-intervals">6. Graphical Representation: Plotting the Local Linear Fits and Confidence Intervals&lt;/h1>
&lt;p>Below we plot the estimated local linear regressions on either side of the cutoff, along with their pointwise 95% confidence intervals.&lt;/p>
&lt;pre>&lt;code class="language-python">import matplotlib.pyplot as plt
def plot_rdd_fit(df, y_variable, x_variable, cutoff, bandwidth, kernel_function, n_grid=100, alpha=0.05):
&amp;quot;&amp;quot;&amp;quot;
Plots the local linear regression fits with pointwise 95% confidence intervals.
The regression is estimated separately on each side of the cutoff.
&amp;quot;&amp;quot;&amp;quot;
# Get the estimates from local linear regressions.
theta_below, var_below, theta_above, var_above = local_linear_regression(df, y_variable, x_variable, cutoff, bandwidth, kernel_function)
if np.any(np.isnan(theta_below)) or np.any(np.isnan(theta_above)):
print(&amp;quot;Local-linear regression failed on one side. No plot produced.&amp;quot;)
return
# Extract coefficients for each side.
beta0_below, beta1_below = theta_below
beta0_above, beta1_above = theta_above
# Create grids for values below and above the cutoff.
x_min, x_max = df[x_variable].min(), df[x_variable].max()
grid_below = np.linspace(x_min, cutoff, n_grid)
grid_above = np.linspace(cutoff, x_max, n_grid)
# Compute the z-value for the (1-alpha) CI.
z_val = norm.ppf(1 - alpha/2)
# Compute predictions and confidence intervals for observations below the cutoff.
mhat_below = []
ci_lower_below = []
ci_upper_below = []
for xg in grid_below:
# Prediction: m0(x) = beta0_below + beta1_below * (x - cutoff)
pred = beta0_below + beta1_below * (xg - cutoff)
vec = np.array([1.0, xg - cutoff])
var_pred = vec @ var_below @ vec
se_pred = np.sqrt(var_pred)
mhat_below.append(pred)
ci_lower_below.append(pred - z_val * se_pred)
ci_upper_below.append(pred + z_val * se_pred)
# Compute predictions and confidence intervals for observations above the cutoff.
mhat_above = []
ci_lower_above = []
ci_upper_above = []
for xg in grid_above:
# Prediction: m1(x) = beta0_above + beta1_above * (x - cutoff)
pred = beta0_above + beta1_above * (xg - cutoff)
vec = np.array([1.0, xg - cutoff])
var_pred = vec @ var_above @ vec
se_pred = np.sqrt(var_pred)
mhat_above.append(pred)
ci_lower_above.append(pred - z_val * se_pred)
ci_upper_above.append(pred + z_val * se_pred)
#Lets create the original lines from the formula
y_below = 5 + 0.3 * grid_below
y_above = 7 + 0.3 * grid_above
# Plot the results.
plt.figure(figsize=(8,6))
plt.plot(grid_below, mhat_below, color='blue', label=r'$\hat{m}_0(x)$')
plt.fill_between(grid_below, ci_lower_below, ci_upper_below, color='blue', alpha=0.3)
plt.plot(grid_above, mhat_above, color='red', label=r'$\hat{m}_1(x)$')
plt.fill_between(grid_above, ci_lower_above, ci_upper_above, color='red', alpha=0.3)
plt.axvline(cutoff, color='black', linestyle='--', label='Cutoff')
plt.xlabel('Running Variable')
plt.ylabel('Outcome')
plt.title('Local Linear Regression Fit with 95% Confidence Intervals')
#Lets also add the original data
plt.scatter(df[x_variable], df[y_variable], color='black', alpha=0.15, label='Data')
#Lets plot the original lines
plt.plot(grid_below, y_below, color='green', label='y = 5 + 0.3x',linestyle='-.')
plt.plot(grid_above, y_above, color='purple', label='y = 7 + 0.3x',linestyle='-.')
plt.legend()
plt.show()
# Call the plotting function.
plot_rdd_fit(data, 'y', 'x', cutoff=0, bandwidth=bandwidth, kernel_function=epanechnikov_kernel)
&lt;/code>&lt;/pre>
&lt;p>&lt;img src="https://luis-zapatabobadilla.netlify.app/project/regression-discontinuity-design-rdd/index.en_files/figure-html/unnamed-chunk-6-1.png" width="768" />&lt;/p>
&lt;p>As we can see, the local linear regression effectively emphasizes the data closest to the cutoff by using weighted observations. While the slope estimates may be more variable—since they rely on data closer to the cutoff, the intercept provides a robust estimate of the treatment effect at the cutoff. This is why the confidence interval is narrow near the cutoff (where the model is most precise) and widens as we move away, reflecting that our inference is primarily focused on the discontinuity point. Overall, the model accurately captures the differences in outcomes between the two sides of the cutoff.&lt;/p>
&lt;h1 id="conclusion">Conclusion&lt;/h1>
&lt;p>In this post we have:&lt;/p>
&lt;ul>
&lt;li>Simulated data with a discontinuity at $x=0$,&lt;/li>
&lt;li>Used an Epanechnikov kernel to weight observations based on their proximity to the cutoff,&lt;/li>
&lt;li>Performed local linear regressions on each side of the cutoff to estimate the outcome functions, and&lt;/li>
&lt;li>Estimated the treatment effect as the jump at the cutoff, along with its 95% confidence interval.&lt;/li>
&lt;/ul>
&lt;p>This example provides a didactic introduction to RDD. By focusing on data near the cutoff, RDD isolates the causal effect of the treatment. Happy coding and exploring RDD!&lt;/p></description></item><item><title>Analyzing Bitcoin Options with Deribit API and Black-Scholes Model</title><link>https://luis-zapatabobadilla.netlify.app/project/bitcoin-options-black-scholes/</link><pubDate>Tue, 26 Nov 2024 00:00:00 +0000</pubDate><guid>https://luis-zapatabobadilla.netlify.app/project/bitcoin-options-black-scholes/</guid><description>&lt;h2 id="introduction">Introduction&lt;/h2>
&lt;p>Bitcoin options have become an essential tool in modern financial markets, offering traders and researchers opportunities to manage risk, speculate on price movements, and explore market dynamics. However, understanding and leveraging these instruments require a combination of financial knowledge and technical expertise.&lt;/p>
&lt;p>This blog aims to provide a step-by-step guide to analyzing Bitcoin options by integrating key financial concepts with practical coding implementations. Specifically, we will:&lt;/p>
&lt;ol>
&lt;li>&lt;strong>Download and Process Historical Data&lt;/strong>:
&lt;ul>
&lt;li>Learn how to use the Deribit API to retrieve detailed Bitcoin options data, overcoming common challenges in data collection through Python automation.blog&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;strong>Understand the Black-Scholes Model&lt;/strong>:
&lt;ul>
&lt;li>Explore the mathematical foundations of options pricing, focusing on how variables like volatility and time-to-maturity influence option values.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;strong>Apply Machine Learning for Volatility Forecasting&lt;/strong>:
&lt;ul>
&lt;li>Use a Random Forest model to predict implied volatility, showcasing a modern, data-driven approach to financial analysis.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;strong>Implement a Delta Strategy&lt;/strong>:
&lt;ul>
&lt;li>Discover how delta, a key measure in options trading, can be used to adjust portfolios dynamically and manage risk effectively.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ol>
&lt;p>We will be showing:&lt;/p>
&lt;ul>
&lt;li>&lt;strong>API expertise&lt;/strong>: Using Python to interact with APIs and process large datasets effectively.&lt;/li>
&lt;li>&lt;strong>Finance Foundations&lt;/strong>: Applying theoretical models like Black-Scholes in real-world scenarios.&lt;/li>
&lt;li>&lt;strong>Machine Learning&lt;/strong>: Leveraging data-driven approaches to forecast critical metrics in financial markets.&lt;/li>
&lt;li>&lt;strong>Strategic Thinking&lt;/strong>: Translating insights from data into actionable strategies, like delta crypto finance strategies&lt;/li>
&lt;/ul>
&lt;h2 id="part-1-downloading-historical-bitcoin-options-data">Part 1: Downloading Historical Bitcoin Options Data&lt;/h2>
&lt;p>We will use Deribit’s historical API to access Bitcoin options data. This API allows fetching complete historical data for options trades.&lt;/p>
&lt;p>The standard &lt;a href="https://docs.deribit.com/#public-get_last_trades_by_currency_and_time" target="_blank" rel="noopener">Deribit API&lt;/a> imposes a limitation on accessing historical data, allowing users to retrieve trades only up to two weeks in the past. To overcome this, Deribit provides a separate historical API endpoint, enabling access to older trade data with detailed records of options activity.&lt;/p>
&lt;p>The steps involve setting up a loop to retrieve data in manageable time intervals and processing the results for further analysis.&lt;/p>
&lt;h3 id="code-implementation">Code Implementation:&lt;/h3>
&lt;pre>&lt;code class="language-python">import requests
import pandas as pd
from datetime import datetime, timedelta
import time
# Define the historical trades URL
historical_trades_url = &amp;quot;https://history.deribit.com/api/v2/public/get_last_trades_by_currency_and_time&amp;quot;
# Function to get historical trades
def get_historical_trades(currency, kind, start_time, end_time, count=1000):
# Convert timestamps to milliseconds since epoch
end_timestamp = int(time.mktime(end_time.timetuple()) * 1000)
start_timestamp = int(time.mktime(start_time.timetuple()) * 1000)
# Define the payload for fetching historical trades
trades_payload = {
'currency': currency,
'start_timestamp': start_timestamp,
'end_timestamp': end_timestamp,
'kind': kind,
'count': count,
'include_old': True
}
# Send the request to get historical trades
trades_response = requests.get(historical_trades_url, params=trades_payload)
# Check if the response is successful
if trades_response.status_code == 200:
trades_data = trades_response.json()
#print(&amp;quot;Historical Trades Response:&amp;quot;, trades_data)
# Process and print trades data
if 'result' in trades_data:
print(&amp;quot;Successfully fetched trades data&amp;quot;)
else:
print(&amp;quot;Failed to fetch trades data&amp;quot;)
else:
print(f&amp;quot;Failed to fetch data: {trades_response.status_code}&amp;quot;)
return trades_data
# Function to process and filter trades data
def get_trades(trades_data):
trades = trades_data['result']['trades']
df = pd.json_normalize(trades)
if 'timestamp' in df.columns:
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
# Filter for call options
calls = df[df['instrument_name'].str.endswith('C')].copy()
# Extract maturity and strike prices
calls.loc[:, 'maturity'] = calls['instrument_name'].apply(lambda x: x.split('-')[1])
calls.loc[:, 'strike'] = calls['instrument_name'].apply(lambda x: x.split('-')[2].replace('C', '').replace('P', ''))
calls['strike'] = calls['strike'].astype(float)
calls['maturity'] = pd.to_datetime(calls['maturity'], format='%d%b%y')
else:
# print(&amp;quot;No timestamp column for date&amp;quot;, start_time)
calls = pd.DataFrame()
return calls
# Loop to fetch data for multiple time intervals
historical_trades = []
start_time = datetime(2024, 11, 7) # Define starting time
for i in range(12): # Loop to get data for 24 hours
end_time = start_time + timedelta(hours=1)
trades_response = get_historical_trades('BTC', 'option', start_time, end_time)
historical_trades.append(get_trades(trades_response))
start_time = end_time
time.sleep(3) # Wait 3 seconds between API calls
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## Successfully fetched trades data
## Successfully fetched trades data
## Successfully fetched trades data
## Successfully fetched trades data
## Successfully fetched trades data
## Successfully fetched trades data
## Successfully fetched trades data
## Successfully fetched trades data
## Successfully fetched trades data
## Successfully fetched trades data
## Successfully fetched trades data
## Successfully fetched trades data
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">
historical_trades = pd.concat(historical_trades, ignore_index=True)
print(historical_trades.head())
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## trade_seq trade_id ... combo_trade_id liquidation
## 0 679 324402707 ... NaN NaN
## 1 43 324402703 ... NaN NaN
## 2 30 324402702 ... NaN NaN
## 3 678 324402688 ... NaN NaN
## 4 4318 324402676 ... NaN NaN
##
## [5 rows x 18 columns]
&lt;/code>&lt;/pre>
&lt;p>Here’s a detailed explanation of what happens step by step:&lt;/p>
&lt;h3 id="connecting-to-deribits-historical-api">Connecting to Deribit’s Historical API&lt;/h3>
&lt;p>The script interacts with the Deribit historical API endpoint, which allows fetching trade data for Bitcoin options. To use this API effectively, the script sends a structured request containing details such as the time range for the data, the type of instrument (e.g., options), and the currency (Bitcoin).&lt;/p>
&lt;h3 id="data-retrieval-in-time-intervals">Data Retrieval in Time Intervals&lt;/h3>
&lt;p>Since the historical database can be extensive, the script divides the data request into manageable chunks. Specifically, it retrieves data in 1-hour intervals, starting from a defined &lt;code>start_time&lt;/code>. This approach ensures that the API isn’t overwhelmed by large requests and adheres to any rate limits imposed by the server. After each request, the script waits for a few seconds before proceeding to the next, ensuring smooth communication with the API.&lt;/p>
&lt;h3 id="filtering-and-processing-the-data">Filtering and Processing the Data&lt;/h3>
&lt;p>Once the trade data is retrieved, it is processed to extract relevant information. The script focuses on “call options,” a specific type of option contract, by filtering instruments whose names end with “C.” It further extracts important details such as:&lt;/p>
&lt;ul>
&lt;li>&lt;strong>Strike Price&lt;/strong>: The agreed price at which the option can be exercised.&lt;/li>
&lt;li>&lt;strong>Maturity Date&lt;/strong>: The expiration date of the option.&lt;/li>
&lt;/ul>
&lt;h3 id="automating-the-workflow">Automating the Workflow&lt;/h3>
&lt;p>To handle larger datasets, the script automates the entire workflow using a loop. For each iteration, it fetches data for a 1-hour window, processes the retrieved trades, and appends the results to a list. This list represents a cumulative collection of all the data retrieved across the defined time period (e.g., 7 hours in this example).&lt;/p>
&lt;p>In summary:&lt;/p>
&lt;ol>
&lt;li>&lt;strong>Historical API&lt;/strong>: The URL &lt;code>https://history.deribit.com/api/v2/public/get_last_trades_by_currency_and_time&lt;/code> allows accessing historical options data. Unlike the WebSocket API, this endpoint provides complete historical data.&lt;/li>
&lt;li>&lt;strong>Data Retrieval Loop&lt;/strong>: To avoid overwhelming the server, we query data in 1-hour intervals with a delay between requests.&lt;/li>
&lt;li>&lt;strong>Filtering and Processing&lt;/strong>:
&lt;ul>
&lt;li>Filters trades to extract only call options (&lt;code>instrument_name&lt;/code> ends with &lt;code>C&lt;/code>).&lt;/li>
&lt;li>Extracts additional details like strike prices and maturity dates for analysis.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ol>
&lt;p>This code ensures efficient fetching of historical Bitcoin options data while adhering to API rate limits and provides well-structured data ready for modeling and analysis.&lt;/p>
&lt;h2 id="part-2-understanding-the-black-scholes-model">Part 2: Understanding the Black-Scholes Model&lt;/h2>
&lt;p>The Black-Scholes model is a mathematical formula for pricing European call and put options. It assumes constant volatility and no dividends.&lt;/p>
&lt;p>Essentially, it determines the fair value of a call or put option based on several key factors: the current price of the underlying asset ($S_0$), the option’s strike price ($K$), the time left until expiration ($T$), the risk-free interest rate ($r$), and the volatility of the asset’s price ($ \sigma $). These variables are combined into a formula that accounts for the probabilistic nature of market movements and the time value of money.&lt;/p>
&lt;p>At its core, the model calculates the likelihood of an option finishing “in the money” (profitable) by using two probability factors, $N(d_1)$ and $N(d_2)$, derived from the normal distribution. These terms represent the probabilities of different market scenarios. For a call option, the formula calculates the expected payoff by weighing the probability of the stock exceeding the strike price at expiration against the present value of the strike price itself. This balance ensures that the price reflects both the potential reward and the risks involved.&lt;/p>
&lt;p>One of the key strengths of the Black-Scholes model is its simplicity and assumptions, such as &lt;strong>constant volatility&lt;/strong> and &lt;strong>no dividends&lt;/strong>. While these assumptions don’t always perfectly match reality, the model is an essential starting point for understanding option pricing and has paved the way for more advanced variations used in modern finance.&lt;/p>
&lt;h3 id="formula">Formula:&lt;/h3>
&lt;p>The price of a call option is given by:
$$
C = S_0 \cdot N(d_1) - K \cdot e^{-rT} \cdot N(d_2)
$$
Where:&lt;/p>
&lt;ul>
&lt;li>$ S_0 $: Current stock price&lt;/li>
&lt;li>$ K $: Strike price&lt;/li>
&lt;li>$ T $: Time to expiration&lt;/li>
&lt;li>$ r $: Risk-free interest rate&lt;/li>
&lt;li>$ N(d) $: Cumulative standard normal distribution&lt;/li>
&lt;li>$ d_1 $: $ \frac{\ln(S_0 / K) + (r + \sigma^2 / 2)T}{\sigma \sqrt{T}} $&lt;/li>
&lt;li>$ d_2 $: $d_1 - \sigma \sqrt{T}$&lt;/li>
&lt;/ul>
&lt;h3 id="code">Code:&lt;/h3>
&lt;pre>&lt;code class="language-python">from scipy.stats import norm
import numpy as np
# Black-Scholes Formula
def black_scholes(S, K, T, r, sigma, option_type=&amp;quot;call&amp;quot;):
d1 = (np.log(S / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * np.sqrt(T))
d2 = d1 - sigma * np.sqrt(T)
if option_type == &amp;quot;call&amp;quot;:
return S * norm.cdf(d1) - K * np.exp(-r * T) * norm.cdf(d2)
elif option_type == &amp;quot;put&amp;quot;:
return K * np.exp(-r * T) * norm.cdf(-d2) - S * norm.cdf(-d1)
# Example usage
S = 20000 # Current BTC price
K = 21000 # Strike price
T = 30 / 365 # Time to expiration in years
r = 0.01 # Risk-free rate
sigma = 0.5 # Volatility
call_price = black_scholes(S, K, T, r, sigma)
print(f&amp;quot;Call Option Price: {call_price}, for Strike Price: {K} and Time to Expiration: {T} years&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## Call Option Price: 744.2789814617408, for Strike Price: 21000 and Time to Expiration: 0.0821917808219178 years
&lt;/code>&lt;/pre>
&lt;h3 id="implied-volatility">&lt;strong>Implied Volatility&lt;/strong>&lt;/h3>
&lt;p>Implied volatility (IV) is a measure of the market’s expectation of the future volatility of the underlying asset’s price. Unlike historical volatility, which is based on past price movements, IV is derived from the market price of options using models like Black-Scholes. It reflects the degree of expected price fluctuations of the underlying asset over the life of the option.&lt;/p>
&lt;p>In practice, implied volatility is an essential tool for traders because:&lt;/p>
&lt;ol>
&lt;li>&lt;strong>Market Sentiment&lt;/strong>: It captures the market’s expectations and risk perceptions.&lt;/li>
&lt;li>&lt;strong>Option Pricing&lt;/strong>: Higher IV leads to higher option premiums since the probability of significant price movement increases.&lt;/li>
&lt;li>&lt;strong>Volatility Smile&lt;/strong>: In real markets, IV often varies with the option’s strike price, forming a “smile” shape when plotted, contrary to Black-Scholes’ assumption of constant IV.&lt;/li>
&lt;/ol>
&lt;p>A “volatility smile” occurs because deep in-the-money and out-of-the-money options often have higher implied volatilities than at-the-money options. This effect reflects market imperfections, demand for certain options, and potential risk.&lt;/p>
&lt;h4 id="black-scholes-model-and-implied-volatility">&lt;strong>Black-Scholes Model and Implied Volatility&lt;/strong>&lt;/h4>
&lt;p>The price of a call option under the Black-Scholes formula is given by:&lt;/p>
&lt;p>$$
C = S_0 \cdot N(d_1) - K \cdot e^{-rT} \cdot N(d_2)
$$&lt;/p>
&lt;p>Here, $ \sigma $ (volatility) is typically an &lt;strong>input&lt;/strong> into the model to calculate the option’s price. However, in the case of implied volatility, we &lt;strong>reverse the process&lt;/strong>: we use the observed market price of the option to solve for $ \sigma $. This involves numerical optimization, as there is no closed-form solution for $\sigma $.&lt;/p>
&lt;h3 id="limitations-of-black-scholes-implied-volatility">&lt;strong>Limitations of Black-Scholes Implied Volatility&lt;/strong>&lt;/h3>
&lt;ol>
&lt;li>&lt;strong>Constant Volatility Assumption&lt;/strong>:
&lt;ul>
&lt;li>The Black-Scholes model assumes that volatility remains constant over the life of the option. However, in reality, volatility is dynamic and varies depending on factors like market conditions, economic data releases, and investor sentiment.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;strong>Lognormal Price Distribution&lt;/strong>:
&lt;ul>
&lt;li>The model assumes that asset prices follow a lognormal distribution, meaning they have a symmetric behavior. However, real-world markets often exhibit &lt;strong>skewness&lt;/strong> (asymmetric returns) and &lt;strong>kurtosis&lt;/strong> (fat tails).&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;strong>Short-Term Maturity Issues&lt;/strong>:
&lt;ul>
&lt;li>For options close to expiration, small changes in price or volatility can lead to large variations in implied volatility. This amplifies numerical optimization errors.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;strong>Deep ITM or OTM Options&lt;/strong>:
&lt;ul>
&lt;li>Deep in-the-money (ITM) or out-of-the-money (OTM) options often result in extreme or nonsensical implied volatilities because their market prices are less sensitive to volatility.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ol>
&lt;h3 id="why-does-the-market-show-a-volatility-smile">&lt;strong>Why Does the Market Show a Volatility Smile?&lt;/strong>&lt;/h3>
&lt;ol>
&lt;li>&lt;strong>Market Skewness and Risk Aversion&lt;/strong>:
&lt;ul>
&lt;li>Investors often seek protection against extreme moves in the market, leading to higher demand (and hence, higher implied volatility) for deep OTM options, especially put options. This demand reflects their willingness to pay more for tail risk hedging.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;strong>Supply-Demand Dynamics&lt;/strong>:
&lt;ul>
&lt;li>Market makers adjust the prices of options based on order flow. If there is higher demand for certain strikes, it increases their implied volatility.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;strong>Real-World Volatility is Stochastic&lt;/strong>:
&lt;ul>
&lt;li>Unlike the constant volatility assumed by Black-Scholes, real-world volatility is stochastic (i.e., it changes over time) and often exhibits clustering. This adds curvature to the implied volatility plot.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;strong>Market Sentiment and Imbalances&lt;/strong>:
&lt;ul>
&lt;li>In bearish markets, implied volatility tends to increase, particularly for OTM puts, as investors rush to buy downside protection. Conversely, in bullish markets, OTM call options might show elevated implied volatilities due to speculative demand.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ol>
&lt;p>The smile in the implied volatility plot reflects the limitations of the Black-Scholes model and the realities of market behavior. While Black-Scholes assumes a flat volatility curve, the observed smile arises from demand for risk hedging, market maker adjustments, and the dynamic nature of volatility. Understanding these nuances allows traders and quants to better interpret market signals and deploy strategies like &lt;strong>delta hedging&lt;/strong>, which benefit from accurate volatility forecasting.&lt;/p>
&lt;p>Below is the Python code to calculate and plot the implied volatility smile using the downloaded options data.&lt;/p>
&lt;pre>&lt;code class="language-python">import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
df = historical_trades
df['days_to_maturity'] = (df['maturity'] - df['timestamp']).dt.days
# Step 1: Clean and filter the data
# Remove rows with invalid or unrealistic IV values
filtered_calls = df[(df['iv'] &amp;gt; 0) &amp;amp; (df['iv'] &amp;lt; 500)] # Filter IV column for valid values
# Ensure days to maturity is positive
filtered_calls = filtered_calls[filtered_calls['days_to_maturity'] &amp;gt; 0]
# Step 2: Calculate moneyness (index_price / strike)
filtered_calls['moneyness'] = filtered_calls['index_price'] / filtered_calls['strike']
# Step 3: Filter by similar days to maturity (e.g., 7 to 30 days)
similar_maturity_calls = filtered_calls[
(filtered_calls['days_to_maturity'] &amp;gt;= 7) &amp;amp;
(filtered_calls['days_to_maturity'] &amp;lt;= 30)
]
# Step 4: Plot the implied volatility smile using moneyness
plt.figure(figsize=(10, 6))
plt.scatter(similar_maturity_calls['moneyness'], similar_maturity_calls['iv'], alpha=0.7, label='Implied Volatility')
plt.title(&amp;quot;Implied Volatility Smile (7-30 Days to Maturity, Moneyness-Based)&amp;quot;)
plt.xlabel(&amp;quot;Moneyness (Index Price / Strike Price)&amp;quot;)
plt.ylabel(&amp;quot;Implied Volatility&amp;quot;)
plt.axvline(1, color='red', linestyle='--', label='At-the-Money (ATM)')
plt.grid(True)
plt.legend()
plt.show()
&lt;/code>&lt;/pre>
&lt;p>&lt;img src="https://luis-zapatabobadilla.netlify.app/project/bitcoin-options-black-scholes/index.en_files/figure-html/unnamed-chunk-3-1.png" width="960" />&lt;/p>
&lt;p>The &lt;strong>implied volatility provided by Deribit&lt;/strong> is derived directly from live market data and reflects the collective sentiment, supply-demand dynamics, and real-time risk perceptions of market participants, without the fridge assumptions of the Black Scholes Formula. This makes it a &lt;strong>highly reliable and actionable measure&lt;/strong>, as it inherently accounts for &lt;strong>factors that models like Black-Scholes cannot capture&lt;/strong>, such as market skewness, kurtosis, and stochastic volatility.&lt;/p>
&lt;p>By using &lt;strong>Deribit’s IV&lt;/strong>, we can focus on applying this market-driven insight to strategies like delta hedging, rather than spending time troubleshooting computational issues or compensating for the limitations of traditional models.&lt;/p>
&lt;h3 id="model-deribit-implied-volatility">&lt;strong>Model Deribit Implied Volatility&lt;/strong>&lt;/h3>
&lt;p>Lets try to create a model that would forecast the implied volatility of Deribit, using as inputs the characteristics of the option. This model should be non parametric as we dont know what specific model what used by Deribit.&lt;/p>
&lt;p>To use the Random Forest model for predicting &lt;strong>implied volatility (IV)&lt;/strong>, replacing the analytical Black-Scholes-based calculation, we follow these steps:&lt;/p>
&lt;ol>
&lt;li>&lt;strong>Filter and Clean the Data&lt;/strong>:
&lt;ul>
&lt;li>We remove outlier trades that might distort IV (e.g., combo trades, block trades, liquidation events).&lt;/li>
&lt;li>Clean and engineer features such as moneyness, days to maturity, historical volatility, and moving averages.&lt;/li>
&lt;li>Ensure no missing or invalid values remain in the features or target (&lt;code>iv&lt;/code>).&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;strong>Train a Random Forest Model&lt;/strong>:
&lt;ul>
&lt;li>We use relevant features that are correlated with IV, such as &lt;code>days_to_maturity&lt;/code>, &lt;code>moneyness&lt;/code>, and volatility indicators.&lt;/li>
&lt;li>Train the Random Forest model to predict the IV (&lt;code>target = 'iv'&lt;/code>) using a training set.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;strong>Predict IV for the Dataset&lt;/strong>:
&lt;ul>
&lt;li>We use the trained model to predict IV for the entire dataset or a test set, then replace the calculated IVs in the dataset with the predicted values for further analysis.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;strong>Visualize the Volatility Smile&lt;/strong>:
&lt;ul>
&lt;li>We plot the predicted IVs against the strike prices to observe the smile pattern.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ol>
&lt;h3 id="step-by-step-code">&lt;strong>Step-by-Step Code&lt;/strong>&lt;/h3>
&lt;h4 id="1-data-preparation">&lt;strong>1. Data Preparation&lt;/strong>&lt;/h4>
&lt;p>Start by ensuring your data is clean and ready for modeling.&lt;/p>
&lt;pre>&lt;code class="language-python"># Filter trades with valid IV and prices
df = historical_trades.copy()
df['maturity'] = pd.to_datetime(df['maturity'], errors='coerce')
df['timestamp'] = pd.to_datetime(df['timestamp'], errors='coerce')
# Drop rows with invalid dates
df = df.dropna(subset=['maturity', 'timestamp'])
# Calculate days to maturity
df['days_to_maturity'] = (df['maturity'] - df['timestamp']).dt.days
df['time_to_maturity'] = df['maturity'] - df['timestamp']
# Filter out invalid IV values and zero index prices
df = df[(df['iv'] &amp;gt; 0) &amp;amp; (df['iv'] &amp;lt; 500)]
df = df[df['index_price'] &amp;gt; 0]
# Create the 'moneyness' column
df['moneyness'] = df['index_price'] / df['strike']
# Extract the hour of the trade
df['hour'] = df['timestamp'].dt.hour
# Ensure non-negative days to maturity
df['days_to_maturity'] = df['days_to_maturity'].apply(lambda x: max(0, x))
# Sort by timestamp and set as index for rolling calculations
df = df.sort_values('timestamp')
df = df.set_index('timestamp')
# Calculate historical volatility and moving averages
df['historical_volatility'] = df['index_price'].rolling('1h').std() / df['index_price'].rolling(window='1h').mean()
df['moving_average'] = df['index_price'] / df['index_price'].rolling('1h').mean()
df['historical_volatility_7'] = df['index_price'].rolling('7h').std() / df['index_price'].rolling(window='7h').mean()
df['moving_average_7'] = df['index_price'] / df['index_price'].rolling('7h').mean()
# Calculate 3-hour rolling metrics
df['historical_volatility_3'] = df['index_price'].rolling(window='3h').std() / df['index_price'].rolling('3h').mean()
df['moving_average_3'] = df['index_price'] / df['index_price'].rolling('3h').mean()
# Reset the index after rolling calculations
df = df.reset_index()
# Drop rows with NaN values after rolling
df = df.dropna(subset=['historical_volatility', 'moving_average', 'historical_volatility_3', 'moving_average_3'])
# Engineer additional features: minutes to maturity and time to maturity in years
df['minutes_to_maturity'] = df['time_to_maturity'].dt.total_seconds() / 60
df = df[df['minutes_to_maturity'] &amp;gt; 0] # Remove rows with non-positive maturity
df['time_to_maturity_year'] = df['minutes_to_maturity'] / (365 * 24 * 60)
# Verify final DataFrame
print(f&amp;quot;Data size after all calculations: {len(df)}&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## Data size after all calculations: 4772
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">print(df[['moneyness', 'historical_volatility', 'historical_volatility_3', 'moving_average', 'moving_average_3']].head())
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## moneyness historical_volatility ... moving_average moving_average_3
## 1 0.934902 0.000415 ... 1.000293 1.000293
## 2 0.997276 0.000353 ... 1.000227 1.000227
## 3 0.959066 0.000345 ... 1.000285 1.000285
## 4 0.959066 0.000325 ... 1.000228 1.000228
## 5 0.831048 0.000292 ... 1.000048 1.000048
##
## [5 rows x 5 columns]
&lt;/code>&lt;/pre>
&lt;h4 id="2-train-the-random-forest-model">&lt;strong>2. Train the Random Forest Model&lt;/strong>&lt;/h4>
&lt;p>Select features and train a Random Forest model.&lt;/p>
&lt;pre>&lt;code class="language-python">from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error
# Select features and target variable
features = df[['days_to_maturity', 'moneyness', 'historical_volatility', 'hour',
'moving_average', 'moving_average_3', 'moving_average_7',
'historical_volatility_3', 'historical_volatility_7']]
target = df['iv']
# Split data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(features, target, test_size=0.2, random_state=42)
# Train the Random Forest model
model = RandomForestRegressor(random_state=42)
model.fit(X_train, y_train)
&lt;/code>&lt;/pre>
&lt;style>#sk-container-id-1 {color: black;background-color: white;}#sk-container-id-1 pre{padding: 0;}#sk-container-id-1 div.sk-toggleable {background-color: white;}#sk-container-id-1 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-1 label.sk-toggleable__label-arrow:before {content: "▸";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-1 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-1 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-1 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-1 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-1 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-1 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: "▾";}#sk-container-id-1 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-1 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-1 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-1 div.sk-parallel-item::after {content: "";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-1 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-serial::before {content: "";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-1 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-1 div.sk-item {position: relative;z-index: 1;}#sk-container-id-1 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-1 div.sk-item::before, #sk-container-id-1 div.sk-parallel-item::before {content: "";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-1 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-1 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-1 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-1 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-1 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-1 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-1 div.sk-label-container {text-align: center;}#sk-container-id-1 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-1 div.sk-text-repr-fallback {display: none;}&lt;/style>&lt;div id="sk-container-id-1" class="sk-top-container">&lt;div class="sk-text-repr-fallback">&lt;pre>RandomForestRegressor(random_state=42)&lt;/pre>&lt;b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. &lt;br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.&lt;/b>&lt;/div>&lt;div class="sk-container" hidden>&lt;div class="sk-item">&lt;div class="sk-estimator sk-toggleable">&lt;input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-1" type="checkbox" checked>&lt;label for="sk-estimator-id-1" class="sk-toggleable__label sk-toggleable__label-arrow">RandomForestRegressor&lt;/label>&lt;div class="sk-toggleable__content">&lt;pre>RandomForestRegressor(random_state=42)&lt;/pre>&lt;/div>&lt;/div>&lt;/div>&lt;/div>&lt;/div>
&lt;pre>&lt;code class="language-python"># Predict and evaluate
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
print(f'Mean Squared Error: {mse}')
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## Mean Squared Error: 11.621701853968593
&lt;/code>&lt;/pre>
&lt;h4 id="3-predict-iv-for-the-full-dataset">&lt;strong>3. Predict IV for the Full Dataset&lt;/strong>&lt;/h4>
&lt;p>Use the trained model to predict IV for the entire dataset.&lt;/p>
&lt;pre>&lt;code class="language-python"># Predict implied volatility for the entire dataset
df['predicted_iv'] = model.predict(features)
&lt;/code>&lt;/pre>
&lt;h4 id="4-visualize-the-implied-volatility-smile">&lt;strong>4. Visualize the Implied Volatility Smile&lt;/strong>&lt;/h4>
&lt;p>Create a plot of predicted IVs against strike prices.&lt;/p>
&lt;pre>&lt;code class="language-python">import matplotlib.pyplot as plt
# Filter dataset for options with 7 to 30 days to maturity
filtered_df = df[(df['days_to_maturity'] &amp;gt;= 7) &amp;amp; (df['days_to_maturity'] &amp;lt;= 30)].dropna(subset=['iv', 'moneyness', 'historical_volatility'])
# Plot IV against moneyness
plt.figure(figsize=(12, 6))
plt.scatter(filtered_df['moneyness'], filtered_df['iv'], color='blue', alpha=0.6, label='Real IV (Deribit)', s=20)
plt.scatter(filtered_df['moneyness'], filtered_df['predicted_iv'], color='orange', alpha=0.6, label='Calculated IV (Random Forest)', s=20)
# Add plot titles and labels
plt.title(&amp;quot;Implied Volatility vs. Moneyness (7-30 Days to Maturity)&amp;quot;, fontsize=14)
plt.xlabel(&amp;quot;Moneyness (Index Price / Strike Price)&amp;quot;, fontsize=12)
plt.ylabel(&amp;quot;Implied Volatility&amp;quot;, fontsize=12)
plt.grid(True)
plt.legend()
# Show the plot
plt.show()
&lt;/code>&lt;/pre>
&lt;p>&lt;img src="https://luis-zapatabobadilla.netlify.app/project/bitcoin-options-black-scholes/index.en_files/figure-html/unnamed-chunk-7-3.png" width="1152" />&lt;/p>
&lt;h4 id="5-optional-feature-importance">&lt;strong>5. (Optional) Feature Importance&lt;/strong>&lt;/h4>
&lt;p>Analyze which features are most important in predicting IV.&lt;/p>
&lt;pre>&lt;code class="language-python">import numpy as np
import matplotlib.pyplot as plt
# Get feature importance
importances = model.feature_importances_
feature_names = features.columns
# Sort features by importance
sorted_indices = np.argsort(importances)[::-1] # Sort in descending order
sorted_feature_names = feature_names[sorted_indices]
sorted_importances = importances[sorted_indices]
# Plot feature importance
plt.figure(figsize=(10, 6))
plt.barh(sorted_feature_names, sorted_importances, color='skyblue')
plt.xlabel(&amp;quot;Importance&amp;quot;)
plt.ylabel(&amp;quot;Feature&amp;quot;)
plt.title(&amp;quot;Feature Importance in Predicting IV&amp;quot;)
plt.gca().invert_yaxis() # Invert y-axis to show the highest importance at the top
plt.show()
&lt;/code>&lt;/pre>
&lt;p>&lt;img src="https://luis-zapatabobadilla.netlify.app/project/bitcoin-options-black-scholes/index.en_files/figure-html/unnamed-chunk-8-5.png" width="960" />&lt;/p>
&lt;h3 id="key-points">&lt;strong>Key Points&lt;/strong>&lt;/h3>
&lt;ul>
&lt;li>&lt;strong>Why Random Forest?&lt;/strong>: It is a fast, flexible and powerful model that can capture non-linear relationships between features and the target (IV). This is useful since implied volatility may not follow a simple analytical formula.&lt;/li>
&lt;li>&lt;strong>Feature Selection&lt;/strong>: Ensure that the selected features are relevant and clean to avoid introducing noise into the model.&lt;/li>
&lt;li>&lt;strong>Interpretability&lt;/strong>: Use feature importance to understand which variables are driving the model’s predictions.&lt;/li>
&lt;/ul>
&lt;p>This approach replaces the analytical Black-Scholes calculation with a data-driven machine learning model to estimate implied volatility. With a bigger data, the random forest could be better trained and more complex models could be made.&lt;/p>
&lt;h2 id="part-3-implementing-a-delta-strategy">Part 3: Implementing a Delta Strategy&lt;/h2>
&lt;h3 id="what-is-delta-in-options-trading">What is Delta in Options Trading?&lt;/h3>
&lt;p>Delta is a measure of how sensitive an option’s price is to changes in the price of the underlying asset. Specifically, for call options, delta represents the expected change in the option’s price for a \1 change in the underlying asset’s price, assuming all other factors remain constant. Mathematically, delta ($\Delta$) is expressed as:&lt;/p>
&lt;p>$$
\Delta = \frac{\partial C}{\partial S}
$$&lt;/p>
&lt;p>Where:&lt;/p>
&lt;ul>
&lt;li>$C$: Option price&lt;/li>
&lt;li>$S$: Price of the underlying asset&lt;/li>
&lt;/ul>
&lt;p>For call options, delta values range between 0 and 1. A delta of 0.5, for instance, means the option’s price is expected to change by \0.50 for every \1 change in the asset’s price. In the case of put options, delta values range between -1 and 0.&lt;/p>
&lt;p>Delta also provides insight into the likelihood of the option expiring in the money (ITM). For example, a call option with a delta of 0.7 suggests a 70% chance of the option being ITM at expiration. Delta evolves dynamically based on factors like the underlying asset’s price, time to maturity, and volatility.&lt;/p>
&lt;p>Understanding delta is crucial for constructing hedging strategies, as it allows traders to adjust their positions to manage risk effectively.&lt;/p>
&lt;h3 id="code-1">Code:&lt;/h3>
&lt;pre>&lt;code class="language-python"># Delta calculation
def calculate_delta(S, K, T, r, sigma):
d1 = (np.log(S / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * np.sqrt(T))
return norm.cdf(d1)
# Example: Hedging with 1 option
delta = calculate_delta(S, K, T, r, sigma)
hedge_position = -delta # Short this fraction of BTC
print(f&amp;quot;Delta Position: {hedge_position} BTC&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## Delta Position: -0.39629035723658007 BTC
&lt;/code>&lt;/pre>
&lt;h3 id="understanding-delta-and-using-it-as-a-market-signal">Understanding Delta and Using it as a Market Signal&lt;/h3>
&lt;p>Delta evolves dynamically based on the option’s moneyness, time to maturity, and the volatility of the underlying asset. For example:&lt;/p>
&lt;ul>
&lt;li>&lt;strong>At-the-Money (ATM):&lt;/strong> Delta is approximately 0.5.&lt;/li>
&lt;li>&lt;strong>Out-of-the-Money (OTM):&lt;/strong> Delta approaches 0 as the option becomes less sensitive to price changes.&lt;/li>
&lt;li>&lt;strong>In-the-Money (ITM):&lt;/strong> Delta approaches 1, reflecting greater sensitivity.&lt;/li>
&lt;/ul>
&lt;p>By observing changes in delta, traders can infer shifts in the market sentiment and adjust their positions to maximize profits. For instance, when delta increases significantly, it may signal bullish momentum, while a sharp decrease may indicate bearish trends. Delta-based signals can also help traders decide when to buy or sell Bitcoin to align with market conditions effectively.&lt;/p>
&lt;h3 id="strategy-using-bitcoin-call-options-delta-as-a-market-signal">Strategy: Using Bitcoin Call Options Delta as a Market Signal&lt;/h3>
&lt;p>One potential strategy involves monitoring the delta of Bitcoin call options to generate buy/sell signals for Bitcoin itself. Here’s how it works:&lt;/p>
&lt;ol>
&lt;li>
&lt;p>&lt;strong>Set-Up&lt;/strong>:&lt;/p>
&lt;ul>
&lt;li>Use a predictive model (e.g., Random Forest) to estimate implied volatility (IV).&lt;/li>
&lt;li>Calculate delta for a specific call option, ensuring it is near the current Bitcoin price (ATM) with moderate time to maturity (e.g., 7–30 days).&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Signal Generation&lt;/strong>:&lt;/p>
&lt;ul>
&lt;li>&lt;strong>Buy Signal:&lt;/strong> When delta increases significantly ($ $ approaches 1), it may indicate bullish momentum in Bitcoin or future bullish expectation. Buy/sell Bitcoin to benefit from potential upward price movement.&lt;/li>
&lt;li>&lt;strong>Sell Signal:&lt;/strong> When delta decreases sharply ($ $ approaches 0), it may indicate bearish momentum or a future expected fall in price. Sell/buy Bitcoin to avoid potential losses.&lt;/li>
&lt;/ul>
&lt;p>Our portfolio value would look like this:&lt;/p>
&lt;/li>
&lt;/ol>
&lt;p>$$
P_{t+1} = 100 + D_{t}(S_{t+1} - S_t) + \dots + D_1(S_2 - S_1)
$$&lt;/p>
&lt;p>Where:&lt;/p>
&lt;ul>
&lt;li>Initial Cash: The portfolio starts with \100.&lt;/li>
&lt;li>Delta ( $D_t $): Represents the sensitivity of the option’s price to changes in the underlying asset’s price at time t.&lt;/li>
&lt;li>Stock Price Change ($ S_{t+1} - S_t $): The difference in the underlying asset’s price between time t and t+1.&lt;/li>
&lt;/ul>
&lt;ol start="3">
&lt;li>&lt;strong>Execution&lt;/strong>:
&lt;ul>
&lt;li>Adjust the trading position based on delta movements while considering transaction costs and rebalancing thresholds to minimize unnecessary trades.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ol>
&lt;ul>
&lt;li>At every round t, we adjust the portfolio value by buying/selling $D_t * S_{t}$, which would modify the value of our portfolio at t+1 to $ D_t * (S_{t+1} - S_t)$ . This is the core of our strategy, and its succes would depend of updating the value of $ D_t $ at every round t, which at the same time, would be a function of the forecasted implied volatility, as well as the strike price and time to maturity.&lt;/li>
&lt;/ul>
&lt;p>&lt;strong>Ensuring that $ D_t $ accurately reflects the option’s sensitivity at each time step is crucial.&lt;/strong>&lt;/p>
&lt;p>&lt;strong>While the standard way of thinking about options is using the underlying asset’s price $ S_{t}$, for the execution of this strategy, its not the price of the asset that matters, but the delta of the option.&lt;/strong>&lt;/p>
&lt;p>&lt;strong>Considering this, $ S_{t}$ in our strategy could be the initial amount of cash of our portfolio. In the first round, as we buy Bitcoin with the whole amount of cash, the value of our portfolio remains unchanged.&lt;/strong>&lt;/p>
&lt;ol start="4">
&lt;li>&lt;strong>Risk Management&lt;/strong>:
&lt;ul>
&lt;li>Use stop-loss orders to limit losses in case of sharp adverse movements.&lt;/li>
&lt;li>Combine delta signals with other indicators (e.g., volatility or moving averages) to enhance decision-making.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ol>
&lt;p>This approach provides a practical and dynamic way to leverage options pricing as a tool for directional trading in Bitcoin markets, making delta a valuable market signal for maximizing profitability.&lt;/p>
&lt;h3 id="workflow-for-delta-strategy-with-random-forest-iv">&lt;strong>Workflow for Delta Strategy with Random Forest IV&lt;/strong>&lt;/h3>
&lt;ol>
&lt;li>&lt;strong>Delta strategy Logic&lt;/strong>:
&lt;ul>
&lt;li>Adjust the stock position dynamically to match the delta of the option (IV forecasted using the Random Forest model).&lt;/li>
&lt;li>Track portfolio value, cash position, and transaction costs over time.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;strong>Simulate Portfolio Performance&lt;/strong>:
&lt;ul>
&lt;li>Simulate the performance of the portfolio as you hedge delta over time.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;strong>Plot Results&lt;/strong>:
&lt;ul>
&lt;li>Visualize key metrics like the portfolio value over time or transaction costs.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ol>
&lt;pre>&lt;code class="language-python">df.iterrows()
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## &amp;lt;generator object DataFrame.iterrows at 0x15ac4fab0&amp;gt;
&lt;/code>&lt;/pre>
&lt;h3 id="code-2">&lt;strong>Code&lt;/strong>&lt;/h3>
&lt;pre>&lt;code class="language-python">import pandas as pd
import matplotlib.pyplot as plt
# Define the delta hedging function
def delta_hedging(df, forecast_iv_column, initial_stock_price, r=0.01, trading_fee_rate=0.002):
# Initialize portfolio and stock positions
portfolio_value = 0
cash_position = initial_stock_price # Starting with cash equal to initial stock price
stock_position = 0 # Starting with no stock initially
results = []
for index, row in df.iterrows():
S = row['index_price']
K = row['strike']
T = row['days_to_maturity'] / 365 # Convert days to years
date = row['date']
#print(K)
sigma_forecast = row[forecast_iv_column] / 100 # Convert percentage to decimal
# Calculate forecasted delta
delta_forecast = (calculate_delta(S, K, T, r, sigma_forecast))*(-1) #is negative because we are shorting the call
# Calculate the number of stocks to buy/sell to adjust to the new delta
delta_change = delta_forecast - stock_position
transaction_cost = 0
if delta_change != 0:
# Calculate transaction cost: trading fee + network fee
trading_fee = abs(delta_change) * S * trading_fee_rate
#transaction_cost = trading_fee + network_fee*S
transaction_cost = 0
if abs(delta_change * S) &amp;gt; transaction_cost:
# Update cash position considering transaction cost
cash_position -= transaction_cost #we substract the transaction cost from the cash position
# Adjust stock position to maintain delta neutrality
cash_position += delta_change * S #if delta_change is positive, we are buying stock, if negative we are selling stock.
#If we buy stock, we substract the stock price from the cash position
stock_position = delta_forecast #we set the stock position to the forecasted delta
# Calculate actual option price using Black-Scholes
#option_price_actual = black_scholes_call(S, K, T, r, sigma_actual)
# Update portfolio value
portfolio_value = (stock_position * S*(-1)) + cash_position #portfolio value is the stock position times the stock price plus the cash position
# Store results
results.append({
'timestamp': row['timestamp'], # Ensure timestamp exists
'portfolio_value': portfolio_value,
'index_price': S
})
return pd.DataFrame(results)
# Apply delta hedging strategy to the data
df['date']= df['timestamp'].dt.date
results = delta_hedging(df, 'predicted_iv', initial_stock_price=100)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## &amp;lt;string&amp;gt;:3: RuntimeWarning: divide by zero encountered in scalar divide
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python"># Create a dual-axis plot
fig, ax1 = plt.subplots(figsize=(12, 6))
# Left y-axis: Index Price
ax1.plot(results['timestamp'], results['index_price'], label='Index Price', color='orange')
ax1.set_xlabel(&amp;quot;Timestamp&amp;quot;, fontsize=12)
ax1.set_ylabel(&amp;quot;Index Price&amp;quot;, fontsize=12, color='orange')
ax1.tick_params(axis='y', labelcolor='orange')
ax1.grid(True)
# Right y-axis: Portfolio Value
ax2 = ax1.twinx()
ax2.plot(results['timestamp'], results['portfolio_value'], label='Portfolio Value', color='blue')
ax2.set_ylabel(&amp;quot;Portfolio Value&amp;quot;, fontsize=12, color='blue')
ax2.tick_params(axis='y', labelcolor='blue')
# Title
plt.title(&amp;quot;Portfolio Value and Index Price Over Time&amp;quot;, fontsize=14)
# Show the plot
fig.tight_layout()
plt.show()
&lt;/code>&lt;/pre>
&lt;p>&lt;img src="https://luis-zapatabobadilla.netlify.app/project/bitcoin-options-black-scholes/index.en_files/figure-html/unnamed-chunk-11-7.png" width="1152" />&lt;/p>
&lt;h3 id="explanation">&lt;strong>Explanation&lt;/strong>&lt;/h3>
&lt;ol>
&lt;li>&lt;strong>Delta Calculation&lt;/strong>:
&lt;ul>
&lt;li>The &lt;strong>forecasted delta&lt;/strong> is calculated using the predicted implied volatility (&lt;code>predicted_iv&lt;/code>) from the Random Forest model.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;strong>Portfolio Adjustments&lt;/strong>:
&lt;ul>
&lt;li>Adjust stock positions dynamically to match the forecasted delta, considering transaction costs.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;strong>Visualization&lt;/strong>:
&lt;ul>
&lt;li>&lt;strong>Portfolio Value&lt;/strong>: Track the total portfolio value over time to assess the effectiveness of the strategy.&lt;/li>
&lt;li>&lt;strong>Transaction Costs&lt;/strong>: Plot cumulative transaction costs to understand the costs&lt;/li>
&lt;li>&lt;strong>Delta Changes&lt;/strong>: Analyze the frequency and magnitude of adjustments required to maintain the delta strategy.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ol>
&lt;h3 id="key-points-1">&lt;strong>Key Points&lt;/strong>&lt;/h3>
&lt;ul>
&lt;li>&lt;strong>Accuracy of IV Forecast&lt;/strong>: The results will depend heavily on the quality of the forecasted IVs (&lt;code>predicted_iv&lt;/code>).&lt;/li>
&lt;li>&lt;strong>Transaction Costs&lt;/strong>: Including realistic transaction costs provides a more accurate simulation of the strategy’s performance.&lt;/li>
&lt;li>&lt;strong>Further Analysis&lt;/strong>: You can experiment with different time intervals (e.g., rebalancing daily or hourly) to evaluate how often the portfolio should be adjusted.&lt;/li>
&lt;/ul>
&lt;h3 id="delta-as-a-market-signal-and-its-impact-on-the-portfolio">&lt;strong>Delta as a Market Signal and its Impact on the Portfolio&lt;/strong>&lt;/h3>
&lt;p>In this approach, the portfolio value is influenced by the deltas of all traded call options, acting as a market signal. Delta behaves like a weighted sum: it is low for out-of-the-money options, high for at-the-money options, and particularly significant for options with high volatility and short days to maturity. Longer-dated options are less impactful due to their lower weight.&lt;/p>
&lt;p>Delta dynamically adjusts based on the option’s moneyness and time to maturity. For deep out-of-the-money options, delta approaches 0, limiting losses if the price drops. Conversely, for deep in-the-money options, delta nears 1, amplifying gains if the price rises. Shorter time to maturity further sharpens delta changes, making the portfolio more sensitive to price fluctuations when at-the-money.&lt;/p>
&lt;p>While this demonstrates the potential for strategic delta adjustments, the intention of this blog is not to define a trading strategy but to explore delta’s role in portfolio dynamics.&lt;/p>
&lt;h3 id="posible-modeling-of-delta">Posible modeling of delta?&lt;/h3>
&lt;p>It could be possible to model delta, though this would not be followed in this blog, i will write the ideas:
Variables that affects $ D_i $:&lt;/p>
&lt;p>$$
D_i = \Phi(d_1), \quad \text{where } d_1 = \frac{\ln(S/K) + (r + \sigma^2 / 2)T}{\sigma \sqrt{T}}
$$&lt;/p>
&lt;p>Where:&lt;/p>
&lt;ul>
&lt;li>Stock Price ($S$): As $S$ increases, $d_1$ increases, and so does $(d_1)$ . A higher $S$ leads to a higher delta for a call option, amplifying the positive impact of $S_{i+1} - S_i$ on the portfolio.&lt;/li>
&lt;li>Strike Price ( $K$ ): A lower K (deep in-the-money option) increases $ d_1 $, leading to a higher delta. If the option starts in the money, delta is closer to 1, and the portfolio becomes more sensitive to price changes.&lt;/li>
&lt;li>Time to Maturity ( T ): As T decreases, $\sqrt{T}$ decreases, which can increase $d_1 $ (depending on the relationship between $S/K$ and $\sigma $). However, as $T $ , delta converges to 1 if the option is in the money and to 0 if it is out of the money.&lt;/li>
&lt;li>Volatility ( $\sigma$ ): Higher volatility increases $ d_1$ when $ S/K &amp;gt; 1 $, leading to a higher delta. In volatile markets, delta can change more significantly, affecting the portfolio positively or negatively depending on the price direction.&lt;/li>
&lt;/ul>
&lt;h3 id="cumulative-sum">&lt;strong>Cumulative Sum&lt;/strong>&lt;/h3>
&lt;p>$$
\sum_{i=1}^{t} D_i(S_{i+1} - S_i)
$$&lt;/p>
&lt;p>The overall portfolio value is the sum of all $D_i(S_{i+1} - S_i) $ terms. Each term is influenced by:
• Consistency of Positive Movements: If most $ S_{i+1} - S_i &amp;gt; 0$ , and delta $D_i$ is positive, the sum of these terms will increase $P_{t+1}$ .
• Magnitude of Delta: The magnitude of $D_i$ amplifies or dampens the effect of $S_{i+1} - S_i$ . Higher delta (closer to 1) leads to greater sensitivity to price changes, increasing the portfolio’s reaction to upward movements.&lt;/p>
&lt;p>Considering the implications of normal distribution between the stock price, we could try to use non parametric modeling, like i talked about it &lt;a href="https://luis-zapatabobadilla.netlify.app/project/kernel-density-local-estimators/" target="_blank" rel="noopener">this post in the blog&lt;/a>.&lt;/p>
&lt;h2 id="conclusion">Conclusion&lt;/h2>
&lt;p>In this blog, we embarked on a journey through the world of Bitcoin options, using tools and strategies that bridge finance, data science, and machine learning. Let’s summarize what we achieved and the tools that made it possible:&lt;/p>
&lt;h3 id="key-takeaways">Key Takeaways:&lt;/h3>
&lt;ol>
&lt;li>
&lt;p>&lt;strong>Data Collection with the Deribit API&lt;/strong>:&lt;/p>
&lt;ul>
&lt;li>We demonstrated how to use the Deribit API to fetch historical Bitcoin options data efficiently.&lt;/li>
&lt;li>By automating the data retrieval process in Python, we handled the complexities of time-interval-based queries, ensuring well-structured datasets ready for analysis.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Understanding the Black-Scholes Model&lt;/strong>:&lt;/p>
&lt;ul>
&lt;li>The blog provided a clear and simplified explanation of the Black-Scholes formula, a cornerstone of options pricing in finance.&lt;/li>
&lt;li>We explored implied volatility, its significance in market sentiment, and limitations of the Black-Scholes model, enhancing the understanding of real-world market dynamics.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Applying Machine Learning for Forecasting&lt;/strong>:&lt;/p>
&lt;ul>
&lt;li>By employing a Random Forest model, we showcased a modern approach to predict implied volatility from market data.&lt;/li>
&lt;li>This non-parametric method allowed us to move beyond traditional assumptions and adapt to complex, real-world patterns in options trading.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Delta Strategy for Portfolio Management&lt;/strong>:&lt;/p>
&lt;ul>
&lt;li>We implemented a delta strategy, adjusting stock positions dynamically based on the delta of Bitcoin options.&lt;/li>
&lt;li>Through visualization and simulation, we highlighted how delta can act as a market signal and a tool for risk management in financial portfolios.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ol></description></item><item><title>Electricity Demand in Peru: A Regional Analysis</title><link>https://luis-zapatabobadilla.netlify.app/project/electricity-demand-analysis/</link><pubDate>Mon, 25 Nov 2024 00:00:00 +0000</pubDate><guid>https://luis-zapatabobadilla.netlify.app/project/electricity-demand-analysis/</guid><description>&lt;h2 id="motivation">Motivation&lt;/h2>
&lt;p>Electricity is a cornerstone of modern life, powering industries, homes, and essential services. Understanding the demand for electricity, particularly at the distribution level, is critical for effective resource planning and optimization. Accurate analysis of electricity demand can help identify usage patterns, forecast future needs, and ensure that energy supply meets demand reliably and sustainably. The code of this project can be seen &lt;a href="https://github.com/luisjo819UCLA/Covid-Impact-on-Energy-Peru" target="_blank" rel="noopener">here&lt;/a>.&lt;/p>
&lt;p>In this analysis, I focus on the demand of distribution companies (empresas distribuidoras) in Peru, which serve as intermediaries between large power generators and end-users like households and businesses. By studying the demand at the departmental (regional) level, this work provides valuable insights into how energy is consumed across different areas.&lt;/p>
&lt;p>The outcomes of such an analysis are highly relevant for:&lt;/p>
&lt;ul>
&lt;li>&lt;strong>Policy-making&lt;/strong>: Supporting government efforts to ensure equitable energy distribution and address regional disparities in electricity access.&lt;/li>
&lt;li>&lt;strong>Investment decisions&lt;/strong>: Assisting energy companies in identifying regions that require infrastructure upgrades or additional capacity.&lt;/li>
&lt;li>&lt;strong>Sustainability&lt;/strong>: Highlighting opportunities for renewable energy integration and reducing inefficiencies in the power grid.&lt;/li>
&lt;/ul>
&lt;p>By combining robust data analysis techniques with domain-specific knowledge, this project demonstrates a practical approach to tackling real-world challenges in the energy sector. This type of analysis is not only adaptable to electricity but can also be extended to other resource management problems, showcasing the versatility of data-driven solutions.&lt;/p>
&lt;h2 id="introduction">Introduction&lt;/h2>
&lt;p>Electricity in the country starts being generated at the generators, and then it is transported to both large consumers (such as large mines and factories) and distribution companies (empresas distribuidoras). It is through these distribution companies (empresas distribuidoras) that electricity is &lt;em>&amp;ldquo;distributed&amp;rdquo;&lt;/em> to regulated customers, such as households and medium or small factories.&lt;/p>
&lt;center>
&lt;img src="distribuidores.PNG" alt="Most common form of electricity distribution" width="400">
&lt;/center>
&lt;p>The purpose of this analysis is to measure the energy demand of the distribution companies (empresas distribuidoras), organized by department (departamento), in Peru.&lt;/p>
&lt;p>The demand of distribution companies (empresas distribuidoras) gives us an indicator of the demand from small and medium-sized businesses, as well as households.&lt;/p>
&lt;p>Households consume electricity constantly over time, so variations should be attributed to fluctuations in the demand from small and medium-sized factories/mines/others.&lt;/p>
&lt;p>The electrical map (mapa eléctrico) of Peru is available on the &lt;a href="https://www.coes.org.pe/Portal/Operacion/CaractSEIN/MapaSEIN" target="_blank" rel="noopener">&lt;strong>COES&lt;/strong>&lt;/a> website.&lt;/p>
&lt;center>
&lt;img src="Mapa_peru.PNG" alt="Source: COES" width="400">
&lt;/center>
&lt;p>The distribution of electricity in Peru takes the form of a circulatory system, in which the final branches expand like a tree.
This is because the final branches typically use a radial distribution system (sistema de distribución radial).&lt;/p>
&lt;p>&lt;img src="radial.png" alt="There are several distribution systems, one of them is the radial system">&lt;/p>
&lt;p>In the radial system (sistema radial), all the electricity demanded in the area enters through a single point.&lt;/p>
&lt;p>For example, in the case of Tumbes, all the lines originate from the Zorritos substation (sub-estación Zorritos) and distribute electricity to the Zarumilla, Tumbes, Zorritos, and Mancora substations (subestaciones Zarumilla, Tumbes, Zorritos y Mancora).&lt;/p>
&lt;p>&lt;img src="Tumbes_2.png" alt="SEIN Map (Mapa del SEIN). Source: COES.">&lt;/p>
&lt;p>As you might guess, this can lead to the problem of information being recorded more than once. We will explore this issue later.&lt;/p>
&lt;h3 id="source">Source&lt;/h3>
&lt;p>We will use as data the demand from agents (distributors) published by COES: &lt;a href="http://www.coes.org.pe/Portal/DemandaBarras/consulta/index?tipo=2#">http://www.coes.org.pe/Portal/DemandaBarras/consulta/index?tipo=2#&lt;/a>.&lt;/p>
&lt;p>This dataset shows the demand of distribution companies (empresas distribuidoras), measured at each available point (which could be substations, transmission lines, etc.).&lt;/p>
&lt;p>The information obtained from COES consists of two parts:&lt;/p>
&lt;ol>
&lt;li>
&lt;p>The description of the measurement points, which includes:&lt;/p>
&lt;p>i) The 5-digit code of the measurement point.&lt;br>
ii) The distribution company (empresa distribuidora).&lt;br>
iii) The substation/transmission line (subestación/linea de transmisión).&lt;br>
iv) The power or load transported by that point.&lt;br>
v) The geographical location.&lt;/p>
&lt;/li>
&lt;/ol>
&lt;p>Table: &lt;span id="tab:unnamed-chunk-1">&lt;/span>Table 1: Header Information (Información de cabecera):&lt;/p>
&lt;table>
&lt;thead>
&lt;tr>
&lt;th style="text-align:left">PUNTO.DE.MEDICIÓN&lt;/th>
&lt;th style="text-align:left">21577&lt;/th>
&lt;th style="text-align:left">22202&lt;/th>
&lt;th style="text-align:left">21558&lt;/th>
&lt;th style="text-align:left">22208&lt;/th>
&lt;/tr>
&lt;/thead>
&lt;tbody>
&lt;tr>
&lt;td style="text-align:left">NA&lt;/td>
&lt;td style="text-align:left">ELECTRO CENTRO&lt;/td>
&lt;td style="text-align:left">ELECTRO CENTRO&lt;/td>
&lt;td style="text-align:left">ELECTRO CENTRO&lt;/td>
&lt;td style="text-align:left">ELECTRO CENTRO&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td style="text-align:left">NA&lt;/td>
&lt;td style="text-align:left">4TP-410&lt;/td>
&lt;td style="text-align:left">CELDA-22.9KV-AUCAYACU&lt;/td>
&lt;td style="text-align:left">4TP-202&lt;/td>
&lt;td style="text-align:left">CELDA - 33KV - EJE MANTARO&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td style="text-align:left">NA&lt;/td>
&lt;td style="text-align:left">22.90&lt;/td>
&lt;td style="text-align:left">0&lt;/td>
&lt;td style="text-align:left">69&lt;/td>
&lt;td style="text-align:left">33&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td style="text-align:left">NA&lt;/td>
&lt;td style="text-align:left">ANDAYCHAGUA ELC&lt;/td>
&lt;td style="text-align:left">AUCAYACU&lt;/td>
&lt;td style="text-align:left">AYACUCHO&lt;/td>
&lt;td style="text-align:left">CAMPO ARMIÑO&lt;/td>
&lt;/tr>
&lt;/tbody>
&lt;/table>
&lt;ol start="2">
&lt;li>The observed data at each point, including the date and time when it was measured. The information is recorded every 30 minutes and is measured in &lt;strong>MW&lt;/strong>. To obtain a unit per hour (&lt;a href="https://es.wikipedia.org/wiki/Megavatio-hora" target="_blank" rel="noopener">&lt;strong>MWh&lt;/strong>&lt;/a>), the sum of one hour must be divided by 2.&lt;/li>
&lt;/ol>
&lt;p>Table: &lt;span id="tab:unnamed-chunk-2">&lt;/span>Table 2: Data measured at each point (Data medida en cada punto):&lt;/p>
&lt;table>
&lt;thead>
&lt;tr>
&lt;th style="text-align:left">PUNTO.DE.MEDICIÓN&lt;/th>
&lt;th style="text-align:left">21577&lt;/th>
&lt;th style="text-align:left">22202&lt;/th>
&lt;th style="text-align:left">21558&lt;/th>
&lt;th style="text-align:left">22208&lt;/th>
&lt;/tr>
&lt;/thead>
&lt;tbody>
&lt;tr>
&lt;td style="text-align:left">2020-02-15 00:30:00&lt;/td>
&lt;td style="text-align:left">0.833&lt;/td>
&lt;td style="text-align:left">0.96&lt;/td>
&lt;td style="text-align:left">9.1&lt;/td>
&lt;td style="text-align:left">0.487&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td style="text-align:left">2020-02-15 01:00:00&lt;/td>
&lt;td style="text-align:left">0.842&lt;/td>
&lt;td style="text-align:left">0.918&lt;/td>
&lt;td style="text-align:left">8.61&lt;/td>
&lt;td style="text-align:left">0.469&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td style="text-align:left">2020-02-15 01:30:00&lt;/td>
&lt;td style="text-align:left">0.771&lt;/td>
&lt;td style="text-align:left">0.906&lt;/td>
&lt;td style="text-align:left">8.37&lt;/td>
&lt;td style="text-align:left">0.463&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td style="text-align:left">2020-02-15 02:00:00&lt;/td>
&lt;td style="text-align:left">0.747&lt;/td>
&lt;td style="text-align:left">0.89&lt;/td>
&lt;td style="text-align:left">8.17&lt;/td>
&lt;td style="text-align:left">0.459&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td style="text-align:left">2020-02-15 02:30:00&lt;/td>
&lt;td style="text-align:left">0.725&lt;/td>
&lt;td style="text-align:left">0.884&lt;/td>
&lt;td style="text-align:left">8.15&lt;/td>
&lt;td style="text-align:left">0.462&lt;/td>
&lt;/tr>
&lt;/tbody>
&lt;/table>
&lt;p>Finally, I assign each substation (subestación) to a geographical department (departamento).&lt;br>
This is a personal classification, under which I consider that each distribution company (empresa distribuidora) has an assigned region where it distributes energy. For example, Luz del Sur only distributes energy in Lima.&lt;/p>
&lt;p>Other companies (empresas) are assigned to multiple departments (departamentos), so I also use Google Maps and &lt;a href="https://www.osinergmin.gob.pe/newweb/uploads/Publico/MapaSEIN/" target="_blank" rel="noopener">&lt;strong>OSINERMING&lt;/strong>&lt;/a> to locate the names of the substations (subestaciones).&lt;/p>
&lt;p>Table: &lt;span id="tab:unnamed-chunk-3">&lt;/span>Table 3: Organization by Departments (Organización en Departamentos):&lt;/p>
&lt;table>
&lt;thead>
&lt;tr>
&lt;th style="text-align:left">PUNTO.DE.MEDICIÓN&lt;/th>
&lt;th style="text-align:left">DEPARTAMENTO&lt;/th>
&lt;th style="text-align:left">FECHA.HORA./.SUBESTACIÓN&lt;/th>
&lt;th style="text-align:left">EMPRESA&lt;/th>
&lt;/tr>
&lt;/thead>
&lt;tbody>
&lt;tr>
&lt;td style="text-align:left">21520&lt;/td>
&lt;td style="text-align:left">ANCASH&lt;/td>
&lt;td style="text-align:left">PALLASCA&lt;/td>
&lt;td style="text-align:left">HIDRANDINA&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td style="text-align:left">21547&lt;/td>
&lt;td style="text-align:left">LA LIBERTAD&lt;/td>
&lt;td style="text-align:left">TAYABAMBA&lt;/td>
&lt;td style="text-align:left">HIDRANDINA&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td style="text-align:left">21644&lt;/td>
&lt;td style="text-align:left">AREQUIPA&lt;/td>
&lt;td style="text-align:left">REPARTICIÓN&lt;/td>
&lt;td style="text-align:left">SEAL&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td style="text-align:left">22365&lt;/td>
&lt;td style="text-align:left">LIMA&lt;/td>
&lt;td style="text-align:left">SANTA ROSA A.&lt;/td>
&lt;td style="text-align:left">ENEL DISTRIBUCION PERU&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td style="text-align:left">21594&lt;/td>
&lt;td style="text-align:left">PIURA&lt;/td>
&lt;td style="text-align:left">CONSTANTE&lt;/td>
&lt;td style="text-align:left">ELECTRO NOR OESTE&lt;/td>
&lt;/tr>
&lt;/tbody>
&lt;/table>
&lt;p>The organization by departments (departamentos) I created can be downloaded &lt;a href="https://github.com/luis-zapata-b/Datos/raw/master/nombres.RDS" target="_blank" rel="noopener">here&lt;/a>.&lt;/p>
&lt;p>One problem with summing this data by department (departamento) is that it can be redundant. As mentioned earlier, some measurement points (puntos de medición) originate from others, meaning the information is recorded two or more times.&lt;/p>
&lt;p>&lt;img src="Tumbes_2.png" alt="Source: COES (Fuente: COES)">&lt;/p>
&lt;p>A more practical way to observe this issue is by using the single-line diagram (diagrama unifilar) that shows direct connections. This map can also be downloaded from the &lt;a href="https://www.coes.org.pe/Portal/Operacion/CaractSEIN/DiagramaUnifilar" target="_blank" rel="noopener">&lt;strong>COES&lt;/strong>&lt;/a> website. Information is only counted more than once in radial systems (sistemas radiales).&lt;/p>
&lt;p>&lt;img src="Tumbes.PNG" alt="Single-Line Diagram (Diagrama Unifilar). Source: COES (Fuente: COES)">&lt;/p>
&lt;p>On the map, we can see how the demand of the Tumbes, Puerto Pizarro, and Mancora substations (subestaciones) is measured entirely by the line &lt;strong>LT-6665A&lt;/strong> towards the &lt;strong>Zorritos - Tumbes 60KV&lt;/strong> substation (subestación).&lt;/p>
&lt;p>We can confirm this in the following table:&lt;/p>
&lt;pre>&lt;code>## Joining with `by = join_by(PUNTO.DE.MEDICIÓN)`
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## Joining with `by = join_by(PUNTO.DE.MEDICIÓN, DEPARTAMENTO,
## `FECHA.HORA./.SUBESTACIÓN`, EMPRESA)`
&lt;/code>&lt;/pre>
&lt;p>Table: &lt;span id="tab:unnamed-chunk-5">&lt;/span>Table 4: Demand - Tumbes (Demanda - Tumbes)&lt;/p>
&lt;table>
&lt;thead>
&lt;tr>
&lt;th style="text-align:left">PUNTO.DE.MEDICIÓN&lt;/th>
&lt;th style="text-align:left">21588&lt;/th>
&lt;th style="text-align:left">21585&lt;/th>
&lt;th style="text-align:left">21586&lt;/th>
&lt;th style="text-align:left">21589&lt;/th>
&lt;th style="text-align:left">21590&lt;/th>
&lt;th style="text-align:left">21614&lt;/th>
&lt;th style="text-align:right">suma&lt;/th>
&lt;/tr>
&lt;/thead>
&lt;tbody>
&lt;tr>
&lt;td style="text-align:left">NA&lt;/td>
&lt;td style="text-align:left">ELECTRO NOR OESTE&lt;/td>
&lt;td style="text-align:left">ELECTRO NOR OESTE&lt;/td>
&lt;td style="text-align:left">ELECTRO NOR OESTE&lt;/td>
&lt;td style="text-align:left">ELECTRO NOR OESTE&lt;/td>
&lt;td style="text-align:left">ELECTRO NOR OESTE&lt;/td>
&lt;td style="text-align:left">ELECTRO NOR OESTE&lt;/td>
&lt;td style="text-align:right">NA&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td style="text-align:left">NA&lt;/td>
&lt;td style="text-align:left">TR-60/22.9/10kV&lt;/td>
&lt;td style="text-align:left">TR-60/33/10kV&lt;/td>
&lt;td style="text-align:left">TR-60/33/10kV&lt;/td>
&lt;td style="text-align:left">TR-60/22.9/10kV&lt;/td>
&lt;td style="text-align:left">TR-60/22.9/10kV&lt;/td>
&lt;td style="text-align:left">LT-6665A&lt;/td>
&lt;td style="text-align:right">NA&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td style="text-align:left">NA&lt;/td>
&lt;td style="text-align:left">22.90&lt;/td>
&lt;td style="text-align:left">10&lt;/td>
&lt;td style="text-align:left">33&lt;/td>
&lt;td style="text-align:left">10&lt;/td>
&lt;td style="text-align:left">22.90&lt;/td>
&lt;td style="text-align:left">60&lt;/td>
&lt;td style="text-align:right">NA&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td style="text-align:left">NA&lt;/td>
&lt;td style="text-align:left">PUERTO PIZARRO&lt;/td>
&lt;td style="text-align:left">TUMBES&lt;/td>
&lt;td style="text-align:left">TUMBES&lt;/td>
&lt;td style="text-align:left">ZARUMILLA&lt;/td>
&lt;td style="text-align:left">ZARUMILLA&lt;/td>
&lt;td style="text-align:left">ZORRITOS - TUMBES&lt;/td>
&lt;td style="text-align:right">NA&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td style="text-align:left">2020-02-15 00:00:00&lt;/td>
&lt;td style="text-align:left">6.07&lt;/td>
&lt;td style="text-align:left">9.82&lt;/td>
&lt;td style="text-align:left">5.62&lt;/td>
&lt;td style="text-align:left">3.11&lt;/td>
&lt;td style="text-align:left">1.98&lt;/td>
&lt;td style="text-align:left">26.6&lt;/td>
&lt;td style="text-align:right">26.60&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td style="text-align:left">2020-02-15 00:30:00&lt;/td>
&lt;td style="text-align:left">4.86&lt;/td>
&lt;td style="text-align:left">0.31&lt;/td>
&lt;td style="text-align:left">5.92&lt;/td>
&lt;td style="text-align:left">2.97&lt;/td>
&lt;td style="text-align:left">1.86&lt;/td>
&lt;td style="text-align:left">15.92&lt;/td>
&lt;td style="text-align:right">15.92&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td style="text-align:left">2020-02-15 01:00:00&lt;/td>
&lt;td style="text-align:left">4.57&lt;/td>
&lt;td style="text-align:left">9.1&lt;/td>
&lt;td style="text-align:left">5.85&lt;/td>
&lt;td style="text-align:left">2.88&lt;/td>
&lt;td style="text-align:left">1.77&lt;/td>
&lt;td style="text-align:left">24.17&lt;/td>
&lt;td style="text-align:right">24.17&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td style="text-align:left">2020-02-15 01:30:00&lt;/td>
&lt;td style="text-align:left">3.65&lt;/td>
&lt;td style="text-align:left">9.12&lt;/td>
&lt;td style="text-align:left">5.83&lt;/td>
&lt;td style="text-align:left">2.87&lt;/td>
&lt;td style="text-align:left">1.71&lt;/td>
&lt;td style="text-align:left">23.18&lt;/td>
&lt;td style="text-align:right">23.18&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td style="text-align:left">2020-02-15 02:00:00&lt;/td>
&lt;td style="text-align:left">3.68&lt;/td>
&lt;td style="text-align:left">9.59&lt;/td>
&lt;td style="text-align:left">5.65&lt;/td>
&lt;td style="text-align:left">2.57&lt;/td>
&lt;td style="text-align:left">1.42&lt;/td>
&lt;td style="text-align:left">22.91&lt;/td>
&lt;td style="text-align:right">22.91&lt;/td>
&lt;/tr>
&lt;/tbody>
&lt;/table>
&lt;p>As seen in both the table and the images above, the measurement point (punto de medición) on the transmission line &lt;strong>Zorritos-Tumbes - LT6665A&lt;/strong> already contains the sum of the points in Tumbes, Puerto Pizarro, and Zarumilla.&lt;/p>
&lt;h2 id="processing">Processing&lt;/h2>
&lt;p>For this presentation, I will analyze two time intervals: 29 days before the start of the coronavirus quarantine (March 16, 2020) and the 29 days following it.&lt;/p>
&lt;p>You can download the data I use from the &lt;a href="http://www.coes.org.pe/Portal/DemandaBarras/consulta/index?tipo=2" target="_blank" rel="noopener">COES&lt;/a> website or directly from &lt;a href="https://github.com/luis-zapata-b/Datos/raw/master/datos.RDS" target="_blank" rel="noopener">here&lt;/a>.&lt;/p>
&lt;p>The information can present a variety of issues:&lt;/p>
&lt;ol>
&lt;li>Missing values (valores omitidos).&lt;/li>
&lt;li>Incorrectly entered values (some numbers are multiplied by 10 or more).&lt;/li>
&lt;li>Outliers (irrationally different numbers that can persist for an entire day).&lt;/li>
&lt;/ol>
&lt;h3 id="handling-missing-values">Handling missing values&lt;/h3>
&lt;p>As an example of how to deal with the first type of error (missing values), I will use the data available for &lt;strong>Tumbes&lt;/strong>, according to my categorization, where missing values can be observed.&lt;/p>
&lt;center>
&lt;p>&lt;img src="https://luis-zapatabobadilla.netlify.app/project/electricity-demand-analysis/index.en_files/figure-html/unnamed-chunk-6-1.png" width="672" />&lt;/p>
&lt;/center>
&lt;p>Visually, it is clear that the series exhibit different seasonality: there are hours during the day when more electricity is consumed and days when less electricity is consumed (such as weekends).&lt;/p>
&lt;p>To impute (fill missing values) in the series, we first need to determine the frequency of these seasonal effects and then proceed to impute within each seasonality (for example, this series has a seasonality of 24 hours and another of 7 days). The package &lt;a href="https://cran.r-project.org/web/packages/imputeR/index.html" target="_blank" rel="noopener">&lt;em>&lt;strong>ImputeR&lt;/strong>&lt;/em>&lt;/a> allows us to do this using the &lt;em>na_seasplit&lt;/em> function.&lt;/p>
&lt;p>The &lt;code>imputeTS&lt;/code> package in R is a powerful tool designed specifically for handling missing values in time series data. One of its key functions, &lt;code>na_seasplit()&lt;/code>, is particularly effective for time series with strong seasonal patterns.&lt;/p>
&lt;p>In this analysis, I chose &lt;code>na_seasplit()&lt;/code> because it imputes missing values by splitting the time series into seasonal components, such as daily or weekly cycles. This approach ensures that the imputed values respect the inherent structure of the data. For example, electricity demand often exhibits predictable patterns based on the time of day or day of the week. By accounting for these patterns, &lt;code>na_seasplit()&lt;/code> provides more realistic and accurate imputations compared to generic methods like mean or linear interpolation.&lt;/p>
&lt;p>This method is especially useful when:&lt;/p>
&lt;ul>
&lt;li>Missing values occur in a regular seasonal context (e.g., during certain hours or days).&lt;/li>
&lt;li>Maintaining the integrity of periodic fluctuations in the data is essential for accurate downstream analysis.&lt;/li>
&lt;/ul>
&lt;p>Overall, the use of &lt;code>imputeTS&lt;/code> and &lt;code>na_seasplit()&lt;/code> demonstrates how specialized tools can enhance the reliability of results, particularly in domains like electricity demand analysis where seasonality plays a crucial role.&lt;/p>
&lt;p>The theory behind this process is not the focus of this analysis; however, I recommend the book &lt;a href="https://otexts.com/fpp2/" target="_blank" rel="noopener">&lt;em>&lt;strong>&amp;ldquo;Forecasting: Principles and Practice&amp;rdquo;&lt;/strong>&lt;/em>&lt;/a> by Rob Hyndman and his course on &lt;a href="https://www.datacamp.com/courses/forecasting-using-r" target="_blank" rel="noopener">Data Camp&lt;/a> for further exploration.&lt;/p>
&lt;center>
&lt;img src="https://luis-zapatabobadilla.netlify.app/project/electricity-demand-analysis/index.en_files/figure-html/unnamed-chunk-7-1.png" width="672" />
&lt;/center>
&lt;p>As observed in the graph, the missing values (valores omitidos) have been replaced, considering both the daily and weekly seasonality of the series.&lt;/p>
&lt;p>A quicker option would be to aggregate the data by day and impute missing values considering only daily seasonality. This will be the method used moving forward, as it helps to avoid errors.&lt;/p>
&lt;hr>
&lt;h3 id="addressing-outliers">Addressing outliers&lt;/h3>
&lt;p>To address outliers (valores atípicos), I use the measurements in the Lambayeque department (departamento), according to my classification, as an example. There is an outlier in the measurement point (punto de medición) &lt;strong>CAYALTI&lt;/strong>, which shows an irrational consumption for one day.&lt;/p>
&lt;p>&lt;img src="https://luis-zapatabobadilla.netlify.app/project/electricity-demand-analysis/index.en_files/figure-html/unnamed-chunk-8-1.png" width="672" />&lt;/p>
&lt;p>Outliers can significantly distort analysis, especially in datasets with numerical values like electricity demand.
To avoid this type of error, I use two filters:&lt;/p>
&lt;p>i) First, I eliminate any value that exceeds a rational consumption within the 30-minute measurement interval (e.g., 300 MWh).&lt;/p>
&lt;p>ii) Second, I eliminate values that exceed 4 times the standard deviation of each series. This approach aims to remove non-recurrent outliers. This method works by identifying data points that deviate excessively from the average pattern of the series, which are likely to be errors or anomalies.&lt;/p>
&lt;p>This approach is effective because:&lt;/p>
&lt;ul>
&lt;li>It adapts to the natural variability of each series, ensuring that normal fluctuations are not mistakenly removed.&lt;/li>
&lt;li>The 4-standard-deviation threshold strikes a balance between sensitivity and robustness, capturing extreme outliers while retaining most valid data points (on a normal distribution, 99% of the values lie within 3 standart deviations).&lt;/li>
&lt;/ul>
&lt;p>By applying this filter, I can clean the data in a systematic way, ensuring that the analysis focuses on meaningful trends without being skewed by extreme and unlikely values.&lt;/p>
&lt;p>In the following image, it can be observed how the outliers (valores atípicos) in &lt;strong>CAYALTI&lt;/strong> were removed, and subsequently, the missing value was imputed to fill the series.&lt;/p>
&lt;p>However, at the point &lt;strong>TUMÁN&lt;/strong>, a third type of error is still present: for one day, the data was arbitrarily recorded at an incorrect scale (multiplied by 100).&lt;/p>
&lt;center>
&lt;img src="https://luis-zapatabobadilla.netlify.app/project/electricity-demand-analysis/index.en_files/figure-html/unnamed-chunk-10-1.png" width="672" />
&lt;/center>
&lt;p>The only way to correct this type of error is to visually inspect the series and manually adjust them.&lt;br>
These types of outliers can affect the interpretation of our data. For example, when analyzing demand by department (departamento), the measurement error in Lambayeque could lead to a misinterpretation.&lt;/p>
&lt;p>This code processes electricity consumption data by cleaning, normalizing, and imputing missing values while addressing outliers to prepare it for analysis and visualization. It groups data by date and department, summing electricity demand across all relevant points of measurement for each department. Seasonal imputation (&lt;code>na_seasplit&lt;/code>) is applied to ensure smooth trends, and outliers are handled using scaling and thresholding. Finally, it generates a faceted plot showing electricity consumption trends for each department, marking the impact of quarantine (March 15, 2020) and highlighting any anomalies, such as the outlier in Lambayeque. It does this by aggregating all the points of measurement per department.&lt;/p>
&lt;pre>&lt;code class="language-r">cont = z %&amp;gt;%
mutate_if(is.character,as.double) %&amp;gt;%
mutate(Fecha = as_date(PUNTO.DE.MEDICIÓN - minutes(30))) %&amp;gt;%
select(-PUNTO.DE.MEDICIÓN) %&amp;gt;%
mutate(Fecha2 = if_else(Fecha &amp;gt; dmy(&amp;quot;15-03-2020&amp;quot;),&amp;quot;DC&amp;quot;,&amp;quot;AC&amp;quot;)) %&amp;gt;%
mutate_at(vars(-c(Fecha,Fecha2)),limite) %&amp;gt;%
mutate_at(vars(-c(Fecha,Fecha2)),abs) %&amp;gt;%
group_by(Fecha2) %&amp;gt;%
mutate_at(vars(-c(Fecha,Fecha2)),scale2) %&amp;gt;%
ungroup() %&amp;gt;%
mutate_at(vars(-c(Fecha,Fecha2)),na_ma,maxgap=47)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-r">pordepa= cont %&amp;gt;%
{.[, which(colMeans(!is.na(.)) &amp;gt; 0.5)]} %&amp;gt;%
{.[, which(colMeans(.!= 0,na.rm = TRUE) &amp;gt; 0.5)]} %&amp;gt;%
group_by(Fecha2) %&amp;gt;%
mutate_at(vars(-c(Fecha,Fecha2)), na_seasplit,algorithm=&amp;quot;ma&amp;quot;) %&amp;gt;%
ungroup() %&amp;gt;%
mutate_at(vars(-c(Fecha,Fecha2)), funs(. / 2000)) %&amp;gt;%
pivot_longer(-c(Fecha,Fecha2),names_to = &amp;quot;PUNTO.DE.MEDICIÓN&amp;quot;,values_to = &amp;quot;gwh&amp;quot;) %&amp;gt;%
left_join(nombres) %&amp;gt;%
group_by(Fecha,DEPARTAMENTO) %&amp;gt;%
summarise(gwh = sum(gwh)) %&amp;gt;%
ungroup()
factorizar = pordepa %&amp;gt;%
filter(Fecha &amp;lt; as_date(&amp;quot;2020-03-15&amp;quot;)) %&amp;gt;%
group_by(DEPARTAMENTO) %&amp;gt;%
summarise(gwh = sum(gwh)) %&amp;gt;%
arrange(gwh) %&amp;gt;%
select(DEPARTAMENTO)%&amp;gt;%
tail(7) %&amp;gt;%
{rbind(c(&amp;quot;OTROS&amp;quot;),.)}
nombres = mutate(nombres,DEPARTAMENTO = ifelse(nombres$DEPARTAMENTO %in% factorizar[[1]],DEPARTAMENTO,&amp;quot;OTROS&amp;quot;))
&lt;/code>&lt;/pre>
&lt;center>
&lt;pre>&lt;code class="language-r">cont %&amp;gt;%
{.[, which(colMeans(!is.na(.)) &amp;gt; 0.5)]} %&amp;gt;%
group_by(Fecha2) %&amp;gt;%
ungroup() %&amp;gt;%
mutate_at(vars(-c(Fecha,Fecha2)), funs(. / 2000)) %&amp;gt;%
pivot_longer(-c(Fecha,Fecha2),names_to = &amp;quot;PUNTO.DE.MEDICIÓN&amp;quot;,values_to = &amp;quot;gwh&amp;quot;) %&amp;gt;%
left_join(nombres) %&amp;gt;%
group_by(Fecha,DEPARTAMENTO) %&amp;gt;%
summarise(gwh = sum(gwh)) %&amp;gt;%
ungroup() %&amp;gt;%
group_by(DEPARTAMENTO) %&amp;gt;%
mutate(gwh = na_seasplit(gwh,find_frequency = TRUE)) %&amp;gt;%
ungroup() %&amp;gt;%
ggplot(aes(x=Fecha, y =gwh)) +
geom_line() +
facet_wrap(.~factor(DEPARTAMENTO,levels = rev(factorizar[[1]])),scales = &amp;quot;free_y&amp;quot;) +
scale_x_date(date_breaks = &amp;quot;1 weeks&amp;quot;,date_labels = &amp;quot;%d-%b&amp;quot;,expand = c(0,0)) +
geom_vline(xintercept = as_date(&amp;quot;2020-03-15&amp;quot;),size=1.5,linetype=&amp;quot;dashed&amp;quot;) +
labs(title = &amp;quot;Electricity Consumption - Distribution Companies (Consumo Eléctrico - Empresas Distribuidoras)&amp;quot;,subtitle = &amp;quot;Electricity consumption measured at stations owned by distribution companies (empresas distribuidoras).&amp;quot;,
y = element_blank(),x=element_blank(),fill=&amp;quot;Department (Departamento)&amp;quot;, caption = &amp;quot;Source: COES. Author: Luis José Zapata Bobadilla.&amp;quot;) +
theme_gray()+
theme(axis.text.x.bottom = element_text(angle = 90,hjust=0.7)) +
ggforce::geom_mark_ellipse(aes(filter=(gwh &amp;gt; 4)&amp;amp;(DEPARTAMENTO==&amp;quot;LAMBAYEQUE&amp;quot;)),fill=&amp;quot;red&amp;quot;)
&lt;/code>&lt;/pre>
&lt;p>&lt;img src="https://luis-zapatabobadilla.netlify.app/project/electricity-demand-analysis/index.en_files/figure-html/unnamed-chunk-13-1.png" width="672" />&lt;/p>
&lt;/center>
&lt;h4 id="key-observations">Key Observations:&lt;/h4>
&lt;ol>
&lt;li>
&lt;p>&lt;strong>General Trends Across Departments&lt;/strong>:&lt;/p>
&lt;ul>
&lt;li>All departments show a clear decrease in electricity consumption after March 16, 2020, reflecting the impact of quarantine measures on economic activity.&lt;/li>
&lt;li>Departments like &lt;strong>Lima&lt;/strong> and &lt;strong>Piura&lt;/strong>, which contribute heavily to overall electricity demand, show a substantial drop.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Notable Patterns&lt;/strong>:&lt;/p>
&lt;ul>
&lt;li>The periodic spikes suggest weekly consumption cycles, particularly visible in regions like &lt;strong>Lima&lt;/strong> and &lt;strong>Piura&lt;/strong>.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Outlier in Lambayeque&lt;/strong>:&lt;/p>
&lt;ul>
&lt;li>The &lt;strong>Lambayeque&lt;/strong> panel highlights an outlier (shaded red) after March 30, indicating a data registration error where recorded consumption was unrealistically high. This emphasizes the need for thorough data cleaning and verification to ensure accurate analysis.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Consistency of Patterns&lt;/strong>:&lt;/p>
&lt;ul>
&lt;li>While the drop after quarantine is expected, the consistent patterns across departments highlight the robustness of the recorded trends, aside from the noted outlier in Lambayeque, when we aggregate by points of measurement.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ol>
&lt;h3 id="addressing-redudant-information">Addressing redudant information&lt;/h3>
&lt;p>A large portion of the information measured in the system is redundant, meaning it is repeated. As more measurement points (puntos de medición) are added, the redundant information in each department (departamento) increases exponentially. If demand is summed by department without applying any filters, some departments may display consumption higher than the actual values. This is the case for Lima in our dataset.&lt;/p>
&lt;p>An effective way to address this problem is to exclude every measurement point (punto de medición) and instead focus only on those points that sum the majority of the measurement points in each department (departamento), as seen with the Zorritos - Tumbes point in the earlier example.&lt;/p>
&lt;center>
&lt;pre>&lt;code>## Joining with `by = join_by(PUNTO.DE.MEDICIÓN)`
## `summarise()` has grouped output by 'Fecha'. You can override using the
## `.groups` argument.
&lt;/code>&lt;/pre>
&lt;p>&lt;img src="https://luis-zapatabobadilla.netlify.app/project/electricity-demand-analysis/index.en_files/figure-html/unnamed-chunk-14-1.png" width="672" />&lt;/p>
&lt;/center>
The plot provides a visual representation of the changes in demand over time, categorized by department.
&lt;h3 id="key-observations-1">Key Observations:&lt;/h3>
&lt;ol>
&lt;li>
&lt;p>&lt;strong>Temporal Trends&lt;/strong>:&lt;/p>
&lt;ul>
&lt;li>The x-axis represents dates, ranging from mid-February to mid-April, showing daily electricity consumption.&lt;/li>
&lt;li>There is a noticeable decrease in electricity demand starting around &lt;strong>March 16, 2020&lt;/strong>, marked by the vertical dashed line. This corresponds to the start of the COVID-19 quarantine period in Peru, reflecting reduced industrial and business activity.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Departmental Breakdown&lt;/strong>:&lt;/p>
&lt;ul>
&lt;li>The stacked area chart highlights the contribution of each department to the total electricity demand.&lt;/li>
&lt;li>&lt;strong>Lima (pink)&lt;/strong> consistently accounts for the largest share of electricity consumption, reflecting its role as the country&amp;rsquo;s economic hub.&lt;/li>
&lt;li>Other significant contributors include &lt;strong>Piura (blue)&lt;/strong>, &lt;strong>La Libertad (green)&lt;/strong>, and &lt;strong>Arequipa (teal)&lt;/strong>.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Impact of Quarantine&lt;/strong>:&lt;/p>
&lt;ul>
&lt;li>The reduction in demand after March 16 is visible across all departments, with a sharp decline in Lima and noticeable decreases in other regions like Arequipa and Lambayeque.&lt;/li>
&lt;li>Smaller departments grouped under &amp;ldquo;OTROS&amp;rdquo; (Others) also show a slight decline, though their contribution to overall demand is relatively small.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Seasonal or Weekly Patterns&lt;/strong>:&lt;/p>
&lt;ul>
&lt;li>The wavelike structure in the plot suggests periodic fluctuations, likely driven by weekday-weekend patterns in electricity usage.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ol>
&lt;h3 id="insights">Insights:&lt;/h3>
&lt;p>This plot effectively demonstrates how a major event (quarantine) can impact electricity demand across different regions. It highlights the significance of Lima and other key regions while showcasing how such analyses in real time can provide actionable insights for policymakers and energy planners.&lt;/p>
&lt;h2 id="conclusion">Conclusion&lt;/h2>
&lt;p>As mentioned earlier, the best way to avoid these types of problems is to focus solely on measurement points (puntos de medición) that aggregate the majority of other points (such as the Zorritos - Tumbes point).&lt;/p>
&lt;p>To achieve this, it is necessary to have regional knowledge of which points aggregate others. This can be done by reviewing the single-line diagram (diagrama unifilar) from COES.&lt;/p>
&lt;p>It is essential to identify the relevant measurement points (puntos de medición) that prevent redundancies in each region.&lt;/p>
&lt;p>This is a pending task that would enable a reliable analysis by department (departamento).&lt;/p>
&lt;p>It is worth noting that COES already publishes compiled information for three zones of Peru (North, Central, and South) in its Daily Evaluation Report (&lt;a href="https://www.coes.org.pe/Portal/PostOperacion/Reportes/Ieod" target="_blank" rel="noopener">IEOD&lt;/a>) under the sheet &amp;ldquo;&lt;strong>Demand by Zone&lt;/strong>&amp;rdquo; (Demanda por zona). Therefore, if the goal is to obtain compiled information for these zones, it is easier to download it directly from the COES website.&lt;/p>
&lt;p>However, if the objective is to analyze the information by department, the approach outlined in this analysis would be the most appropriate.&lt;/p>
&lt;p>This analysis illustrates my proficiency in data cleaning, statistical modeling, and visualization using R, along with my ability to adapt to technical topics like electricity distribution systems.&lt;/p>
&lt;p>All the files used in this analysis can be downloaded from the following link:&lt;br>
&lt;a href="https://github.com/luis-zapata-b/Datos/archive/master.zip" target="_blank" rel="noopener">https://github.com/luis-zapata-b/Datos/archive/master.zip&lt;/a>&lt;/p>
&lt;h3 id="final-conclusion">Final Conclusion&lt;/h3>
&lt;p>This analysis highlights the critical role of data-driven methodologies in understanding electricity demand at the regional level, emphasizing its importance for policy-making, investment decisions, and sustainability efforts. By addressing key challenges such as redundant data, missing values, and outliers, the approach presented ensures accurate and actionable insights into energy consumption trends across Peru&amp;rsquo;s departments.&lt;/p>
&lt;p>The results demonstrate how external factors, like the COVID-19 quarantine, can significantly impact electricity demand, with clear patterns observed across major regions like Lima, Piura, and Lambayeque. Moreover, the use of advanced imputation methods and outlier filtering techniques underscores the importance of rigorous data preparation in ensuring reliable conclusions.&lt;/p>
&lt;p>The mechanism developed in this study not only provides valuable insights into regional electricity consumption but also establishes a reproducible framework. By leveraging publicly available data from COES, this methodology can be replicated and scaled for future analyses, supporting government efforts to optimize resource allocation and plan for sustainable energy systems.&lt;/p>
&lt;p>Overall, this project showcases the integration of technical expertise in R, critical thinking, and adaptability to complex topics, demonstrating a robust foundation for tackling real-world challenges in resource management and energy analysis.&lt;/p></description></item><item><title>Exploring Neural Networks with Pytorch</title><link>https://luis-zapatabobadilla.netlify.app/project/2024-11-22-neural-network/</link><pubDate>Sat, 23 Nov 2024 00:00:00 +0000</pubDate><guid>https://luis-zapatabobadilla.netlify.app/project/2024-11-22-neural-network/</guid><description>&lt;p>In this blog, we’ll explore how to use a neural network built with PyTorch to predict handwritten digits from the MNIST dataset. Along the way, we’ll break down key concepts like tensors, neural network architecture, and training processes, making it easier to understand the fundamental building blocks of deep learning.&lt;/p>
&lt;p>The MNIST dataset, a collection of 28x28 grayscale images of digits (0–9), is a classic benchmark for machine learning. Our goal is to create a model that accurately recognizes these digits using the power of neural networks.&lt;/p>
&lt;h2 id="introduction">Introduction&lt;/h2>
&lt;p>Machine learning is a transformative tool for modeling complex relationships in data. Neural networks, a class of machine learning models inspired by the human brain, are particularly adept at handling non-linear relationships. This post explores their application, focusing on tensors, neural networks, and their underlying theory.&lt;/p>
&lt;hr>
&lt;h2 id="tensors-the-backbone-of-neural-networks">Tensors: The Backbone of Neural Networks&lt;/h2>
&lt;p>At the heart of neural networks lie &lt;strong>tensors&lt;/strong>, multidimensional arrays that generalize matrices to higher dimensions. They efficiently handle complex data like images, text, or time series, making them critical for machine learning.&lt;/p>
&lt;p>For instance, a scalar is a rank-0 tensor (a single number), a vector is rank-1 (a sequence of numbers), and a matrix is rank-2 (a 2D grid). Consider This 2D input tensor &lt;code>x&lt;/code>, which could represent a dataset:&lt;/p>
&lt;pre>&lt;code class="language-python">import torch
x = torch.tensor([[1, 2], [3, 4], [5, 6]]) # A 2D tensor (matrix)
print(x)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## tensor([[1, 2],
## [3, 4],
## [5, 6]])
&lt;/code>&lt;/pre>
&lt;p>Tensors flow through the network, undergoing operations like matrix multiplication and activation functions, ultimately producing outputs. Their ability to efficiently process data on GPUs makes tensors indispensable for modern machine learning.&lt;/p>
&lt;h2 id="neural-network-architecture">Neural Network Architecture&lt;/h2>
&lt;p>A neural network is composed of layers of interconnected nodes (neurons) that process input data and produce predictions:&lt;/p>
&lt;ul>
&lt;li>&lt;strong>Input Layer&lt;/strong>: Receives the raw data (e.g., tensors representing images, text, or numbers) and passes it to the next layer.&lt;/li>
&lt;li>&lt;strong>Hidden Layers&lt;/strong>: These intermediate layers perform computations, applying weights, biases, and activation functions to extract meaningful patterns and features.&lt;/li>
&lt;li>&lt;strong>Output Layer&lt;/strong>: Generates the final output, such as classifications, predictions, or probabilities.&lt;/li>
&lt;/ul>
&lt;p>Each connection between neurons has a weight that adjusts during training, enabling the network to learn from data by minimizing error. Activation functions like ReLU or Sigmoid introduce non-linearity, allowing the network to model complex relationships.&lt;/p>
&lt;p>&lt;img src="https://upload.wikimedia.org/wikipedia/commons/6/60/ArtificialNeuronModel_english.png" alt="Neuron - 1 layer">&lt;/p>
&lt;h3 id="example-model-configuration">Example Model Configuration&lt;/h3>
&lt;p>The neural network model in this example uses a simple feedforward architecture. We define it as:&lt;/p>
&lt;pre>&lt;code class="language-python">import torch.nn as nn
class SimpleNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(SimpleNN, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(hidden_size, output_size)
def forward(self, x):
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
input_size = 28 * 28 # Example: 28x28 images
hidden_size = 128
output_size = 10 # Example: 10 classes
model = SimpleNN(input_size, hidden_size, output_size)
&lt;/code>&lt;/pre>
&lt;p>Lets dive into a more detailed code explanation of the neural network architecture.&lt;/p>
&lt;h3 id="1-the-dataset-mnist">1. The Dataset: MNIST&lt;/h3>
&lt;p>The MNIST dataset is a collection of grayscale images of handwritten digits, commonly used as a benchmark dataset in machine learning. Each image is:&lt;/p>
&lt;ul>
&lt;li>&lt;strong>28x28 pixels&lt;/strong> in size.&lt;/li>
&lt;li>Labeled with a number from &lt;strong>0 to 9&lt;/strong> (10 classes in total).&lt;/li>
&lt;/ul>
&lt;h4 id="code-explanation">Code Explanation&lt;/h4>
&lt;pre>&lt;code class="language-python">from torchvision import datasets, transforms
# Define transformations for the dataset
transform = transforms.Compose([transforms.ToTensor()])
&lt;/code>&lt;/pre>
&lt;ul>
&lt;li>&lt;strong>Transforms&lt;/strong>: The dataset is preprocessed using &lt;code>transforms.ToTensor()&lt;/code>, which converts the images into PyTorch tensors (normalized to [0, 1]).&lt;/li>
&lt;li>&lt;strong>Compose&lt;/strong>: Allows multiple transformations to be chained together. Here, only the conversion to a tensor is applied.&lt;/li>
&lt;/ul>
&lt;pre>&lt;code class="language-python"># Load training and testing datasets
train_dataset = datasets.MNIST(root='./data', train=True, transform=transform, download=True)
test_dataset = datasets.MNIST(root='./data', train=False, transform=transform, download=True)
&lt;/code>&lt;/pre>
&lt;ul>
&lt;li>&lt;strong>&lt;code>train=True&lt;/code>/&lt;code>False&lt;/code>&lt;/strong>: Indicates whether to load the training or testing split of the MNIST dataset.&lt;/li>
&lt;/ul>
&lt;pre>&lt;code class="language-python"># Create DataLoaders
train_loader = DataLoader(train_dataset, batch_size=100, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=100, shuffle=False)
&lt;/code>&lt;/pre>
&lt;ul>
&lt;li>&lt;strong>&lt;code>DataLoader&lt;/code>&lt;/strong>: A utility that:
&lt;ul>
&lt;li>Loads data in &lt;strong>batches&lt;/strong> (size &lt;code>batch_size=100&lt;/code> here).&lt;/li>
&lt;li>&lt;strong>Shuffles&lt;/strong> the training data for randomness.&lt;/li>
&lt;li>Ensures efficient data loading during training/testing.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ul>
&lt;p>A &lt;strong>batch&lt;/strong> refers to a subset of the dataset processed at one time during training or inference. Instead of feeding the entire dataset to the model, which can be computationally expensive and memory-intensive, the data is divided into smaller groups (batches). Each batch passes through the network, computes predictions, and calculates the loss. The model then updates its weights based on the average loss of the batch. This approach balances efficiency and learning, making training manageable even for large datasets like MNIST.&lt;/p>
&lt;h3 id="2-the-neural-network-simplenn">&lt;strong>2. The Neural Network: &lt;code>SimpleNN&lt;/code>&lt;/strong>&lt;/h3>
&lt;p>A neural network is composed of layers of interconnected nodes (neurons) that process input data and produce predictions. Here&amp;rsquo;s how &lt;code>SimpleNN&lt;/code> is structured:&lt;/p>
&lt;h4 id="code-explanation-1">Code Explanation&lt;/h4>
&lt;pre>&lt;code class="language-python">class SimpleNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(SimpleNN, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(hidden_size, output_size)
&lt;/code>&lt;/pre>
&lt;ul>
&lt;li>&lt;strong>&lt;code>nn.Module&lt;/code>&lt;/strong>: Base class for all PyTorch models.&lt;/li>
&lt;li>&lt;strong>&lt;code>__init__&lt;/code>&lt;/strong>: Defines the structure of the neural network.
&lt;ul>
&lt;li>&lt;strong>&lt;code>input_size&lt;/code>&lt;/strong>: The number of input features (28x28 = 784 for MNIST images flattened into vectors).&lt;/li>
&lt;li>&lt;strong>&lt;code>hidden_size&lt;/code>&lt;/strong>: Number of neurons in the hidden layer (set to 128 here).&lt;/li>
&lt;li>&lt;strong>&lt;code>output_size&lt;/code>&lt;/strong>: The number of output classes (10 digits: 0 to 9).&lt;/li>
&lt;li>&lt;strong>&lt;code>fc1&lt;/code>&lt;/strong>: A fully connected (dense) layer that transforms the input into the hidden layer with dimensions &lt;code>[input_size -&amp;gt; hidden_size]&lt;/code>.&lt;/li>
&lt;li>&lt;strong>&lt;code>ReLU&lt;/code>&lt;/strong>: Applies the &lt;strong>ReLU activation function&lt;/strong>, introducing non-linearity to the model. ReLU replaces negative values with 0.&lt;/li>
&lt;li>&lt;strong>&lt;code>fc2&lt;/code>&lt;/strong>: A fully connected layer that transforms the hidden layer output to the final output layer with dimensions &lt;code>[hidden_size -&amp;gt; output_size]&lt;/code>.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ul>
&lt;pre>&lt;code class="language-python"> def forward(self, x):
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
&lt;/code>&lt;/pre>
&lt;ul>
&lt;li>&lt;strong>&lt;code>forward&lt;/code>&lt;/strong>: Defines how data flows through the network.&lt;/li>
&lt;/ul>
&lt;ol>
&lt;li>Passes the input through &lt;code>fc1&lt;/code> (input layer).&lt;/li>
&lt;li>Applies the ReLU activation.&lt;/li>
&lt;li>Passes the result through &lt;code>fc2&lt;/code> (output layer).&lt;/li>
&lt;li>Returns the final output.&lt;/li>
&lt;/ol>
&lt;p>&lt;strong>init&lt;/strong> establishes the components of the network, and &lt;strong>forward&lt;/strong> dictates how those components are used during the forward pass. Together, they form the blueprint and operational flow of the model.&lt;/p>
&lt;p>The &lt;strong>ReLU activation function&lt;/strong> (Rectified Linear Unit) is one of the most commonly used activation functions in neural networks, especially in deep learning. Its popularity stems from its simplicity, efficiency, and effectiveness.&lt;/p>
&lt;h3 id="what-is-relu">&lt;strong>What Is ReLU?&lt;/strong>&lt;/h3>
&lt;p>The ReLU function is defined mathematically as:&lt;/p>
&lt;p>$$
f(x) =
\begin{cases}
x &amp;amp; \text{if } x &amp;gt; 0 \\&lt;br>
0 &amp;amp; \text{if } x \leq 0
\end{cases}
$$
Or simply:&lt;/p>
&lt;p>$$
f(x) = \max(0, x)
$$
In words, ReLU outputs the input value directly if it&amp;rsquo;s positive and outputs &lt;strong>0&lt;/strong> for any negative value.&lt;/p>
&lt;h3 id="why-use-an-activation-function">&lt;strong>Why Use an Activation Function?&lt;/strong>&lt;/h3>
&lt;p>Activation functions introduce &lt;strong>non-linearity&lt;/strong> into the neural network. Without an activation function, the network would simply consist of linear transformations (matrix multiplications), which means it would only be able to model &lt;strong>linear relationships&lt;/strong> in data. Non-linear activation functions, like ReLU, allow the network to model &lt;strong>complex, non-linear relationships&lt;/strong>.&lt;/p>
&lt;p>ReLU is applied to the output of each neuron (or unit) in a layer after the weighted sum of inputs and bias. Here&amp;rsquo;s what happens:&lt;/p>
&lt;ol>
&lt;li>A neuron calculates a &lt;strong>weighted sum&lt;/strong> of its inputs:&lt;/li>
&lt;/ol>
&lt;p>$$ z = \mathbf{w} \cdot \mathbf{x} + b, \\ \&lt;br>
where: \\ \&lt;br>
\mathbf{w}: Weights, \\ \&lt;br>
\mathbf{x}: Inputs, \\ \&lt;br>
b: Bias $$&lt;/p>
&lt;ol start="2">
&lt;li>The ReLU function is applied to (z) to produce the neuron’s output:&lt;/li>
&lt;/ol>
&lt;p>$$a = f(z) = \max(0, z)$$&lt;/p>
&lt;p>This process is repeated across all neurons in the layer.&lt;/p>
&lt;hr>
&lt;h3 id="benefits-of-relu">&lt;strong>Benefits of ReLU&lt;/strong>&lt;/h3>
&lt;ol>
&lt;li>&lt;strong>Simplicity&lt;/strong>: ReLU is computationally inexpensive because it involves simple thresholding at zero. Unlike other activation functions, like sigmoid or tanh, it does not require complex mathematical operations like exponentials.&lt;/li>
&lt;li>&lt;strong>Avoids Vanishing Gradients&lt;/strong>:
&lt;ul>
&lt;li>Activation functions like sigmoid and tanh compress outputs into a small range, which can cause gradients to vanish during backpropagation, making learning very slow in deep networks.&lt;/li>
&lt;li>ReLU doesn’t compress values, so the gradient is preserved for positive inputs, enabling faster and more stable learning.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;strong>Efficient Sparsity&lt;/strong>:
&lt;ul>
&lt;li>Since ReLU outputs &lt;strong>0&lt;/strong> for negative inputs, it introduces sparsity in the network. Sparsity helps by reducing the dependency between neurons and improving computation efficiency.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ol>
&lt;ul>
&lt;li>ReLU introduces non-linearity between the input and output layers, allowing the network to learn complex patterns in the MNIST dataset.&lt;/li>
&lt;li>Its simplicity and efficiency make it an ideal choice for a small-scale network like this one.&lt;/li>
&lt;/ul>
&lt;h3 id="visualizing-relu">&lt;strong>Visualizing ReLU&lt;/strong>&lt;/h3>
&lt;p>Here’s how ReLU behaves visually:&lt;/p>
&lt;ul>
&lt;li>For $(x &amp;gt; 0)$, ReLU outputs the same value.&lt;/li>
&lt;li>For $(x \leq 0)$, ReLU outputs 0.&lt;/li>
&lt;/ul>
&lt;p>&lt;img src="https://upload.wikimedia.org/wikipedia/commons/6/6c/Rectifier_and_softplus_functions.svg" alt="ReLU Graph">&lt;/p>
&lt;p>In summary, ReLU is simple, fast, and effective for training deep neural networks, making it the default choice in many modern architectures.&lt;/p>
&lt;h3 id="3-model-initialization">&lt;strong>3. Model Initialization&lt;/strong>&lt;/h3>
&lt;pre>&lt;code class="language-python">input_size = 28 * 28 # Example: 28x28 images
hidden_size = 128
output_size = 10 # Example: 10 classes
model = SimpleNN(input_size, hidden_size, output_size)
&lt;/code>&lt;/pre>
&lt;ul>
&lt;li>&lt;strong>&lt;code>input_size = 28 * 28&lt;/code>&lt;/strong>: Each MNIST image is a 28x28 matrix. Before feeding it into the model, it&amp;rsquo;s flattened into a 1D tensor of size 784.&lt;/li>
&lt;li>&lt;strong>&lt;code>hidden_size = 128&lt;/code>&lt;/strong>: The hidden layer contains 128 neurons. This is a hyperparameter and can be adjusted.&lt;/li>
&lt;li>&lt;strong>&lt;code>output_size = 10&lt;/code>&lt;/strong>: The output layer contains 10 neurons, one for each digit class (0 to 9).&lt;/li>
&lt;li>&lt;strong>&lt;code>model&lt;/code>&lt;/strong>: Instantiates the &lt;code>SimpleNN&lt;/code> class with the specified parameters.&lt;/li>
&lt;/ul>
&lt;hr>
&lt;h3 id="4-model-training-expectations">&lt;strong>4. Model Training Expectations&lt;/strong>&lt;/h3>
&lt;p>The goal is to train the model to correctly classify MNIST digits with high accuracy. Here&amp;rsquo;s what we expect:&lt;/p>
&lt;ul>
&lt;li>&lt;strong>Input&lt;/strong>: A batch of flattened MNIST images (&lt;code>[batch_size, 784]&lt;/code>).&lt;/li>
&lt;li>&lt;strong>Hidden Layer&lt;/strong>: Maps the input to a feature space of size 128.&lt;/li>
&lt;li>&lt;strong>Output Layer&lt;/strong>: Produces probabilities for each digit class using a softmax layer (applied externally during training).&lt;/li>
&lt;li>&lt;strong>Loss Function&lt;/strong>: Measures how far the predictions are from the true labels.&lt;/li>
&lt;li>&lt;strong>Optimization&lt;/strong>: Uses &lt;strong>Stochastic Gradient Descent (SGD)&lt;/strong> or another optimizer to minimize the loss by adjusting weights.&lt;/li>
&lt;/ul>
&lt;p>The &lt;strong>loss function&lt;/strong> serves as a key metric in machine learning, quantifying how well or poorly a model’s predictions align with the actual target values. By evaluating the difference between the predicted outcomes and the true labels, the loss function provides a numerical value that guides the optimization process, helping to improve the model’s performance.&lt;/p>
&lt;p>To minimize this loss, &lt;strong>gradient descent&lt;/strong> is often used as an optimization algorithm. It works by iteratively adjusting the model’s parameters in the direction that reduces the loss function the most. By following the gradient (or slope) of the loss function, gradient descent ensures the model progressively improves its predictions, moving closer to the optimal solution.&lt;/p>
&lt;hr>
&lt;h3 id="5-expected-results">&lt;strong>5. Expected Results&lt;/strong>&lt;/h3>
&lt;ul>
&lt;li>&lt;strong>Accuracy&lt;/strong>: For a simple feedforward network like this, we expect around &lt;strong>90%-92% accuracy&lt;/strong> on the MNIST test set after training.&lt;/li>
&lt;li>&lt;strong>Loss&lt;/strong>: The loss will start high (e.g., 2.0) and gradually decrease to values around &lt;strong>0.3-0.5&lt;/strong> as the model learns.&lt;/li>
&lt;li>&lt;strong>Improvement Potential&lt;/strong>:
&lt;ul>
&lt;li>Adding more hidden layers or increasing the hidden size.&lt;/li>
&lt;li>Experimenting with advanced architectures like CNNs.&lt;/li>
&lt;li>Using data augmentation techniques for better generalization.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ul>
&lt;h1 id="example">Example&lt;/h1>
&lt;p>Lets combine this concepts, and run the model in order the get the results.&lt;/p>
&lt;h3 id="data-loading">Data Loading&lt;/h3>
&lt;p>We use PyTorch&amp;rsquo;s &lt;code>DataLoader&lt;/code> to load the training and testing data.&lt;/p>
&lt;pre>&lt;code class="language-python">from torch.utils.data import DataLoader
from torchvision import datasets, transforms
# Define transformations for the dataset
transform = transforms.Compose([transforms.ToTensor()])
# Load training and testing datasets
train_dataset = datasets.MNIST(root='./data', train=True, transform=transform, download=True)
test_dataset = datasets.MNIST(root='./data', train=False, transform=transform, download=True)
# Create DataLoaders
train_loader = DataLoader(train_dataset, batch_size=100, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=100, shuffle=False)
&lt;/code>&lt;/pre>
&lt;h3 id="loss-function-and-optimizer">Loss Function and Optimizer&lt;/h3>
&lt;p>We use Cross Entropy Loss as the loss function and SGD as the optimizer:&lt;/p>
&lt;pre>&lt;code class="language-python">import torch.optim as optim
loss_fn = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)
&lt;/code>&lt;/pre>
&lt;hr>
&lt;h2 id="training-the-neural-network">Training the Neural Network&lt;/h2>
&lt;p>Training a neural network involves repeatedly feeding data through the model, calculating the error (loss), and updating the model&amp;rsquo;s parameters using optimization techniques like gradient descent. The &lt;code>train_loop()&lt;/code> function handles this process for each training epoch.&lt;/p>
&lt;p>Here’s how &lt;code>train_loop()&lt;/code> is implemented:&lt;/p>
&lt;pre>&lt;code class="language-python">def train_loop(dataloader, model, loss_fn, optimizer):
&amp;quot;&amp;quot;&amp;quot;
Training loop for a neural network model.
Parameters:
- dataloader: DataLoader object for training data
- model: Neural network model
- loss_fn: Loss function (e.g., CrossEntropyLoss)
- optimizer: Optimizer (e.g., SGD, Adam)
Returns:
None
&amp;quot;&amp;quot;&amp;quot;
size = len(dataloader.dataset)
model.train()
for batch, (X, y) in enumerate(dataloader):
# Flatten images into vectors
X = X.view(X.size(0), -1)
# Forward pass
pred = model(X)
loss = loss_fn(pred, y)
# Backpropagation
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Log progress
if batch % 100 == 0:
loss_current = loss.item()
print(f&amp;quot;loss: {loss_current:&amp;gt;7f} [{batch * len(X):&amp;gt;5d}/{size:&amp;gt;5d}]&amp;quot;)
&lt;/code>&lt;/pre>
&lt;p>This function is executed within each training epoch, as shown below:&lt;/p>
&lt;pre>&lt;code class="language-python">for epoch in range(5):
train_loop(train_loader, model, loss_fn, optimizer)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## loss: 2.302421 [ 0/60000]
## loss: 2.082567 [10000/60000]
## loss: 1.820236 [20000/60000]
## loss: 1.481050 [30000/60000]
## loss: 1.281981 [40000/60000]
## loss: 1.009585 [50000/60000]
## loss: 0.945703 [ 0/60000]
## loss: 0.837330 [10000/60000]
## loss: 0.799911 [20000/60000]
## loss: 0.746439 [30000/60000]
## loss: 0.629169 [40000/60000]
## loss: 0.529109 [50000/60000]
## loss: 0.390061 [ 0/60000]
## loss: 0.420087 [10000/60000]
## loss: 0.353291 [20000/60000]
## loss: 0.467722 [30000/60000]
## loss: 0.710849 [40000/60000]
## loss: 0.349696 [50000/60000]
## loss: 0.385319 [ 0/60000]
## loss: 0.443223 [10000/60000]
## loss: 0.247738 [20000/60000]
## loss: 0.438087 [30000/60000]
## loss: 0.547100 [40000/60000]
## loss: 0.468050 [50000/60000]
## loss: 0.330704 [ 0/60000]
## loss: 0.365649 [10000/60000]
## loss: 0.326305 [20000/60000]
## loss: 0.363884 [30000/60000]
## loss: 0.315488 [40000/60000]
## loss: 0.360471 [50000/60000]
&lt;/code>&lt;/pre>
&lt;hr>
&lt;h2 id="visualizing-predictions">Visualizing Predictions&lt;/h2>
&lt;p>After training, we can compare the model&amp;rsquo;s predictions to true labels using a histogram:&lt;/p>
&lt;pre>&lt;code class="language-python">import matplotlib.pyplot as plt
def test_loop(dataloader, model, loss_fn):
model.eval()
size = len(dataloader.dataset)
num_batches = len(dataloader)
test_loss = 0
correct = 0
all_preds = []
all_labels = []
with torch.no_grad():
for X, y in dataloader:
X = X.view(X.size(0), -1)
pred = model(X)
test_loss += loss_fn(pred, y).item()
correct += (pred.argmax(1) == y).type(torch.float).sum().item()
all_preds.extend(pred.argmax(1).tolist())
all_labels.extend(y.tolist())
test_loss /= num_batches
correct /= size
return test_loss, correct, all_preds, all_labels
test_loss, test_acc, pred, lab = test_loop(test_loader, model, loss_fn)
print(f&amp;quot;Test Error: \n Accuracy: {(100*test_acc):&amp;gt;0.1f}%, Avg loss: {test_loss:&amp;gt;8f} \n&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## Test Error:
## Accuracy: 90.5%, Avg loss: 0.341179
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python"># Plot histograms
plt.hist(pred, bins=10, alpha=0.5, label='Predictions')
plt.hist(lab, bins=10, alpha=0.5, label='Labels')
plt.legend()
plt.show()
&lt;/code>&lt;/pre>
&lt;p>&lt;img src="https://luis-zapatabobadilla.netlify.app/project/2024-11-22-neural-network/index.en_files/figure-html/unnamed-chunk-7-1.png" width="672" />&lt;/p>
&lt;hr>
&lt;h2 id="conclusion">Conclusion&lt;/h2>
&lt;p>In this project, we trained a simple feedforward neural network on the MNIST dataset and evaluated its performance. The final results were as follows:&lt;/p>
&lt;ul>
&lt;li>&lt;strong>Test Accuracy&lt;/strong>: 90.4%&lt;/li>
&lt;li>&lt;strong>Average Test Loss&lt;/strong>: 0.3445&lt;/li>
&lt;/ul>
&lt;p>The histogram above shows that the predictions closely match the true labels, demonstrating that the neural network successfully learned patterns in the data. While the accuracy indicates solid performance, further improvements could be achieved through:&lt;/p>
&lt;ul>
&lt;li>Optimizing hyperparameters (e.g., learning rate, batch size, number of hidden units).&lt;/li>
&lt;li>Experimenting with deeper or more complex architectures like Convolutional Neural Networks (CNNs).&lt;/li>
&lt;li>Increasing the number of training epochs to allow the network to converge better.&lt;/li>
&lt;/ul>
&lt;p>This blog demonstrated how to build, train, and evaluate a simple feedforward neural network using PyTorch to classify handwritten digits from the MNIST dataset. Along the way, we covered essential concepts such as tensors, neural network architecture, activation functions, and the training process.&lt;/p>
&lt;p>Neural networks are versatile tools with applications across diverse domains. This project serves as a foundation for understanding how to implement and optimize these models, paving the way for tackling more complex machine learning challenges in the future.&lt;/p>
&lt;hr>
&lt;h3 id="references">References&lt;/h3>
&lt;ul>
&lt;li>PyTorch Documentation: &lt;a href="https://pytorch.org/docs/">https://pytorch.org/docs/&lt;/a>&lt;/li>
&lt;li>MNIST Dataset: &lt;a href="http://yann.lecun.com/exdb/mnist/">http://yann.lecun.com/exdb/mnist/&lt;/a>&lt;/li>
&lt;/ul></description></item><item><title>Kernel Density and Local Estimators with Confidence Bands</title><link>https://luis-zapatabobadilla.netlify.app/project/kernel-density-local-estimators/</link><pubDate>Sat, 23 Nov 2024 00:00:00 +0000</pubDate><guid>https://luis-zapatabobadilla.netlify.app/project/kernel-density-local-estimators/</guid><description>&lt;h2 id="introduction">Introduction&lt;/h2>
&lt;p>In this post, we&amp;rsquo;ll explore &lt;strong>Kernel Density Estimation (KDE)&lt;/strong>, &lt;strong>Local Constant Estimator&lt;/strong>, and &lt;strong>Local Linear Estimator&lt;/strong>. Additionally, we&amp;rsquo;ll introduce &lt;strong>95% Confidence Bands&lt;/strong> (both point-wise and universal) to quantify the uncertainty in the estimators.&lt;/p>
&lt;p>This will provide a more complete understanding of these non-parametric methods and how to use them effectively.&lt;/p>
&lt;hr>
&lt;h2 id="kernel-density-estimation-kde-with-confidence-bands">Kernel Density Estimation (KDE) with Confidence Bands&lt;/h2>
&lt;p>Kernel Density Estimation (KDE) estimates the probability density function of a random variable by smoothing data points with a kernel function. To evaluate the reliability of the KDE, we add point-wise and universal confidence bands.&lt;/p>
&lt;h3 id="kernel-density-estimation-kde-theory-and-application">Kernel Density Estimation (KDE): Theory and Application&lt;/h3>
&lt;p>&lt;strong>Kernel Density Estimation (KDE)&lt;/strong> is a non-parametric method used to estimate the probability density function (PDF) of a dataset. Unlike parametric approaches, KDE does not assume the data follows a specific distribution (e.g., normal distribution). Instead, it constructs the density estimate by smoothing individual data points using a kernel function. This makes KDE highly flexible and particularly useful when the underlying data distribution is unknown or non-standard, such as in financial data where heavy tails and skewness are common.&lt;/p>
&lt;p>The KDE is defined as:&lt;/p>
&lt;p>$$
\hat{f}(x) = \frac{1}{n h} \sum_{i=1}^n K\left(\frac{x - X_i}{h}\right),
$$&lt;/p>
&lt;p>where:&lt;/p>
&lt;ul>
&lt;li>$ \hat{f}(x) $ is the estimated density at point $ x $,&lt;/li>
&lt;li>$ X_i $ are the data points,&lt;/li>
&lt;li>$ K $ is the kernel function (e.g., Epanechnikov or Gaussian),&lt;/li>
&lt;li>$ h $ is the bandwidth, controlling the smoothness of the estimate.&lt;/li>
&lt;/ul>
&lt;p>The choice of bandwidth $ h $ is crucial. Smaller $ h $ values lead to a more flexible estimate but can result in overfitting, while larger $ h $ values produce a smoother density at the cost of losing detail.&lt;/p>
&lt;h3 id="when-to-use-kde">When to Use KDE&lt;/h3>
&lt;p>KDE is particularly valuable in situations where the density of the data is unknown and may deviate from standard distributions. For example:&lt;/p>
&lt;ul>
&lt;li>&lt;strong>Exploratory Analysis&lt;/strong>: When we want to visualize the shape of the data&amp;rsquo;s distribution without assuming normality.&lt;/li>
&lt;li>&lt;strong>Non-Normal Data&lt;/strong>: Financial data, for instance, often exhibit heavy tails or skewness, making KDE a robust choice to uncover the true density.&lt;/li>
&lt;/ul>
&lt;p>In the code example above, the KDE is compared to a normal density estimation.&lt;/p>
&lt;h3 id="confidence-bands">Confidence Bands&lt;/h3>
&lt;p>Confidence bands, both pointwise and uniform, provide uncertainty estimates for the density function:&lt;/p>
&lt;ul>
&lt;li>&lt;strong>Pointwise Confidence Bands&lt;/strong> quantify the variability at specific points, showing how confident we are about the estimate at each ( x ).&lt;/li>
&lt;li>&lt;strong>Uniform Confidence Bands&lt;/strong> cover the entire range of ( x ), ensuring that the true density lies within the band with a given probability.&lt;/li>
&lt;/ul>
&lt;p>These bands help evaluate the reliability of the KDE and highlight areas where the estimate may be less accurate due to data sparsity or noise.&lt;/p>
&lt;h3 id="example-kde-with-confidence-bands">Example: KDE with Confidence Bands&lt;/h3>
&lt;p>Here&amp;rsquo;s a KDE estimator example with pointwise confidence bands for financial data using the Epanechnikov kernel. The code downloads stock price data (&lt;strong>APPLE&lt;/strong>), computes log returns, and estimates the density with confidence bands. The normal density is also calculated for comparison.
:&lt;/p>
&lt;pre>&lt;code class="language-python">import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
import yfinance as yf
# Download financial data
def download_financial_data(ticker, start_date, end_date):
data = yf.download(ticker, start=start_date, end=end_date)
log_returns = np.log(data['Close'] / data['Close'].shift(1)).dropna()
return log_returns
# Define KDE with Epanechnikov Kernel
def epanechnikov_kernel(u):
return np.where(np.abs(u) &amp;lt;= np.sqrt(5), (3 / (4 * np.sqrt(5))) * (1 - u**2 / 5), 0)
def kernel_density_estimate(x_values, data, bandwidth):
densities = np.zeros_like(x_values)
for i, x in enumerate(x_values):
weights = epanechnikov_kernel((x - data) / bandwidth)
densities[i] = np.sum(weights) / (len(data) * bandwidth)
return densities
# Function to calculate variance estimate for pointwise confidence intervals
def variance_estimate(x_values, data, bandwidth):
n = len(data)
variances = np.zeros_like(x_values)
for i, x0 in enumerate(x_values):
K_h_values = epanechnikov_kernel((data - x0) / bandwidth) / bandwidth
term1 = (1 / n) * np.sum(K_h_values**2)
term2 = ((1 / n) * np.sum(K_h_values))**2
variances[i] = (term1 - term2) / n
return variances
# Function to calculate the normal density
def normal_density_estimate(x_values, mean, std_dev):
return (1 / (np.sqrt(2 * np.pi * std_dev**2))) * np.exp(-((x_values - mean)**2) / (2 * std_dev**2))
# Download and preprocess financial data
ticker = &amp;quot;AAPL&amp;quot; # Example ticker
start_date = &amp;quot;2023-01-01&amp;quot;
end_date = &amp;quot;2024-01-01&amp;quot;
log_returns = download_financial_data(ticker, start_date, end_date)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## /Users/luisj/anaconda3/lib/python3.11/site-packages/yfinance/utils.py:775: FutureWarning: The 'unit' keyword in TimedeltaIndex construction is deprecated and will be removed in a future version. Use pd.to_timedelta instead.
## df.index += _pd.TimedeltaIndex(dst_error_hours, 'h')
##
[*********************100%%**********************] 1 of 1 completed
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python"># KDE and confidence bands
x_values = np.linspace(log_returns.min(), log_returns.max(), 1000)
bandwidth = 0.02 # Example bandwidth
density_estimates = kernel_density_estimate(x_values, log_returns.values, bandwidth)
# Pointwise confidence bands
alpha = 0.05
variance_estimates = variance_estimate(x_values, log_returns.values, bandwidth)
z_alpha = norm.ppf(1 - alpha / 2)
lower_bounds = density_estimates - z_alpha * np.sqrt(variance_estimates)
upper_bounds = density_estimates + z_alpha * np.sqrt(variance_estimates)
# Normal density for comparison
mean_returns = log_returns.mean()
std_returns = log_returns.std()
normal_density = normal_density_estimate(x_values, mean_returns, std_returns)
# Plot results
plt.figure(figsize=(12, 6))
plt.plot(x_values, density_estimates, label=&amp;quot;KDE (Epanechnikov)&amp;quot;, color='blue')
plt.plot(x_values, normal_density, label=&amp;quot;Normal Density (Mean &amp;amp; Std Dev)&amp;quot;, color='red', linestyle='--')
plt.fill_between(x_values, lower_bounds, upper_bounds, color='gray', alpha=0.3, label=&amp;quot;95% Pointwise Confidence Band&amp;quot;)
plt.xlabel(&amp;quot;Log Returns&amp;quot;)
plt.ylabel(&amp;quot;Density&amp;quot;)
plt.title(f&amp;quot;Kernel Density Estimation for {ticker} with Confidence Bands&amp;quot;)
plt.legend()
plt.show()
&lt;/code>&lt;/pre>
&lt;p>&lt;img src="https://luis-zapatabobadilla.netlify.app/project/kernel-density-local-estimators/index.en_files/figure-html/unnamed-chunk-1-1.png" width="1152" />&lt;/p>
&lt;h3 id="explanation">Explanation:&lt;/h3>
&lt;ol>
&lt;li>&lt;strong>Epanechnikov Kernel&lt;/strong>: The function smooths the data points based on the Epanechnikov formula. A bandwidth parameter controls the degree of smoothing.&lt;/li>
&lt;li>&lt;strong>Normal Density&lt;/strong>: The normal density estimate is calculated using the sample mean and standard deviation for comparison with the KDE.&lt;/li>
&lt;li>&lt;strong>Confidence Bands&lt;/strong>:
&lt;ul>
&lt;li>&lt;strong>Variance Estimate&lt;/strong>: Variance for pointwise confidence intervals is computed based on kernel weights.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ol>
&lt;h4 id="conclusion">Conclusion&lt;/h4>
&lt;p>KDE is a powerful tool for density estimation, especially when the underlying distribution of the data is unknown or non-standard. It is particularly useful in domains like finance, where data often deviate from normality, exhibiting heavy tails or irregular shapes. By using kernels and bandwidths, KDE provides a flexible, data-driven approach to estimate densities without relying on strict parametric assumptions. The addition of confidence bands further enhances its utility by quantifying the uncertainty in the estimates, making KDE a robust choice for both exploratory and confirmatory data analysis.&lt;/p>
&lt;h2 id="introduction-nonparametric-regression">Introduction: Nonparametric Regression&lt;/h2>
&lt;p>Using the estimation of Kernel Density Estimators, now we can approach the expected values of Y given X (using the esitmated density). By doing this, we can obtain non parametric estimators.
Nonparametric regression methods are powerful tools for estimating the relationship between a response variable $ Y $ and a predictor $ X $, without assuming a specific parametric form for the underlying relationship. Unlike traditional linear or polynomial regression, nonparametric methods adapt to the data&amp;rsquo;s structure, providing flexibility in modeling complex relationships.&lt;/p>
&lt;p>Two widely used nonparametric regression estimators are the &lt;strong>Nadaraya-Watson Estimator&lt;/strong> and the &lt;strong>Local Linear Estimator&lt;/strong>. While both methods use kernel functions to assign weights to data points based on their proximity to the evaluation point, they differ in how they model the local behavior of the data.&lt;/p>
&lt;hr>
&lt;h3 id="the-nadaraya-watson-estimator">The Nadaraya-Watson Estimator&lt;/h3>
&lt;p>The &lt;strong>Nadaraya-Watson Estimator&lt;/strong> is a simple, kernel-based approach to regression. For a given point $x $, the estimator computes the weighted average of the response variable $ Y $ using the weights determined by the kernel function:&lt;/p>
&lt;p>$$
\hat{m}(x) = \frac{\sum_{i=1}^n K_h(x - X_i) Y_i}{\sum_{i=1}^n K_h(x - X_i)},
$$&lt;/p>
&lt;p>where:&lt;/p>
&lt;ul>
&lt;li>$( K_h(u) = \frac{1}{h} K\left(\frac{u}{h}\right) ) $ is the kernel function scaled by the bandwidth ( h ),&lt;/li>
&lt;li>$( X_i )$ and $( Y_i )$ are the predictor and response variables, respectively.&lt;/li>
&lt;/ul>
&lt;p>The kernel function ( K ) determines the weight assigned to each observation. Common kernels include the Gaussian kernel and the Epanechnikov kernel. The bandwidth ( h ) controls the smoothness of the estimate: smaller values of ( h ) result in a more flexible, less smooth fit, while larger values yield smoother estimates.&lt;/p>
&lt;p>While the Nadaraya-Watson Estimator is simple and effective, it can suffer from &lt;strong>boundary bias&lt;/strong>. Near the edges of the data, the kernel weights become asymmetric, leading to inaccuracies in the estimated values.&lt;/p>
&lt;hr>
&lt;h3 id="the-local-linear-estimator">The Local Linear Estimator&lt;/h3>
&lt;p>The &lt;strong>Local Linear Estimator&lt;/strong> extends the Nadaraya-Watson approach by fitting a &lt;strong>local linear regression&lt;/strong> in the neighborhood of each evaluation point ( x ). Instead of assuming a constant value for ( Y ) (as in NW), this method models ( Y ) as a linear function:&lt;/p>
&lt;p>$$ Y \approx \theta_0 + \theta_1 (X - x).$$&lt;/p>
&lt;p>For a given ( x ), the parameters $ \theta_0 $ and $ \theta_1 $ are estimated by minimizing a kernel-weighted least-squares objective:&lt;/p>
&lt;p>$$
\min_{\theta_0, \theta_1} \sum_{i=1}^n K_h(X_i - x) \left[ Y_i - \theta_0 - \theta_1 (X_i - x) \right]^2.
$$&lt;/p>
&lt;p>The solution gives the local linear regression coefficients $ \hat{\theta}_0 $ and $ \hat{\theta}_1 $, and the estimator at ( x ) is $ \hat{m}(x) = \hat{\theta}_0 $.&lt;/p>
&lt;p>By allowing for a linear fit within the kernel window, the Local Linear Estimator addresses the &lt;strong>boundary bias&lt;/strong> issue present in the Nadaraya-Watson Estimator. It can better capture the local structure of the data and typically performs well both near the edges and in regions with varying density.&lt;/p>
&lt;hr>
&lt;h3 id="comparison-of-the-two-methods">Comparison of the Two Methods&lt;/h3>
&lt;table>
&lt;thead>
&lt;tr>
&lt;th>Feature&lt;/th>
&lt;th>Nadaraya-Watson Estimator&lt;/th>
&lt;th>Local Linear Estimator&lt;/th>
&lt;/tr>
&lt;/thead>
&lt;tbody>
&lt;tr>
&lt;td>&lt;strong>Model Assumption&lt;/strong>&lt;/td>
&lt;td>Locally constant&lt;/td>
&lt;td>Locally linear&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>&lt;strong>Bias near boundaries&lt;/strong>&lt;/td>
&lt;td>High (prone to boundary bias)&lt;/td>
&lt;td>Low (reduces boundary bias)&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>&lt;strong>Complexity&lt;/strong>&lt;/td>
&lt;td>Simple (weighted average)&lt;/td>
&lt;td>More complex (weighted least squares)&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>&lt;strong>Behavior near edges&lt;/strong>&lt;/td>
&lt;td>Underestimates or overestimates response&lt;/td>
&lt;td>Handles boundaries more accurately&lt;/td>
&lt;/tr>
&lt;/tbody>
&lt;/table>
&lt;p>Both methods depend heavily on the choice of the kernel function and the bandwidth parameter, which control the smoothness and flexibility of the estimates.&lt;/p>
&lt;h3 id="python-code">Python Code&lt;/h3>
&lt;pre>&lt;code class="language-python">import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
from scipy.integrate import quad
# Define kernels
def epanechnikov_kernel(u):
return np.where(np.abs(u) &amp;lt;= np.sqrt(5), (3 / (4 * np.sqrt(5))) * (1 - u**2 / 5), 0)
# Nadaraya-Watson Estimator
def nadaraya_watson(X, Y, x_grid, bandwidth, kernel=epanechnikov_kernel):
estimates = []
for x in x_grid:
weights = kernel((X - x) / bandwidth)
numerator = np.sum(weights * Y)
denominator = np.sum(weights)
estimates.append(numerator / denominator if denominator &amp;gt; 0 else 0)
return np.array(estimates)
# Local Linear Estimator
def local_linear_estimator(X, Y, x_eval, bandwidth, kernel=epanechnikov_kernel):
n = len(X)
U = np.vstack([np.ones(n), X - x_eval]).T
W = np.diag(kernel((X - x_eval) / bandwidth) / bandwidth)
theta_hat = np.linalg.inv(U.T @ W @ U) @ (U.T @ W @ Y)
return theta_hat[0], theta_hat[1]
# Variance estimator for pointwise confidence intervals
def compute_s_hat(X, residuals, x_eval, bandwidth, kernel=epanechnikov_kernel):
weights = kernel((X - x_eval) / bandwidth) / bandwidth
weights_squared = weights**2
residuals_squared = residuals**2
f_hat = np.sum(weights) / (len(X) * bandwidth)
s_hat = np.sqrt(np.sum(weights_squared * residuals_squared) / (len(X)**2 * f_hat**2))
return s_hat
# Generate synthetic data
np.random.seed(42)
X = np.linspace(0, 10, 100)
Y = np.sin(X) + np.random.normal(0, 0.2, size=len(X))
# Define evaluation grid and bandwidth
x_grid = np.linspace(0, 10, 200)
bandwidth = 0.8
# Estimate Nadaraya-Watson
nw_estimates = nadaraya_watson(X, Y, x_grid, bandwidth)
# Estimate Local Linear
ll_intercepts = []
for x in x_grid:
intercept, _ = local_linear_estimator(X, Y, x, bandwidth)
ll_intercepts.append(intercept)
# Residuals for Nadaraya-Watson
nw_residuals = Y - nadaraya_watson(X, Y, X, bandwidth)
# Pointwise Confidence Intervals
alpha = 0.05
z_alpha = norm.ppf(1 - alpha / 2)
pointwise_lower = []
pointwise_upper = []
s_hat_values = []
for x_eval, m_eval in zip(x_grid, nw_estimates):
s_hat = compute_s_hat(X, nw_residuals, x_eval, bandwidth)
s_hat_values.append(s_hat)
pointwise_lower.append(m_eval - z_alpha * s_hat)
pointwise_upper.append(m_eval + z_alpha * s_hat)
# Plot Nadaraya-Watson with Pointwise CI
plt.figure(figsize=(12, 6))
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## &amp;lt;Figure size 1200x600 with 0 Axes&amp;gt;
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.plot(x_grid, nw_estimates, label=&amp;quot;Nadaraya-Watson Estimate&amp;quot;, color=&amp;quot;blue&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## [&amp;lt;matplotlib.lines.Line2D object at 0x17d060550&amp;gt;]
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.fill_between(x_grid, pointwise_lower, pointwise_upper, color=&amp;quot;blue&amp;quot;, alpha=0.2, label=&amp;quot;95% Pointwise CI&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## &amp;lt;matplotlib.collections.PolyCollection object at 0x17d0f1b90&amp;gt;
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.scatter(X, Y, alpha=0.5, label=&amp;quot;Data Points&amp;quot;, color=&amp;quot;black&amp;quot;, s=10)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## &amp;lt;matplotlib.collections.PathCollection object at 0x17d0e6cd0&amp;gt;
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.title(&amp;quot;Nadaraya-Watson Estimator with Pointwise Confidence Intervals&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## Text(0.5, 1.0, 'Nadaraya-Watson Estimator with Pointwise Confidence Intervals')
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.xlabel(&amp;quot;X&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## Text(0.5, 0, 'X')
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.ylabel(&amp;quot;Y&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## Text(0, 0.5, 'Y')
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.legend()
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## &amp;lt;matplotlib.legend.Legend object at 0x17d069d10&amp;gt;
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.show()
&lt;/code>&lt;/pre>
&lt;p>&lt;img src="https://luis-zapatabobadilla.netlify.app/project/kernel-density-local-estimators/index.en_files/figure-html/unnamed-chunk-2-3.png" width="1152" />&lt;/p>
&lt;pre>&lt;code class="language-python"># Uniform Confidence Bands
def compute_G(x_grid, X, residuals, bandwidth, kernel=epanechnikov_kernel):
n = len(X)
G_values = []
for x_eval in x_grid:
kernel_values = kernel((X - x_eval) / bandwidth) / bandwidth
total_weight = np.sum(kernel_values)
weights = kernel_values / total_weight if total_weight &amp;gt; 0 else np.zeros_like(kernel_values)
xi = np.random.normal(0, 1, n)
s_hat = compute_s_hat(X, residuals, x_eval, bandwidth)
G_x = np.sum(xi * residuals * weights / s_hat)
G_values.append(G_x)
return np.array(G_values)
def gaussian_multiplier_bootstrap(x_grid, X, residuals, bandwidth, kernel=epanechnikov_kernel, B=1000, alpha=0.05):
bootstrap_sup = []
for _ in range(B):
G_values = compute_G(x_grid, X, residuals, bandwidth, kernel)
bootstrap_sup.append(np.max(np.abs(G_values)))
return np.quantile(bootstrap_sup, 1 - alpha)
q_alpha = gaussian_multiplier_bootstrap(x_grid, X, nw_residuals, bandwidth)
uniform_lower = nw_estimates - q_alpha * np.array(s_hat_values)
uniform_upper = nw_estimates + q_alpha * np.array(s_hat_values)
# Plot with Uniform Confidence Bands
plt.figure(figsize=(12, 6))
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## &amp;lt;Figure size 1200x600 with 0 Axes&amp;gt;
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.plot(x_grid, nw_estimates, label=&amp;quot;Nadaraya-Watson Estimate&amp;quot;, color=&amp;quot;blue&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## [&amp;lt;matplotlib.lines.Line2D object at 0x17de5ebd0&amp;gt;]
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.fill_between(x_grid, uniform_lower, uniform_upper, color=&amp;quot;red&amp;quot;, alpha=0.1, label=&amp;quot;95% Uniform CI&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## &amp;lt;matplotlib.collections.PolyCollection object at 0x17de92590&amp;gt;
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.scatter(X, Y, alpha=0.5, label=&amp;quot;Data Points&amp;quot;, color=&amp;quot;black&amp;quot;, s=10)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## &amp;lt;matplotlib.collections.PathCollection object at 0x17de2c410&amp;gt;
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.title(&amp;quot;Nadaraya-Watson Estimator with Uniform Confidence Bands&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## Text(0.5, 1.0, 'Nadaraya-Watson Estimator with Uniform Confidence Bands')
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.xlabel(&amp;quot;X&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## Text(0.5, 0, 'X')
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.ylabel(&amp;quot;Y&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## Text(0, 0.5, 'Y')
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.legend()
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## &amp;lt;matplotlib.legend.Legend object at 0x17de9ee90&amp;gt;
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.show()
&lt;/code>&lt;/pre>
&lt;p>&lt;img src="https://luis-zapatabobadilla.netlify.app/project/kernel-density-local-estimators/index.en_files/figure-html/unnamed-chunk-2-4.png" width="1152" />&lt;/p>
&lt;p>&lt;strong>Pointwise vs. Uniform Confidence Bands&lt;/strong>&lt;/p>
&lt;p>Pointwise and uniform confidence bands both quantify the uncertainty in regression estimates but differ in their scope. &lt;strong>Pointwise confidence bands&lt;/strong> provide an interval estimate for the regression function at each specific point ( x ), indicating the range where the true function is likely to lie with a given probability (e.g., 95%). However, these intervals do not account for the simultaneous uncertainty across all points in the domain.&lt;/p>
&lt;p>In contrast, &lt;strong>uniform confidence bands&lt;/strong> account for the entire range of ( x ), ensuring that the true regression function lies within the band at all points with a specified probability (e.g., 95%). While pointwise bands are narrower and easier to compute, uniform bands are more conservative and robust, capturing the overall uncertainty across the entire function.&lt;/p>
&lt;h3 id="key-features">Key Features&lt;/h3>
&lt;ol>
&lt;li>&lt;strong>Synthetic Data&lt;/strong>: Non-linear function $ Y = \sin(X) + \text{noise} $.&lt;/li>
&lt;li>&lt;strong>Nadaraya-Watson Estimation&lt;/strong>: Smoothed estimates with Epanechnikov kernel.&lt;/li>
&lt;li>&lt;strong>Local Linear Estimation&lt;/strong>: Estimates the function with reduced bias.&lt;/li>
&lt;li>&lt;strong>Pointwise Confidence Intervals&lt;/strong>: Calculated using the standard error of residuals.&lt;/li>
&lt;li>&lt;strong>Uniform Confidence Bands&lt;/strong>: Computed via Gaussian multiplier bootstrap.&lt;/li>
&lt;/ol>
&lt;p>This approach demonstrates the application of kernel-based regression estimators and provides clear visual comparisons of pointwise and uniform confidence intervals.&lt;/p>
&lt;pre>&lt;code class="language-python"># Plot Local Linear Estimator
plt.figure(figsize=(12, 6))
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## &amp;lt;Figure size 1200x600 with 0 Axes&amp;gt;
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.plot(x_grid, ll_intercepts, label=&amp;quot;Local Linear Estimate&amp;quot;, color=&amp;quot;green&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## [&amp;lt;matplotlib.lines.Line2D object at 0x17ded4890&amp;gt;]
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.scatter(X, Y, alpha=0.5, label=&amp;quot;Data Points&amp;quot;, color=&amp;quot;black&amp;quot;, s=10)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## &amp;lt;matplotlib.collections.PathCollection object at 0x17dec5990&amp;gt;
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.title(&amp;quot;Local Linear Estimator&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## Text(0.5, 1.0, 'Local Linear Estimator')
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.xlabel(&amp;quot;X&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## Text(0.5, 0, 'X')
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.ylabel(&amp;quot;Y&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## Text(0, 0.5, 'Y')
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.legend()
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## &amp;lt;matplotlib.legend.Legend object at 0x17ded64d0&amp;gt;
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.show()
&lt;/code>&lt;/pre>
&lt;p>&lt;img src="https://luis-zapatabobadilla.netlify.app/project/kernel-density-local-estimators/index.en_files/figure-html/unnamed-chunk-3-7.png" width="1152" />&lt;/p>
&lt;pre>&lt;code class="language-python"># Plot Comparison: Nadaraya-Watson vs Local Linear Estimators
plt.figure(figsize=(12, 6))
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## &amp;lt;Figure size 1200x600 with 0 Axes&amp;gt;
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.plot(x_grid, nw_estimates, label=&amp;quot;Nadaraya-Watson Estimate&amp;quot;, color=&amp;quot;blue&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## [&amp;lt;matplotlib.lines.Line2D object at 0x17dec8590&amp;gt;]
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.plot(x_grid, ll_intercepts, label=&amp;quot;Local Linear Estimate&amp;quot;, color=&amp;quot;green&amp;quot;, linestyle=&amp;quot;--&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## [&amp;lt;matplotlib.lines.Line2D object at 0x17deabfd0&amp;gt;]
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.scatter(X, Y, alpha=0.5, label=&amp;quot;Data Points&amp;quot;, color=&amp;quot;black&amp;quot;, s=10)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## &amp;lt;matplotlib.collections.PathCollection object at 0x17dec4290&amp;gt;
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.title(&amp;quot;Comparison: Nadaraya-Watson vs Local Linear Estimators&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## Text(0.5, 1.0, 'Comparison: Nadaraya-Watson vs Local Linear Estimators')
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.xlabel(&amp;quot;X&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## Text(0.5, 0, 'X')
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.ylabel(&amp;quot;Y&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## Text(0, 0.5, 'Y')
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.legend()
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## &amp;lt;matplotlib.legend.Legend object at 0x17de7f210&amp;gt;
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-python">plt.show()
&lt;/code>&lt;/pre>
&lt;p>&lt;img src="https://luis-zapatabobadilla.netlify.app/project/kernel-density-local-estimators/index.en_files/figure-html/unnamed-chunk-3-8.png" width="1152" />&lt;/p>
&lt;h2 id="conclusion-1">Conclusion&lt;/h2>
&lt;p>The plot compares the &lt;strong>Nadaraya-Watson Estimator&lt;/strong> (solid blue line) and the &lt;strong>Local Linear Estimator&lt;/strong> (dashed green line) against the observed data points (gray dots). Here are some key observations:&lt;/p>
&lt;ol>
&lt;li>
&lt;p>&lt;strong>Overall Fit&lt;/strong>:&lt;/p>
&lt;ul>
&lt;li>Both estimators capture the non-linear structure of the data effectively, reflecting the sinusoidal trend of the underlying function.&lt;/li>
&lt;li>The estimators generally align well in regions where the data density is higher.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Boundary Behavior&lt;/strong>:&lt;/p>
&lt;ul>
&lt;li>At the edges of the data (e.g., near $ X = 0 $ and $ X = 10 $), the &lt;strong>Nadaraya-Watson Estimator&lt;/strong> shows a stronger bias, curving upward or downward.&lt;/li>
&lt;li>The &lt;strong>Local Linear Estimator&lt;/strong> performs better at the boundaries, maintaining a smoother and more accurate extrapolation due to its local linear adjustment.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Flexibility vs. Bias&lt;/strong>:&lt;/p>
&lt;ul>
&lt;li>The &lt;strong>Nadaraya-Watson Estimator&lt;/strong>, being locally constant, is slightly less responsive to rapid changes in the data, particularly at the boundaries where it suffers from higher bias.&lt;/li>
&lt;li>The &lt;strong>Local Linear Estimator&lt;/strong>, with its linear adjustment, is better equipped to handle such variations, leading to reduced bias and improved accuracy near the edges.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Central Region&lt;/strong>:&lt;/p>
&lt;ul>
&lt;li>In the central region of the domain (e.g., between $ X = 3 $ and $ X = 7 $), both estimators perform similarly, as the data density is sufficient for accurate local smoothing.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Practical Implications&lt;/strong>:&lt;/p>
&lt;ul>
&lt;li>The &lt;strong>Nadaraya-Watson Estimator&lt;/strong> may be more suitable for datasets where boundary effects are not a concern and the goal is simplicity, or we are unsure of the linear assumptions in the data. Its locally constant approach avoids making strong assumptions about the underlying structure, making it a safer choice for exploratory analysis in small datasets&lt;/li>
&lt;li>The &lt;strong>Local Linear Estimator&lt;/strong> is preferable when boundary accuracy is critical or when the data exhibits sharp trends that require more adaptive modeling.It can handle variations better, especially when there is enough data to justify the assumption of local linearity.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ol>
&lt;h3 id="final-conclusion">Final Conclusion&lt;/h3>
&lt;p>In this post, we explored the theory and implementation of &lt;strong>Kernel Density Estimation (KDE)&lt;/strong>, the &lt;strong>Nadaraya-Watson Estimator&lt;/strong>, and the &lt;strong>Local Linear Estimator&lt;/strong>, along with methods to construct &lt;strong>95% confidence bands&lt;/strong> (pointwise and uniform). These non-parametric techniques provide a flexible framework for analyzing data without assuming a specific parametric model, making them powerful tools for understanding complex relationships.&lt;/p>
&lt;p>&lt;strong>Kernel Density Estimation (KDE)&lt;/strong> allows us to estimate the probability density function of a variable, with the kernel function and bandwidth playing key roles in balancing bias and variance. The inclusion of confidence bands helps quantify the uncertainty in the density estimates, providing deeper insights into the reliability of the results.&lt;/p>
&lt;p>The &lt;strong>Nadaraya-Watson Estimator&lt;/strong> is a simple and intuitive approach to nonparametric regression that uses kernel-weighted averages to estimate the response variable. While effective in capturing trends, it is susceptible to boundary bias and less responsive to sharp changes in the data.&lt;/p>
&lt;p>The &lt;strong>Local Linear Estimator&lt;/strong>, on the other hand, fits a locally linear model to reduce bias at the boundaries and adapt better to variations in the data. Its ability to handle local trends makes it a more robust choice in many scenarios, especially when data density varies across the domain.&lt;/p>
&lt;p>Confidence bands enhance these methods by providing uncertainty estimates. &lt;strong>Pointwise confidence bands&lt;/strong> quantify uncertainty at individual points, while &lt;strong>uniform confidence bands&lt;/strong> ensure coverage over the entire domain, offering a more robust perspective on the estimator&amp;rsquo;s reliability.&lt;/p>
&lt;p>The &lt;strong>Nadaraya-Watson Estimator&lt;/strong> is particularly useful for exploratory analysis, especially with small datasets or when there are uncertainties about the linearity of the underlying relationships. In contrast, the &lt;strong>Local Linear Estimator&lt;/strong> is better suited for situations where accuracy near boundaries or sharp data trends is critical.&lt;/p>
&lt;p>In conclusion, these nonparametric methods offer flexibility and adaptability in data analysis, making them essential tools for uncovering complex patterns and relationships. By carefully selecting the appropriate estimator, kernel function, and bandwidth, you can tailor these approaches to meet your analytical objectives effectively.&lt;/p></description></item><item><title>Presidential Elections in Peru 2021: A Text Analysis</title><link>https://luis-zapatabobadilla.netlify.app/project/presidential-elections-analysis/</link><pubDate>Fri, 22 Nov 2024 00:00:00 +0000</pubDate><guid>https://luis-zapatabobadilla.netlify.app/project/presidential-elections-analysis/</guid><description>&lt;link href="https://luis-zapatabobadilla.netlify.app/project/presidential-elections-analysis/index.en_files/htmltools-fill/fill.css" rel="stylesheet" />
&lt;script src="https://luis-zapatabobadilla.netlify.app/project/presidential-elections-analysis/index.en_files/htmlwidgets/htmlwidgets.js">&lt;/script>
&lt;link href="https://luis-zapatabobadilla.netlify.app/project/presidential-elections-analysis/index.en_files/wordcloud2/wordcloud.css" rel="stylesheet" />
&lt;script src="https://luis-zapatabobadilla.netlify.app/project/presidential-elections-analysis/index.en_files/wordcloud2/wordcloud2-all.js">&lt;/script>
&lt;script src="https://luis-zapatabobadilla.netlify.app/project/presidential-elections-analysis/index.en_files/wordcloud2/hover.js">&lt;/script>
&lt;script src="https://luis-zapatabobadilla.netlify.app/project/presidential-elections-analysis/index.en_files/wordcloud2-binding/wordcloud2.js">&lt;/script>
&lt;h1 id="introduction">Introduction&lt;/h1>
&lt;p>How do political parties craft their messages to win over voters? This blog dives into the government plans from Peru’s 2021 presidential election, analyzing the priorities and sentiments of six major parties using cutting-edge text-mining tools. By uncovering patterns in language and tone, this analysis provides a data-driven lens into the strategies of political discourse.&lt;/p>
&lt;p>This methodology could be effectively applied in other countries, like the United States, to analyze political platforms, legislative texts, or policy proposals. By extracting key terms and sentiments, it can provide insights into thematic focuses, public priorities, and ideological differences, enabling data-driven comparisons across political parties or regions.&lt;/p>
&lt;p>This document analyzes the government plans for the 2021 Peruvian presidential election, plans registered with the &lt;strong>JNE&lt;/strong> by the respective parties (the government plans can be downloaded from &lt;a href="https://drive.google.com/drive/folders/1RiqHdqcj5McYOyFilHZiLQuyLUIvhI0w" target="_blank" rel="noopener">here&lt;/a>). Due to the large number of parties (23), only the top 6 parties with the highest voter intentions according to &lt;a href="https://www.ipsos.com/sites/default/files/ct/news/documents/2021-01/anexo1_publicacion.pdf" target="_blank" rel="noopener">IPSOS&lt;/a> will be analyzed. The project can be replied in this Github repository: &lt;a href="https://github.com/luisjo819UCLA/Text_Mining_Peru_Goverment" target="_blank" rel="noopener">PlanGobierno&lt;/a>.&lt;/p>
&lt;p>The processing of the survey follows the methodology presented in the book &lt;a href="https://www.tidytextmining.com/" target="_blank" rel="noopener">Tidy Text&lt;/a> by Julia Silge and David Robinson.&lt;/p>
&lt;p>First, this analysis focuses on the government plans of the top six parties with the highest voter intentions, as reported by &lt;a href="https://www.ipsos.com/sites/default/files/ct/news/documents/2021-01/anexo1_publicacion.pdf" target="_blank" rel="noopener">IPSOS&lt;/a>: &lt;strong>Victoria Nacional, Fuerza Popular, Partido Morado, Juntos por el Perú, Podemos Perú&lt;/strong>, and &lt;strong>Acción Popular&lt;/strong>. Notably, &lt;strong>Peru Libre&lt;/strong>, the party that ultimately won the election with Pedro Castillo as its candidate, was not even included in this survey. This omission starkly underscores how isolated Lima and its media are from the realities and priorities of rural Peru. Even the author, living in Lima at the time, was embedded in this bubble of perspectives, which largely ignored the growing influence of political movements outside the capital. This analysis, therefore, serves as a reminder of the biases inherent in focusing solely on urban, mainstream narratives while neglecting the broader political landscape.&lt;/p>
&lt;p>The purpose of this analysis is to help the reader understand the differences between the various government plans. For this purpose, the analysis strives to present the government plans impartially.&lt;/p>
&lt;h1 id="global-results">Global Results&lt;/h1>
&lt;p>Below is a word cloud representing the combined text from the six government plans:&lt;/p>
&lt;div class="wordcloud2 html-widget html-fill-item" id="htmlwidget-1" style="width:672px;height:480px;">&lt;/div>
&lt;script type="application/json" data-for="htmlwidget-1">{"x":{"word":["nacional","desarrollo","salud","sistema","servicios","gobierno","social","plan","recursos","calidad","acceso","infraestructura","seguridad","peruanos","empresas","personas","ley","millones","reforma","pandemia","programa","proyectos","niveles","programas","sociales","derechos","vida","sostenible","ciudadanos","gobiernos","regionales","pobreza","centros","digital","servicio","agua","covid","fortalecer","instituciones","marco","locales","procesos","enfoque","ministerio","forma","cultural","capacidad","capacidades","cultura","promover","transporte","base","sistemas","actividades","condiciones","integral","ciudadana","derecho","fortalecimiento","mercado","propuesta","zonas","ciudades","financiamiento","sociedad","territorio","justicia","mejorar","proceso","mecanismos","oportunidades","crecimiento","territorial","plazo","sectores","apoyo","naturales","peruano","ambiental","generar","lucha","cambio","impulsar","ambiente","pbi","violencia","desarrollar","gasto","productos","alto","implementar","mundo","cobertura","igualdad","red","laboral","reducir","regiones","garantizar","entidades","regional","culturales","vivienda","control","defensa","fiscal","rural","competencias","falta","mujeres","consumo","permita","superior","casos","medidas","objetivos","acciones","etc","ingresos","necesidades","transparencia","lograr","proponemos","comunidades","crisis","establecer","impacto","demanda","diversidad","necesario","alta","impulsaremos","redes","urbano","baja","empleos","humano","pensiones","rurales","cumplimiento","actividad","eficiencia","familiar","local","incremento","internacional","mejora","modelo","reformas","requiere","agricultura","eficiente","espacios","personal","peruana","bienestar","ciudadano","digitales","planes","privada","universidades","valores","crear","privado","tasa","pueblos","educativa","nacionales","obras","estrategia","inteligencia","libre","promedio","turismo","asimismo","conocimiento","costo","familias","funciones","internet","oferta","frente","industria","siguientes","competitividad","exterior","humanos","mypes","porcentaje","profesionales","puedan","respeto","anual","aumento","brecha","intereses","principios","productiva","asistencia","civil","docentes","estudiantes","estudios","presupuesto","productivas","decisiones","fundamental","incentivos","mercados","problemas","sentido","brechas","inversiones","popular","ciencia","necesidad","promoveremos","educativo","especial","fondos","institucional","laborales","patrimonio","conjunto","fondo","generando","informalidad","manejo","organismos","problema","tributaria","beneficios","futuro","impulso","mayores","productividad","principal","asegurar","bienes","capital","caso","conectividad","importante","lima","residuos","ambientales","carrera","centro","cuentas","riesgos","rol","comunidad","escala","judicial","objetivo","realidad","sostenibilidad","competencia","evitar","menores","negocios","riesgo","alimentaria","central","especialmente","mujer","mundial","tipo","trabajadores","actual","compras","contexto","datos","estrategias","internacionales","mejores","permitan","reconocimiento","universal","fomento","formal","legal","organizaciones","pago","promoviendo","educativas","empresa","gobernanza","impuestos","materia","principales","propone","saneamiento","secundaria","vulnerables","adecuada","financiera","hospitales","identidad","real","renovables","resultados","seguimiento","selva","cero","conflictos","cti","familia","forestal","monitoreo","productivo","proyecto","efectiva","enfermedades","escuelas","responsable","aprovechamiento","constitucional","crearemos","deporte","emergencia","estabilidad","historia","primaria","privados","sostenibles","tratamiento","viviendas","ausencia","cuentan","herramientas","institucionales","sexual","actores","cadenas","cargo","construir","contar","efectos","fuentes","fuerzas","funcionarios","gas","labor","normativo","paz","poblaciones","puestos","sanitaria","tasas","unidades","vulnerabilidad","adolescentes","compromiso","corto","desigualdad","eje","hogares","necesitamos","permanente","pymes","victoria","acceder","adultos","congreso","diversas","ejercicio","equipamiento","fiscales","ilegal","libertad","llegar","menor","meses","planeamiento","propuestas","responsabilidad","respuesta","delitos","diversos","empresarial","equipos","escolar","funcionamiento","oportunidad","pesca","privadas","urbana","beneficio","deuda","educativos","efecto","fuerza","integridad","mype","natural","registro","requieren","riego","alimentos","comercio","estatales","financiero","incrementar","matriz","peruanas","poblados","profesional","seguro","urbanos","agregado","autoridad","continua","costos","delito","desastres","fortaleceremos","infantil","normas","persona","pobres","presente","riqueza","actos","becas","camino","debemos","digna","espacio","ingreso","nativas","procedimientos","activos","cambios","crimen","implementado","institucionalidad","marcha","organizado","plataforma","recuperar","rescate","territorios","activa","alcance","ampliar","ciudad","confianza","distintos","docente","edad","equidad","instrumentos","propiedad","punto","seguros","administrativa","aplicando","bajos","descentralizada","esfuerzo","estatal","favor","importancia","interno","potencial","precios","prioridad","tiempos","universitaria","altos","autoridades","cadena","cantidad","ciudadanas","emisiones","enfrentar","entidad","entorno","esfuerzos","global","grupos","habilidades","habitantes","industrias","instituto","institutos","integrada","mediano","mejoramiento","orden","posibilidad","actuales","banco","cierre","contrataciones","cuidado","distritos","ecosistemas","garantice","ii","medicamentos","multisectorial","ordenamiento","potenciar","productivos","producto","suelo","sur","armadas","aseguramiento","atender","consecuencia","contratos","discapacidad","efectivo","emprendimiento","essalud","establecimiento","estructura","facilitar","fuente","inei","medios","micro","miles","padres","penal","pleno","productores","pruebas","situaciones","soporte","temas","transferencia","vivir","adecuado","administrativos","banca","colegios","complejidad","conocimientos","delincuencia","democracia","financieros","genera","igv","implementaremos","implica","incluye","iniciativas","inseguridad","necesita","oportuna","pre","pueblo","seguir","toma","vigilancia","agencia","aumentar","basado","bosques","circular","criterios","ejes","especies","garantizando","gremios","hidrocarburos","humana","incentivar","particular","periodo","potable","presupuestal","priorizando","priorizar","reactiva","siglo","suelos","tales","transparente","tributarios","carga","comunitaria","consejo","consolidar","dichos","evidencia","fomentar","fortaleciendo","impulsando","plataformas","pnp","prioridades","proteger","reglas","relaciones","tala","temprana","tolerancia","vacuna","aprendizaje","articulada","asegurando","ayuda","brindar","clave","compra","cuidados","debidamente","desarrollaremos","directivos","empleabilidad","fines","forestales","fuerte","incluyendo","informal","masivo","minsa","modelos","naciones","origen","resulta","talentos","us","vacunas","abierto","aire","bicentenario","biodiversidad","cambiar","conforme","desempleo","eficacia","elevar","empresariales","equilibrio","esenciales","estableceremos","formales","integrado","intervenciones","mecanismo","naturaleza","orientado","poderes","pondremos","puesto","recurso","sierra","talento","tomar","abastecimiento","agrario","agro","alcanzar","anemia","bases","cifras","concepto","consecuencias","demandas","dinero","ernc","especializados","experiencia","fundamentales","importantes","instancias","julio","mantener","pilares","puntos","regular","rentabilidad","solidaridad","tradicionales","viene","afiliados","aprovechar","bancos","busca","causas","cerrar","contrato","contribuir","creando","criminal","deficiente","deudas","directa","eficaz","elementos","equipo","especiales","generan","grado","incorporando","incorporar","informales","intercambio","interna","ministerios","municipalidades","oficinas","plena","progreso","reguladores","soles","subsidios","transversal","aguas","alcantarillado","avances","barreras","basada","ceplan","comercial","concesiones","consulta","convencionales","cumplir","dignidad","distancia","ecosistema","escenario","escuela","esquema","estableciendo","eventos","finalidad","gastos","haremos","iii","implementados","impuesto","independientes","infancia","insuficiente","insumos","limitada","lugares","minedu","pacientes","pandemias","pasivos","permitiendo","policial","post","resultado","saludables","servir","sunat","acorde","ahorro","altamente","altas","aps","aspectos","buscando","comerciales","consumidores","contribuyan","creemos","cuencas","cuya","deportiva","directamente","diversidades","encuentran","establecimientos","evitando","existente","existentes","extrema","factores","indecopi","indispensable","industrial","inmediata","integrar","jueces","materiales","orientada","pea","plantas","presencia","previsional","principio","progresiva","puesta","sectoriales","tele","vial","xxi","activo","acuerdos","amenazas","campesinas","carretera","comunicaciones","contenidos","convenios","costa","cultivos","desarrollando","distintas","eliminar","equilibrado","exportaciones","finalmente","hijos","ideas","individual","inicio","judiciales","legales","liderazgo","mantenimiento","mediana","mental","moderna","normativa","norte","permanentes","permite","presidente","prevenir","pro","prosperidad","pyme","resiliencia","resumen","segmentos","torno","tributarias","urbanas","viven","actuar","agricultores","alianza","animal","anti","aparato","aportes","asociaciones","asociatividad","colectiva","compromisos","consumidor","continuar","dejar","digno","dotar","ejecutivo","emprendedores","emprendimientos","establece","formas","funcionario","generado","generales","impactos","invertir","justa","laboratorios","logro","mano","modalidades","moderno","movilidad","museos","necesitan","preventiva","reconoce","reglamento","republicana","respetando","retos","saludable","suficiente","terrenos","tierras","unidad","acuicultura","adecuadas","afroperuanos","aporte","captura","comisiones","compatriotas","convivencia","corredores","creativas","denuncias","dignas","dignos","efectivos","ejecutar","elevada","endeudamiento","ente","erradicar","familiares","humanidad","implementada","intercultural","iv","lgtbi","libertades","mar","mejorando","militar","mmm","monto","necesaria","necesarios","optimizar","paciente","representantes","resiliente","revisar","tipos","universidad","universitarios","vital","vulnerable","adecuadamente","adecuados","afecta","afectan","apoyar","aprobado","artesanal","barrios","campo","canales","canon","casa","combatir","competitiva","competitivos","considerando","constante","contribuya","desigualdades","directo","escolares","esencial","estructurales","excelencia","fecha","financiar","futuras","grupo","hombres","incluir","incluya","iniciativa","interculturalidad","joven","juan","juntos","leyes","masiva","materias","municipales","participar","pesquera","pnic","profundas","progresivamente","promotor","protocolos","proveer","reforzar","resto","sanciones","subnacionales","suma","unidas","zona","abandono","actualidad","administrativo","ancestrales","andina","animales","aprender","aprobada","asegure","capitales","clusters","conscientes","constituye","decreto","demostrado","dichas","eficientes","electricidad","emprenderemos","especializado","existencia","exportadora","externo","fallas","garanticen","gei","hogar","honestidad","identificados","impunidad","inclusive","independencia","independiente","interoperabilidad","km","labores","logros","macro","manifestaciones","material","mejoras","miembros","mm","obtener","operativa","plantea","plazos","porcentual","promueva","promueve","provincias","registros","renta","rescatar","responsables","retorno","sectorial","servidores","solidaria","temporal","trabajando","trabajaremos","usuarios","virtual","alianzas","alumnos","anuales","artes","artificial","auto","avance","avanzar","bcr","carencia","ciclo","comportamiento","consideramos","continuidad","creatividad","dando","definir","descentralizado","dicha","disminuir","eliminando","empoderamiento","enfermedad","enorme","entornos","especializadas","etapa","expedientes","experiencias","extranjera","formalidad","funcional","gases","gubernamentales","individuales","industriales","inmediato","investigados","lote","mirada","mitigar","moleculares","obligaciones","obra","pacto","penales","perspectiva","pilar","procesamiento","progresivo","reduciendo","referencia","reformar","representa","resolver","responsabilidades","restricciones","sis","soluciones","superar","tarifas","terrorismo","tributario","utilizar","vecinales","venido","ventanilla","acelerar","afp","afrontar","ahorros","artesanales","articular","beneficiarios","bonos","buscan","cabo","camas","capaz","carreteras","colapso","compartido","competitivas","conjunta","creciente","cubrir","cumplen","debilidad","disponible","diversificada","especializada","evaluar","expresiones","expuesto","extranjero","factor","generaciones","grave","inadecuada","influencia","informe","inicial","instrumento","integrales","investigadores","ministro","necesarias","normatividad","operaciones","oro","pagar","policiales","poniendo","populares","presenta","preventivo","procesal","profunda","rector","regresar","saberes","sanitarios","superintendencia","tarifa","telemedicina","tema","territoriales","transportes","transversales","trazabilidad","vecinos","vigencia","vista","visto","abiertos","actualizar","adicionalmente","administrativas","adquisiciones","aeropuertos","agentes","agraria","agrarios","alternativos","ama","anualmente","aplicada","aprobados","banda","bolsillo","bono","burocracia","buscar","capa","componente","considerar","constitucionales","constituyen","contacto","corporativo","crudo","cultivo","culturas","cuyo","defender","defensores","directos","disponibilidad","duplicidad","equitativa","funcionando","gestionar","gratuita","identificar","implementando","inclusiva","ineficiencia","ineficiente","infectados","infoestructura","informes","iniciar","instancia","juntas","latina","legislativo","lgbti","licitaciones","limitaciones","limpias","mala","maltrato","media","mineras","ministros","mitad","monetaria","motivo","muestra","multimodal","municipal","opciones","operadores","otorgar","partes","participan","pcm","pertinencia","piloto","planilla","poblacionales","predios","presencial","presidencia","remuneraciones","rendimiento","reservas","salir","sana","secundarios","snp","tareas","tradicional","urgencia","vinculados","voluntad","agenda","alternativas","ancha","aprovechando","articulado","aseguraremos","barrio","basados","cabe","caminos","camiones","cargos","casas","catastro","circuitos","clima","coca","contactos","contagios","corresponde","corte","cuente","deberes","deportivas","detectar","diciembre","disponibles","efectividad","ejercer","elecciones","embarazo","estudiante","estudio","extranjeros","facturas","fase","ffaa","fibra","financieras","finanzas","flota","formato","generen","hospitalaria","humanas","incluyen","integrando","interior","investigaciones","lineamientos","luz","madera","marina","medicina","medida","mef","mejoraremos","memoria","mineros","mipyme","motor","multianual","nutricional","obliga","ocde","organismo","originarios","parcial","partidos","permanencia","permisos","pesqueros","precaria","predictibilidad","presupuestos","previa","producida","propondremos","rdnfo","reactivar","reciben","recibir","relacionados","residuales","rubro","ruta","segura","significa","similar","solidario","sostenido","spp","subsidio","sunedu","superiores","sustentada","tomando","trabas","transformar","tratados","trayectorias","unidos","utilizando","variables","venta","ventajas","verde","viables","vienen","vigente","vinculadas","virtuales","web","abierta","acabar","academia","adicional","adoptar","alternativa","amazonia","amenaza","aprendizajes","art","aseguren","aspecto","atractivo","autorizaciones","brinda","carbono","carreras","certificados","circuito","clara","claves","cofinanciamiento","colectivos","comunales","contribuyendo","coordinada","cosecha","creado","cursos","daremos","deber","declaraciones","deja","departamentos","deportivo","desastre","destinados","distrito","drogas","encontrar","espera","estructural","estructuras","etapas","excesiva","formativas","garantiza","generados","globales","gracias","graves","hambre","implementadas","in","incrementando","intersectorial","juradas","justo","lesa","licenciamiento","licencias","limitado","logrado","luchar","meritocracia","militares","minero","modernos","modificar","moral","negocio","nuevamente","nutritivos","oficina","oligopolios","operan","papeles","parque","permiten","pertenece","pertinente","porcentuales","positivo","prestaciones","previo","privilegios","produce","protegidas","puertos","reales","recibe","reduciremos","relevancia","remota","representan","restaurar","revertir","salariales","sancionar","sanitarias","significativamente","soberano","start","tarea","temporales","terrestre","velocidad","verdes","acceden","activamente","adicionales","afectando","afectar","amplia","aplicar","atraer","aumentando","bajas","belaunde","buscamos","callao","calles","capacitados","capacitar","causa","cem","chile","colectivas","complejos","comunes","comunitario","conducta","conformado","consejos","consiste","consulados","consultas","contenido","creativa","cuenten","darle","data","debate","deficiencias","dependencia","desarrollado","desechos","dificultades","dimensiones","doctrina","documento","dominio","dosis","efectivas","electorales","elevaremos","emprendedor","encargada","encuesta","entrada","entrega","equivalente","esquemas","evidente","exige","expandir","exteriores","externa","fortalecido","fujimorismo","gobernabilidad","gore","gubernamental","hora","horizontal","igualitario","incapaz","incertidumbre","integradas","involucrados","juvenil","legado","legislar","libres","limpia","lleguen","maestros","mandato","medianas","minera","mixtos","modernizar","morada","mortandad","mtc","multidimensional","norma","normalidad","obligatoria","obligatorio","observatorio","odio","ofrece","ofrecen","organizada","papel","parques","participaciones","perdido","perfil","permitir","personales","pesqueras","planteamos","plenamente","poblacional","podamos","precario","preservar","primario","prioritario","prioriza","procesados","profundizar","propiciando","propiciar","provinciales","prueba","racial","re","reconocer","requisitos","reserva","respondan","ruc","serenazgo","serie","siquiera","sitios","sobretodo","sub","suficientes","suman","susalud","sustentado","talleres","telecomunicaciones","termina","tierra","trabajador","trabajos","tramo","transferencias","trayectoria","turistas","ups","vidas","virus","viva","volver","abusos","accidentes","acelerada","acerca","acercar","ampliando","ancestral","antecedentes","aportantes","arte","asamblea","basadas","blandas","brindan","brinden","bruto","cercanos","ciento","colas","combustibles","comedores","completo","concurrencia","concurrente","concursos","conectar","constituyente","consulado","contaminantes","contrario","contratados","criterio","cuarta","cuerpo","cumplan","cuyos","dada","deba","dejando","densidad","denuncia","departamento","deportistas","desarrolla","desarrollados","desarrollen","diplomacia","distanciamiento","dni","doble","docencia","egresados","elaborar","electoral","emocional","empezar","entes","entrenamiento","escasez","escasos","estudiar","exclusivamente","excluyente","existir","extender","facultades","fija","flexibles","fomenta","fomentaremos","formar","formativos","ganancias","garantizado","garantizaremos","gente","gores","gravemente","hacerse","herramienta","honesta","ideario","importar","impulsen","incapacidad","incentivo","inclusivo","inequidad","inestabilidad","inmaterial","inmunidad","innovadora","innovadores","integrados","integre","inteligente","intergubernamental","isc","juego","lamentablemente","lanzaremos","licencia","liquidez","llega","llegan","logrando","lotes","madres","manteniendo","marca","medicinas","modos","monopolios","multas","municipios","negativos","normativas","nutritivo","optimizaremos","ordenado","orientadas","otorgamiento","paradigma","paralelo","parlamentaria","patentes","pensamiento","pese","peso","planeta","podido","ponen","posibilidades","posibles","positivos","potencialidades","precariedad","precarios","precedentes","preparado","priorice","prioritarios","promulgada","proponer","quedado","racismo","radio","realidades","realizan","realmente","reciclaje","reducido","regulatorio","relevantes","rentable","rentas","republicanismo","requerimos","romper","rondas","rutas","salarial","senasa","siguen","sociedades","solar","sostenimiento","ssr","sueldos","sufrido","supervisar","suscritos","sustancialmente","sustentable","tempranamente","tendencia","totalidad","transformaciones","tratar","trimestre","usos","vecinal","vive","voto","abordar","activar","actualizado","adecuar","afectado","afps","afrodescendientes","afroperuana","agilizaremos","agravado","alternancia","ambientes","amigable","ampliaremos","andino","anexo","aprobar","arequipa","articule","ascensos","asentamientos","asignados","atractivos","automatizado","bibliotecas","calificados","calzado","canasta","caos","capaces","caracterizado","carece","cartera","cas","catastros","celeridad","certificaciones","cites","claras","clase","coaching","combate","compartimentos","competentes","comprende","comprometido","comunal","concentrada","concesionario","conciencia","concursables","congresistas","consecuente","considerados","consistente","contagio","contribuciones","contributivos","contribuyen","contribuyentes","convencidos","convierte","cooperativas","coronavirus","corregir","crea","crecer","criminalidad","cuarentena","cuellos","darse","decididamente","dedicados","degradadas","delincuentes","depende","dependientes","deportivos","detalle","determinar","diez","diferencias","dirigidas","dirigido","disponer","documentos","domiciliaria","dual","dudosa","ejecutadas","elegidos","elemento","embarcaciones","empleados","encontramos","equipados","esencia","estancos","evite","exigencias","exoneraciones","exportador","extremo","farmacias","felicidad","finales","fondem","frontal","generadores","gerencia","gestionaremos","gratuito","guerra","haga","idea","ilegales","impacta","inclusivas","incorpora","indebido","infraestructuras","injerencia","instalada","insuficientes","inteligentes","intercambios","intermedias","invernadero","ipd","iquitos","junio","jurados","juventud","lanzamiento","lava","lengua","libros","localidades","lucro","madre","mancomunidades","manos","mantiene","mascotas","matrimonio","mes","metropolitana","minerales","modificaciones","monitorear","movimientos","muertes","multisectoriales","numero","obstante","oficial","oficiales","oficio","operativos","organizacional","organizadas","orientados","otorgando","palanca","participativa","pasando","paso","pasturas","pensionistas","per","perder","perjuicio","permitido","pesado","pescadores","planificadora","planillas","positiva","postas","potenciando","preventivas","primas","prioritarias","productor","productoras","promperu","prompyme","proveedores","provincia","puno","punta","queda","ranking","realiza","reclamos","reconocemos","reconocidos","reconstruir","reemplazo","reformular","regulatoria","rentabilizar","republicanas","resaltar","respectivos","responde","saldo","salto","sano","seguras","seleccionados","sentencias","serio","sexo","shock","siembra","significativa","siguiendo","similares","socio","sostener","sostenida","subasta","suele","sumado","supone","tantas","tarjeta","tendencias","tope","traban","trans","uci","unificado","unitario","universitario","urgente","usd","utilizados","vertical","vraem","zee","abastos","abordaje","aborto","abril","absoluta","accede","accesibilidad","accionar","acelerado","acto","actualizados","adaptarse","adquiera","adscritos","afectadas","agresivo","agropecuaria","aislamiento","ajustes","alcanza","alcanzado","alimentarios","alineamiento","almacenamiento","amparo","apertura","aplica","aplicable","aplicaciones","aplicado","apostamos","apoyando","aprueba","asociada","asociados","asociativos","asumen","asumir","ataque","atenciones","atenten","austeridad","balance","basa","beneficiados","bosque","brindando","carencias","carteras","censo","centrales","centralismo","cifra","circunstancias","clases","cofopri","coherente","colectivo","columna","combatiremos","comisarias","competir","competitivo","complementado","complementar","completa","completamente","comprar","comunitarios","conceptos","concytec","conferencia","conflictividad","conformados","consenso","contener","controlar","convertido","convertir","convertiremos","convertirse","correcto","corriente","corrupto","costumbres","creados","cuenca","cumplido","cuota","cuotas","curricular","cuyas","debilitado","dedicarse","defendemos","demandadas","demora","deportes","desatada","descentralista","descongestionar","desigual","deterioro","diferenciadas","digesa","dirigida","discriminatorios","distinta","distritales","diversificar","ds","ducto","duplicar","economica","eficaces","ejecutado","elevados","elevando","emergencias","empleadores","emprender","empresarios","encuentren","ende","enfocados","enfoques","equipamientos","escenarios","esparcimiento","especialistas","estable","establecidas","estilo","exigencia","exitosa","extremos","favorecer","feminicidio","firme","forjar","fortalece","fortalecida","fortalecidas","fraude","funciona","fundamento","fusiones","futura","futuros","gasoducto","generada","generadora","genere","gerentes","gobernar","habilitados","harina","herencia","hidroelectricidad","hiper","historias","hoja","hospitalarias","idioma","igualmente","iic","importaciones","impulsa","incidencia","incluidas","incluido","incorporan","incorporen","indicador","informada","intencionalmente","interculturales","inundaciones","inversionistas","juegos","juicios","lectura","lenguas","ligada","llegue","localidad","maestro","magisterial","magnitud","mantienen","mapeo","marginales","marzo","maximizar","mayo","mega","mesa","migratoria","minam","mincetur","minplan","mipymes","miras","modernas","mostrar","muestran","nombramiento","obligado","obtenidos","oficialmente","oleoducto","onp","operatividad","ordenar","organizaremos","orgullo","orienta","otorga","paralizados","parlamentario","parlamento","particulares","pe","peligro","pensionario","perdidos","peru","picchu","plantear","pone","portabilidad","posgrado","postores","precarias","precio","premios","presentar","presidentes","previsto","primordial","priorizaremos","producen","promesa","proponiendo","protegiendo","proteja","protesta","provincial","puentes","quedan","radical","rastreo","razones","realizadas","rebrotes","recetas","reconociendo","recuperaremos","reducida","reduzca","referente","registrados","relevante","remunerados","reportes","respaldado","respectivamente","respectivas","responder","retraso","rezago","roles","salida","sbs","semillas","sentar","serias","severamente","simple","simplificados","simplificar","sisfoh","smart","software","solicitudes","solidarias","spc","stock","sustento","tercer","terroristas","tesoro","tradiciones","transitorio","trato","tributos","tupa","umbral","universales","usando","usuario","ven","ventaja","ventas","verdaderamente","verdaderos","viceministerio","vinculante","vivimos","voluntariado","abastecer","absolutamente","accesible","activas","acuden","acusen","adecuando","administraciones","administradoras","administrar","adolescente","afectados","afiliado","agravarse","agregada","alerta","alguien","alimenticios","alineado","alquiler","alternativo","ambas","ambiciosa","amplio","amplios","anchoveta","andinos","ap","aplicados","app","apps","apreciar","aprobadas","aptitud","apuesta","arbitraje","armas","articulador","articulados","articulando","articulen","artistas","asciende","asegura","atribuciones","atunera","autorizados","basta","beca","beneficia","big","bilateral","biomasa","bn","botella","brinde","buscaremos","cabeceras","canalizar","capacitaciones","capacitando","carta","causado","centralizada","cercana","certificadas","cetpro","chatarreo","cic","cientos","claros","co","cobranza","cobro","comparables","compartida","comprometemos","comunitarias","concentrado","concretar","conectado","confinamiento","conforman","conglomerados","consciencia","consensos","conservar","consideradas","considere","constitutivo","contamos","contempla","contingencia","contingentes","contratar","contribuye","controles","convenio","convirtiendo","cooperativo","correctamente","correctivas","corrientes","corrupta","crediticio","cualitativo","cubiertos","cuidando","cuidar","cumpliendo","debilidades","debilitamiento","declara","declarar","defensoras","delyr","dependiente","derrotar","desarrollan","descentralizados","deseen","despilfarro","devolver","diferencia","digemid","dinamismo","direcciones","directivo","directorio","dirigentes","disciplina","dispositivos","disuasiva","dorsal","ecuador","efectivamente","eirls","ej","ejecutivos","ejemplos","elaborado","elevado","embarcaderos","empleado","enfrentan","enormes","entendido","entrante","errores","escalamiento","escalar","escasa","escaso","especifica","esperado","esperanza","establecen","establecidos","estaciones","estandarizar","estatuto","estima","estrecha","estudiantil","estudiantiles","expertos","explica","extraordinaria","facilidad","facilite","fae","fallos","feminicidios","fideicomiso","financiadas","flujo","flujos","fluvial","foncodes","formular","fragmentado","frontera","fronteras","fujimori","fundamentalmente","generaremos","gestionado","grados","hacerla","hacinamiento","higiene","hijo","hipotecarios","horarios","horizonte","hospital","hoteles","identificadas","idoneidad","iest","iglesias","iguales","igualitaria","impactan","impide","implementan","incentivaremos","incidir","incluidos","inclusivos","incrementado","incrementaremos","indirectos","indispensables","induce","inhumanos","innovador","innovadoras","instalaciones","instituyendo","intensivo","internos","introducir","irreversible","jato","jne","jornada","jornadas","jubilados","justas","juveniles","largas","lecciones","legitimidad","lenta","lento","liderado","liderar","litigio","llegado","llegando","llevado","logran","lograrlo","lograrse","loreto","macrorregionales","mafias","mapa","masivas","mejorado","mensuales","merece","microempresas","militantes","minas","ministeriales","mixto","modalidad","monumentos","morales","mortalidad","motivos","multilaterales","nativos","necesariamente","negativa","netas","nombrados","objeto","ocasiona","ocurre","ofrecimiento","ola","online","operativas","ote","pagos","paquete","paquetes","parlamentarios","participa","pasar","patrimonial","patrones","patrullaje","paulatina","peligrosidad","pensar","perfiles","pescado","pesquero","piura","planificar","plenipotenciarios","portales","posterior","presentado","presentes","presidencial","presupuestales","privarlos","procuradores","producido","produciendo","profesores","progresar","prohibiendo","promoverlo","promueven","proporcionar","propuesto","protecciones","prudencia","publico","punible","racional","racionalmente","rango","ratio","realicen","realizando","rebote","recibido","reconocen","recuperadas","redundancias","referida","refleja","reformaremos","refuerzo","reguladora","remanentes","remunerado","reniec","rentabilizando","reorganizaremos","repo","reporte","reproductiva","republicano","republicanos","requerido","requerimientos","requieran","requisito","residencia","respaldo","responden","reto","revalorar","ricos","rincones","roma","salvaguardar","sanos","secundario","segmento","semanales","semipresencial","sentencia","serfor","seria","simples","simplificando","sinergias","sirvan","sirven","sobrecostos","sobrevivencia","socialmente","socioculturales","solucionar","subir","sucesivos","sufrimientos","sujetos","suministros","sunafil","supervisor","supervisores","sustentables","sustentar","tdnr","tejido","temor","temperatura","terceros","terminales","transparentar","transparentes","trascendencia","tribunal","turno","unificando","urge","urgentes","utiliza","vacancia","variedad","vayan","vehicular","vemos","ventiladores","viabilidad","vice","vigoroso","vinculan","vocaciones","xx","abajo","abogado","abuso","acondicionamiento","acortar","actitudes","actor","administration","adoptado","adscrita","agencias","agendas","agilizar","agosto","aguda","agudizarse","ajuste","alberga","alcanzados","alejadas","alentar","aliviar","almacenes","alumno","ambicioso","ambientalmente","andinas","anteriores","aparte","aplicables","aporta","aportar","apropiadas","aprovechan","articularemos","as","asesoramiento","asignado","asignatura","aspira","aspiraciones","asumidos","asumimos","ataques","atendida","audiovisual","aumentan","aumente","aus","autopista","ayudar","bajar","balas","barriles","bcrp","beneficiadas","bicicletas","bid","bio","biodegradables","bioseguridad","blindaje","bordea","burocratismo","busque","caja","cambiante","cancha","candidatos","capacitada","capacitado","capitalismo","cara","carpeta","carteles","causal","cercanas","china","ciencias","cine","civiles","claramente","clientes","clubes","coadyuve","coberturas","colonial","comando","combata","combatiendo","combustible","comenzando","comienza","compadrazgo","competente","complementada","complementaria","comprender","conaca","concedente","concesionarios","concluya","concretas","concurso","conduce","conflicto","congestionar","conocidos","conquista","consciente","conseguido","considerado","consiguiente","consorcios","construyen","construyendo","contables","contaminante","contando","contenidas","contextos","continuaremos","contralores","contributiva","convivimos","coordinar","correcta","correspondiente","correspondientes","corruptos","cosa","cosechas","costeras","creacion","creadores","crece","crecido","criminales","cubierta","culminar","cumple","cuna","curriculares","curso","debiendo","debiera","decenas","decidido","declarado","dedicado","deficientes","definidas","definitiva","definitivamente","dejen","demandan","den","departamental","departamentales","deportista","deriva","desarrolladas","desayuno","descanso","descongestionamiento","desmedro","desordenado","despliegue","desterrar","destiempo","destinadas","destino","destrabe","detectados","determinadas","determinante","devastadoras","devenga","diarios","dictado","dificultan","dinamizando","dinamizar","dinamizaremos","directiva","directores","directorios","dirigidos","disciplinas","dispersa","distribuida","distrital","duda","eba","eco","ejecutan","ejecuten","ejecutiva","ejecutoras","elaborados","eliminaremos","embajadas","eminentemente","empoderar","enaco","encargadas","encargado","encuentre","enero","enfocada","enfrenta","enfrentamos","enfrentando","entrampamiento","entrar","envejecimiento","envergadura","equipadas","equipar","equiparar","equitativas","escalas","escritura","especialidades","especializaciones","espejismo","esperar","establecida","establecido","estamentos","estandarizado","estimulantes","estricta","estricto","estructurado","evidenciado","excepcional","exceso","excluidos","existan","expediente","expresa","extendida","externos","extremas","facilidades","factibilidad","fallecidos","fauna","fcrp","fernando","firma","fiscalizador","fiscalizar","flagelo","fluviales","foco","formalizados","formalmente","formativa","formulan","fortalecidos","fortaleza","fortalezca","forzado","fracasado","fragmentada","fuertes","funcionan","funcione","fundamentos","gabinete","gama","garante","garantizada","gasolinas","generador","gestionada","golpeados","gozar","grande","guardabosques","habitante","hablar","hagan","huaicos","ideal","identidades","identificado","identifique","idiomas","iiee","imagen","imarpe","impagos","imparte","impedir","impiden","implementa","impulsado","impulsados","impunes","incas","incendios","incorpore","inculcar","independientemente","indica","individuo","inexistencia","influencias","info","inglaterra","iniciado","inmediatos","inmensa","inmuebles","innovate","inpe","instalar","institute","insumo","integrantes","integren","intensidad","interconectada","interinstitucional","introduciendo","invertido","investigar","invirtiendo","involucre","junta","jurisdicciones","justos","labranza","lavado","learning","libro","liderada","ligadas","limpio","litio","liviano","llevando","llulla","logre","luchando","lucharemos","machu","make","malos","manuales","manufacturera","marginal","marinas","mascarillas","materializarse","mayoristas","mejore","mejoren","memorias","mencionados","mesas","mfop","migrantes","milagro","milenaria","minagri","minoritarias","modificado","monocultivos","monumental","moratoria","mostrado","multidisciplinarios","multinivel","necesiten","negociar","neo","neoliberales","nevados","nombramientos","noviembre","nula","obligatoriedad","obsoleto","ocupados","ods","oecd","of","ofreciendo","ofrezcan","operando","oportuno","optimista","optimizados","ordinarios","organizados","originada","original","otorgue","ott","oxigeno","paga","pagado","pagan","pagando","paralizadas","pares","participativo","participen","particularmente","pasa","pasajeros","pasivo","pdu","pena","penas","pendiente","perfeccionamiento","pericia","persistencia","pertenecen","pertenencia","pfizer","pide","pierde","piezas","pisco","piso","pisos","pistas","plantaciones","planteadas","poli","ponga","porcentajes","portuario","portuarios","posee","posicionamiento","posteriormente","potenciador","potencialidad","preferencial","prensa","prepago","preparar","presentada","presentan","preservando","presidenciales","prestadoras","previas","previsionales","prima","primarios","primeras","priorizados","proactiva","probable","procurando","producir","produjeron","profundamente","profundidad","promocional","promotores","promuevan","proporcionando","propugna","propugnamos","protegida","protejan","prototipos","proveedor","proyecciones","proyectada","publican","puerta","puertas","quella","raza","razonables","reactivo","realistas","realizarse","rechaza","recientemente","recoger","recompra","reconocidas","recordar","recuperado","redefinir","redujo","referido","refiere","reflejan","reflejar","refugio","registrando","registrar","regulan","reinante","relacionadas","relativo","religiosa","rellenos","remesas","renovable","renovado","renovar","rentabilizadas","reordenamiento","reorganizar","repago","reparaciones","reparto","repotenciar","representados","representar","representativas","representatividad","representativo","representativos","requerimiento","resuelvan","retiro","retornar","retroceso","revalorizar","revisaremos","rezagado","riguroso","rigurosos","ritmo","rof","rrss","salvaguarda","sancione","sanipes","sanitario","satisfacer","satisfaciendo","satisfactoria","satisfactorio","seguido","sensibles","serenazgos","seres","servidas","sexuales","siembras","significativos","simplificaremos","sistematizado","sistematizar","sobrecarga","socioemocional","soportar","sua","subastas","subempleo","subsistemas","sufren","sujeta","superan","superando","supere","superficie","supremo","surge","sustentabilidad","sustentados","sustitutos","tablet","tc","technology","techo","tecnificado","tenencia","terminado","terminan","terminar","terreno","texto","tgp","tic","titular","topes","totalmente","traba","traduce","trae","transferidas","transformaremos","transitar","transmisibles","tratarse","trazado","trimestral","trujillo","tv","ubicados","uit","unificar","universalidad","uruguay","utilidades","valles","valorando","vehiculares","venga","venimos","verse","viajes","vicioso","vigentes","vih","vincularemos","vio","violencias","violentas","voluntaria","voluntario","voz","vulnerabilidades","abandonadas","abarcar","abatimiento","abiertas","abundantes","abusiva","accesibles","acercando","acortando","acreditados","acudir","acumulado","ad","adendas","administrado","adolescencia","adulta","adversos","afectada","afectas","afecten","afines","afirmado","afroperuanas","aglomeraciones","agrarias","agrava","agravante","agroforestales","aisladas","aislado","alarmantes","alberto","alcances","alemania","aliados","alineados","almacenaje","andamiaje","anp","anterioridad","antiguo","apartado","aplicadas","aplican","aportan","apostando","apostar","apoyamos","apoyan","apoyos","aprendo","apunta","apunten","arancel","aras","argentina","armoniosa","arreglos","articuladores","aseguran","asesor","asignadas","asistir","asociativa","asume","atacando","atendidas","atendidos","atraso","atraviesan","automatizada","automotor","automotriz","avanzada","avanzadas","avanzados","ayuden","balanceado","balanza","bancarios","barato","basan","beneficien","bim","binacionales","biodigestores","biodiversa","bionegocios","bisexuales","blancos","blockchain","boletas","bolsas","brasil","buses","business","caf","cajamarca","cajas","caldo","calentamiento","calificado","cambiado","cambiaremos","camisea","caracteriza","carcelaria","carecen","cargas","caros","causar","celac","celulares","centers","centrado","centralista","cercano","cerraremos","cerrojos","cicc","ciego","cien","cimientos","citas","climas","coactiva","cobrado","cobros","coexisten","coexistencia","cofide","colaborativo","colapsado","colegio","colombia","coludidos","comisionados","compartidas","compartidos","compatible","compiten","complejo","complementariamente","complemento","compone","componentes","compromete","comprometidos","comprometiendo","comuneros","conafor","concentra","concentrando","concesionarias","concluido","concluir","concordancia","concreto","condena","condicionadas","conductas","conectadas","conectados","confiable","confieren","configuran","confluyen","conformar","conjuntas","consagrado","consagrados","consensuada","consensuadas","consensuado","consta","constitucionalmente","construccion","construcciones","construidas","construidos","construya","contaba","contemple","contengan","contenida","continuas","continuo","contrabando","contractual","contrarrestar","contrasta","contribuido","contribuyente","convierta","conviertan","convivir","convocar","coop","coordinando","corea","corresponda","corresponden","cortos","cotidiana","coyuntura","cpm","creada","crean","creativos","credibilidad","crediticia","crediticios","creencia","crucial","cruel","cubierto","culminan","cumpla","cura","cursado","dadas","deban","debida","decente","decidida","declarada","dedica","dedicadas","define","degenerativas","democratizar","demostrando","demuestra","denominaciones","denominado","denominados","dependa","depender","depredador","derivados","derogada","desaparecidas","desarrollarse","desarrolle","desarrollos","desarticulada","descansos","descendientes","descentralizadas","descubiertos","descubrir","descuento","descuentos","desequilibrio","desfasada","desfasados","desincentivan","desleal","desocupados","desorden","desordenada","despegue","destinado","desventaja","determina","determinado","determinan","determinantes","devolverle","diaria","diarias","dificulta","digitalizados","digitalmente","dinamizador","diploma","diplomado","directas","dirigir","discrecionalidad","disfrutar","disminuiremos","disminuya","dispuestos","disruptivas","disruptivo","distribuye","disuasivo","diversa","dl","doctorados","domiciliario","dotarlos","dpas","duro","dv","economist","ecoturismo","edades","eeuu","eficientemente","electro","elegido","elimine","emitir","emp","empieza","empoderaremos","empresarias","enap","enapu","encargan","encuestas","enfoca","enfocado","enfocarse","enmarca","enriquece","ensayos","entender","entendiendo","entendimiento","entiende","entrampada","entregado","entregue","epidemias","eps","equipada","equivale","escoger","escucha","esfera","estabilizar","establezca","estandarizados","estrictamente","estrictas","estructuran","europea","evaluando","eventuales","eviten","exacerbado","excelentes","excesivo","excluidas","exclusiones","exista","exitosas","expansiva","explican","exploratoria","exploratorias","explotaciones","exportable","extensionistas","extensivo","extorsiones","extractivas","extractivos","extraer","extrajudicial","facilitador","facilitan","facilitarle","facultad","fallado","farmacovigilancia","fases","favorecidas","federaciones","feminista","financiado","financiamientos","financiando","firmar","fise","flexibilidad","fomenten","fonafe","formado","formados","formalizadas","formalizar","formalizarlos","formativo","formularemos","foro","fracaso","ftth","fuego","fuertemente","funcionales","gais","gana","ganancia","ganando","ganar","gasolina","gatilla","generadoras","generalizada","gestantes","gestionadas","gestiones","giratoria","gnl","golpeado","gozan","gratificaciones","gratuitamente","gratuitos","gravedad","grifos","habitacionales","hablamos","hacerlos","hacienda","hechos","hijas","historial","hoc","homologar","hotelero","hoyo","huancabamba","humanitaria","iafas","ie","iesp","ilo","impacte","impartida","implementaron","impone","importador","importando","imposibilidad","impostergable","imprescindible","impuestas","impulsamos","inacal","incentivado","incentivando","incentive","incida","incide","incidentes","incipiente","incluida","incluiremos","inconexos","incrementa","indebidos","indiscriminado","inefectividad","ineficientes","inexistente","infoplanilla","ingenieros","ingentes","inglesa","ingresa","inicios","injusticia","inmobiliarios","innecesarios","innovar","ins","insertar","insignia","instalados","intangible","integralmente","integran","integraremos","intelectual","intensivamente","intensivas","intensivos","interactiva","interconectividad","interesa","interferencias","intermediarios","intermedio","internacionalmente","intersectoriales","intersexuales","invierta","invierte","involucradas","involucrando","involucrar","ipis","ipress","irlanda","irregular","irrestricto","itp","jefe","juez","jugar","jurisprudencia","juventudes","juzgados","laboralmente","laico","largos","latente","lesbianas","ligados","limita","limitando","limpieza","line","lista","llamado","lobby","localmente","logistica","logra","lograron","logren","longevidad","longitudinal","luchamos","machine","made","maderables","madure","magistrados","malla","maneja","manejados","manejar","mantenido","manufactura","mapas","maquinarias","marcona","marcos","masa","masivamente","materializar","materna","mayormente","medias","medioambientales","megadiverso","mencionado","mensual","mentalidad","mente","mentiroso","meramente","mercadeo","mercantilismo","mercantilistas","merecen","mero","metalurgia","microfinancieras","midis","migratorias","migratorio","mimp","mincul","mini","minimizar","misiones","modificados","monocultural","monopolistas","montos","morbilidad","morosidad","motores","mtpe","muestras","multa","multi","multiculturalidad","multiples","nacen","nacimiento","necesitados","negociaciones","neoliberal","netflix","nombrado","nombre","normativos","norperuano","nota","nsnp","nstitucional","numerosas","nutrientes","obligadas","obligan","obligar","obviamente","ocasionada","ochenta","ocioso","ocupada","ocupar","ocurrencia","oficios","ofrezca","omaped","oms","on","opera","operativo","operen","ordenada","oredis","organizar","organizativa","orientador","orientar","oriente","origina","orquestas","otorgadas","otorgan","pad","pagadero","paliar","paliativo","panamericanos","pandillaje","pantalla","papa","paralelamente","parciales","parcialmente","participando","pasaremos","pasaron","patente","patrulleros","pavimento","pbu","pcn","peligrosos","penalidad","pendientes","pensionables","peores","perdiendo","perfeccionar","perfeccionaremos","perfilar","performance","periodos","perros","personalidad","pertenecientes","pertinentes","perusat","pico","planificada","plano","planos","plantean","plantearse","platos","plazas","plural","pluralidad","pluralismo","poblado","pobladores","pobre","policias","policy","politica","polos","pongan","populistas","portafolio","poseen","posteriores","postgrado","potencia","potenciaremos","potencie","precisando","precisiones","predecibles","predial","pregrado","premisa","preocupaciones","preparadas","prepare","presentados","presididas","presos","presta","prestadores","pretende","pretender","previos","prioricen","prioritaria","prioritariamente","privilegiando","privilegiar","probablemente","procesar","producidos","profundizando","profundizaremos","profundo","programar","progresivos","promedios","pronaa","pronamachcs","propicias","propiedades","propietarios","proponen","proporcional","propulsar","propuso","prospectiva","protege","provea","provecho","proveen","provenientes","proviene","provisiones","provocado","proyectado","publica","publicada","pucallpa","puente","puerto","qali","quechua","quedando","quedaron","queden","quehacer","quema","quiebras","quinquenio","quo","radios","ramas","rangos","rasgos","razonabilidad","reactivando","reafirma","realista","realizada","recauda","recaudar","receta","rechazamos","reciban","recibiendo","recomendaciones","recomendadas","reconocida","reconozcan","reconvertir","recreativas","rectoras","reducidos","reemplazar","reestructuraciones","reestructurar","reflejo","reforestadas","reforestar","reforzamiento","reforzando","reforzaremos","refundar","registrado","reglamentos","regresa","regulado","regularemos","rehabilitar","reincidencia","reino","remuneradas","remunerativa","rendir","rentables","rentista","reos","repos","repotenciados","reprimiendo","requeridas","requeridos","requiera","reservados","residentes","resilientes","respaldada","respeta","respetar","responda","respuestas","restablecer","restaurantes","restituir","retira","retirar","retornen","revisarse","revitalizar","rico","rigen","rigor","rndfo","robo","robustecer","robusto","rubros","rumbo","sabido","salario","salarios","salaverry","sancionado","sancionadora","santa","sars","satelital","secano","sedes","seguida","seguimos","selectiva","semana","semanas","sembradas","semestre","semi","sencillos","senda","sensaciones","septiembre","serios","sesiones","severa","severas","shocks","significativo","sincerando","sismos","sitio","soberana","socios","sofisticados","solicitar","solidez","solvencia","sostenidamente","sostiene","startup","status","subnacional","suboficiales","subsectores","subsidiado","subsistema","sucede","sucedido","sueldo","suelen","suerte","sujeto","superficiales","suponen","sustancial","sustantivas","sustenta","tagle","tambo","tambos","tecnologia","tentativa","terminen","testigos","textiles","the","tics","tiende","tim","tocache","tolerantes","tomadas","torre","trajeron","trajo","tranquilidad","transcendencia","transexuales","transferir","transformado","traslado","tratamientos","travestis","trazados","treinta","tripulantes","tsunamis","ubicado","uif","unasur","universitarias","usualmente","usureras","vacaciones","validar","valioso","vanguardia","varados","variabilidad","vea","vectores","vegetales","vendedor","vender","ventana","ventures","verdaderas","versus","viabilizar","viable","video","violan","violentos","virtuoso","visibilidad","visibilizar","visita","visitantes","viviendo","vivos","vuelto","vuelva","vuelvan","vuelve","vuelven","vulnerado","warma","working","xix","yacimientos","zaga","aa","abandonado","abanico","abarque","abastecen","abogados","absorber","absorbiendo","abusivo","accedan","accesos","aceites","acelerador","aceleremos","aceptables","aceptada","acercamiento","acervo","aciertos","acoger","acogimiento","acopio","acordes","acortamiento","acreditaciones","acreditadas","actualiza","actualizadas","actualizaremos","acumuladas","adaptar","adapten","adecuaremos","adecuarse","adenda","adi","adicciones","adjudicados","administra","administrada","administrador","administrados","adopta","adoptadas","adquirido","adquirir","aduanas","adulto","adversas","afecte","afianzar","afiliadas","afirmamos","afirmar","afirmaremos","afirmativa","aforo","afroperuano","agente","agilizando","agotamiento","agravando","agredidos","agreguen","agresiones","agresiva","agresivas","agresores","agrobanco","agrobiodiversidad","agroexportadora","agroindustria","agroindustriales","agropecuarias","agudizado","agudizados","ahorra","ajeno","alarmante","alcaldes","alcanzaba","alcanzan","alcanzando","alejados","alejar","alentadoras","alentamos","alentando","alertas","aliado","aliento","alimentan","alimentarias","alimentario","alimenten","alineadas","alinear","alivio","alterar","altoandinas","altoandinos","ambiguo","ambo","amigables","amigos","ampliaciones","ampliadas","ampliado","ampliados","ampliarse","ana","analfabetismo","analizar","ancestros","anclada","anclado","and","andenes","andes","anhelo","ansiada","antenas","anticonceptivos","antigua","antiguas","anuncia","aparatos","apci","aplicarse","aplicativos","aplique","apn","apoya","apoyaron","aprecia","aprende","aprendemos","aprendiendo","apropiado","aprovechables","aprovechados","aproveche","aprox","aptas","apuntalar","apuntan","arbitrarios","arcas","arduamente","armada","armadores","arraigada","arrastrando","articuladamente","articuladas","ascenso","asegurada","asegurado","aseguramientos","asegurarse","asignaciones","asignando","asimilando","asisten","asistencial","asistentes","asociadas","asolado","asumiendo","asuntos","atacar","atendido","atendiendo","atendieron","atentan","aterrizamos","atienda","atienden","atractiva","atraeremos","atrasadas","atraviesa","aumenta","aumentaremos","aumentos","austria","autoaprendizaje","autoempleados","autoestima","autofinanciados","autoindentifican","autoritarias","autosostenibles","autosuficientes","aval","avanza","avanzando","ayude","bachillerato","bailarines","bancada","bancaria","bancarias","bancario","baratas","baratos","barril","basura","beneficiando","beneficiaria","beneficie","beneficiosa","biblioteca","bicicleta","billetera","bimodal","binacional","binomio","biodiversos","blanco","bm","boleta","bonificaciones","braille","brevedad","brindarle","brindarles","brindarnos","brotes","bruscamente","bullying","buques","bus","bye","cabalidad","caballa","cabecera","caen","calcular","california","calle","cama","cambiando","caminado","campea","campesino","campos","canal","canalice","canalizando","canatur","canta","cantidades","capacitacion","capacitadas","capacitadoras","capturado","capturar","carcelario","cardiovasculares","carecemos","carecer","carente","carentes","casilla","catastrales","causada","causados","ccl","celebrar","celular","cemento","censura","centennials","centra","centrada","centralizadamente","centralizado","centralizar","cercos","cerradas","cerrado","certeza","cf","chacra","chalecos","chapter","chileno","chimbote","chino","ciberdefensa","ciclos","ciegos","ciertamente","circunstancia","citados","cite","cities","clamorosa","claridad","clasificar","cliente","club","cluster","coadyuven","cobra","cobradas","cobran","cocinas","cocineros","codo","colaborando","colaborar","colaborativa","colectividades","coloca","colocaciones","colocados","coloque","colusiones","combatidos","combinaciones","combinado","combinando","combine","combis","come","cometan","cometer","comida","commerce","compartan","comparte","comparten","compartiendo","compartir","compendio","compensar","compitan","compleja","complejidades","complementan","complementarias","complementario","complementarios","complementarse","complementen","completar","complicada","complicados","comporte","compradores","compuesto","computadora","comunera","comunicado","comunicadores","comunicarnos","concentradas","concentrados","concentran","concentrar","concentrarse","conceptual","concernientes","concertada","concertado","concesionados","concluida","concreta","concretos","condenados","condenamos","condenas","condicen","condicionamiento","conductores","condujo","conexos","confecciones","confidencial","confidencialidad","confirma","conformidad","congresista","congruentes","conjugar","conjuntamente","conoce","conocido","consagrada","consecutivos","consentimiento","conservarla","conservas","considerablemente","considerada","consideran","considerarse","consignar","consistencia","consolidada","consolidado","consolidados","consolidando","constitucion","constituido","constituir","constituirse","constituyendo","constructiva","constructivo","construida","construiremos","construyan","consular","consultoras","consultorio","consume","consumismo","contabilidad","contempladas","contemplado","contemplados","continuara","contrapelo","contraproducentes","contraste","controlada","controversias","contundente","convencido","convencional","convenciones","conversen","convertirla","convertirlas","convierten","convocada","convocatoria","coopac","cooperativismo","coordina","coordinadas","corporativas","correlato","correspondan","corrupcion","cosedena","costeros","costoso","cov","crearse","crecen","crecientes","credito","credo","cree","creyendo","crianza","criminalizan","cruda","cruzado","cualidades","cualquiera","cuantitativa","cuantitativo","cuartel","cuarto","cuasi","cubran","cubre","cuello","cuestionar","culminada","culpabilidad","cultivar","cultores","cumplida","cupos","curativo","curiosidad","curricula","cusco","cuzco","danza","danzas","david","debacle","debatidos","debieran","debilitada","debilitan","decenios","decidan","decidir","decido","decimos","decrecimiento","decretos","dedicada","deducibles","deducir","deficiencia","defiende","definido","definidos","definimos","deforestadas","deforestan","dejadas","dejado","dejaron","deje","delictivos","delimite","delineando","delinquido","delinquir","denegada","denominada","denominadas","denunciados","denuncian","denunciar","denuncien","dependen","dependiendo","depositen","depredadores","derivadas","derivado","derivarse","deriven","derrotero","desactualizado","desaparecer","desaparezca","desaprovechamiento","desarrolladores","desarticulado","desarticular","desbordados","descansa","descargas","descarrillarse","descentralizar","descentralizaremos","desconocen","desconocimiento","describen","descritas","descubierto","descuidado","deseado","desembarcaderos","designar","desincentive","deslizamientos","desnaturalizado","desnudado","destacados","destacando","destacar","desterrando","destinada","destinar","destruido","destruir","desuso","desventajosa","desvirtuado","desvirtuando","detectando","detecte","deteriorado","determinada","deudores","develado","devenido","diariamente","diario","dictar","dicten","dietas","diferenciados","dificultad","difundidas","difundir","digitalizada","digitalizarnos","dini","diroes","discapacidades","discriminatorio","discurso","disfrute","disminuido","dispersos","dispone","disponga","dispuestas","dispuesto","disputas","distinto","distorsiones","distribuidos","distribuir","distribuyen","diversifica","diversificado","diversificando","dividendo","dividida","doblegado","doce","doctores","doctrinales","doing","dolor","dolorosa","domiciliados","domiciliarias","domicilio","domicilios","dominante","donantes","dotaremos","droga","drugs","dss","du","duales","dumping","duplicidades","durables","duradera","duras","ebr","ebt","economia","economistas","edificios","educador","educando","efectivizar","efectuar","egresan","eia","eib","eirl","ejecutados","ejecutor","ejecutores","ejercen","ejercicios","ejerzan","elaborada","elaboran","elabore","electromovilidad","elementales","elevadas","eleven","elusivos","embarazadas","embargos","emergentes","emigrar","emisor","emocionales","empaques","empezando","empiezan","emplea","empleando","empoderados","emprendedora","encadenamientos","encapsular","encareciendo","encarecimiento","encargo","encargue","encontrado","encuentro","endeudarse","endo","enferman","enfocaremos","enfrentado","enfrentamiento","enfrentarlo","enlace","enlazamiento","enmarcada","entendimientos","entero","entregables","entregadas","entrevistas","envases","epidemia","equilibrada","equipado","equitativo","eriazas","eriazos","erradicando","error","erupciones","escalable","escalables","escaleras","escritores","escultura","esencialmente","espacial","especialidad","especializa","especie","espectro","esperados","esperamos","esperan","esposo","estables","estacionalidad","estadios","estancada","estancamiento","estandarizaremos","estatista","estigma","estimamos","estimulan","estimular","estimularemos","estimulen","estirando","estrategas","estrato","estrecho","estrictos","estudia","etnia","eu","europa","evaluaciones","evaluaremos","eventual","eventualmente","evidencias","evitan","evitarlo","evolucionado","excedan","exceden","excedentes","excepcionales","excepcionalidad","excepcionalmente","excepciones","excesivamente","excesivos","excesos","excluida","exenciones","exhaustiva","existido","exitoso","expande","experto","explicar","exploratorios","explotar","exponencial","exportadoras","expresado","expuestas","extensa","externalidades","extractiva","extranjeras","extraordinario","fab","fabricante","facilita","facilitando","factura","falencias","fallidas","faltantes","faltas","fame","farmacia","fatalidad","favoreciendo","favorezca","ferias","ferrocarriles","ferroviaria","ferry","ff","fianzas","ficta","fiel","fiestas","figuras","fijar","fijo","financia","financiada","financiadoras","financiados","financian","financie","fintech","firmas","firmemente","fiscalizadas","flagrantes","flexible","flora","focalizada","focalizado","fomente","food","forjaremos","formacion","formalizada","formalizador","forman","forme","formulado","fortalecerse","fortalezas","fortalezcan","fortunas","francisco","franquicias","fraudulenta","frecuentes","frentes","fresco","frescos","friaje","fronteriza","fronterizos","fruto","funcionado","funcionar","funcionen","fundamentada","fusionando","gago","gales","ganados","garras","gastar","generacional","generalizar","genuina","genuino","geotermia","gerenciales","gerente","gestionarse","gestores","giratorias","giro","glaciares","globalizada","globalizado","gnv","gobernando","gobernante","government","goza","grade","gradual","grids","grilletes","grito","guardianes","guiadas","guiar","habilidad","habilitaciones","habitabilidad","habitacional","hacerlas","hacerle","hambruna","hazte","heterogeneidad","hielo","hipotecar","hipotecario","holding","homenaje","honradez","horacio","horizontalidad","huancavelica","huella","humanista","humay","iafa","ideales","identificada","identifican","ignorando","igualar","iirsa","ilegalidad","iliquidez","imagina","imaginario","impartiendo","impedido","imperativo","imperio","imperium","impida","implacable","implantar","implantaremos","implementarse","implementen","implicadas","implican","implicar","impongan","impositivo","improvisado","impulsada","impulsadas","impulsadores","impulsaron","impulsora","inaceptable","inadecuadas","inadecuado","incentivados","incentiven","inciden","incierto","incluyentes","incompleto","inconclusa","inconclusas","inconsistencia","incorporado","incorporados","incrementadas","incrementados","incrementales","incrementen","incubadoras","incumplimiento","incurridos","indebidamente","indesligables","indice","indirectamente","indolencia","industrializar","ineficaz","inequitativas","inevitable","infantiles","infohospitales","informadas","infractores","ingresado","ingresantes","ingresar","inhabilitados","inhibe","iniciales","inicialmente","iniciando","inicie","inmediatamente","inmediatez","inmensas","inmenso","inmigrantes","inmobiliaria","inmobiliario","inmovilismo","innecesariamente","innecesarias","innecesario","innegable","innove","inocuidad","inquietante","insalvable","insatisfechas","inscribir","inscritos","insignificantes","insolvencia","inspirados","instaladas","instalando","instaurar","institucionalizado","institucionalizando","insultan","integrador","integralidad","integrarse","intensa","intensas","intensiva","interactivo","interconectadas","interesados","intergeneracional","intergubernamentales","interinstitucionales","internaciones","interpersonal","interprovincial","interrelaciones","interrupciones","intervenidos","intervienen","intrascendentes","introduciremos","invalidez","invasiones","inversa","inversores","investidura","investigadora","investigativas","inviable","inviertan","invierten","invisibles","involucra","involucramiento","involucran","involucraremos","involucren","inyectar","irracional","irse","itinerantes","ius","jefas","join","jorge","jurel","justificar","juzgado","juzgamiento","laboran","laboratorio","labs","lagunas","laicidad","lanzar","larga","lazos","leche","legislacion","legislativas","legislativos","lentos","lesivas","letal","letales","levantar","lgbtiq","liberar","libremente","liceos","licitado","licitar","ligeros","limbo","limitadas","limitados","limitan","limpios","listado","listas","listos","lit","litigantes","living","llamadas","llamarse","llegamos","llegaron","llenar","llenen","llevaba","llevada","llevados","llevarse","loayza","localizados","lograda","lomas","lujo","luxemburgo","macchu","machista","macrorregional","madura","mafiosos","maker","malas","males","management","manda","mando","mandos","manejando","mantenemos","mantengan","marcado","marcas","margen","marino","marinos","marshall","marta","masificar","masificaremos","masivos","maternidad","maximicen","maximizaremos","mcvs","mecanizados","medicinal","medicinales","medidor","medioambiental","mejoradas","mencionadas","mencionar","menoscabar","mentes","mera","mercantilista","meros","metropolitanos","microbuses","microempresa","microfinanciamiento","microseguros","milenarias","milenario","millas","millenials","minem","minfra","minimizaremos","ministerial","minka","mitades","mite","mixtas","modernizaremos","modificada","mof","momentos","monetarios","monitoreado","monitoreados","monopolizadoras","monumentales","moquegua","moratorio","mostrando","motivada","motivados","movilizador","movilizar","movimiento","muelle","muertos","multideportivos","multifuncional","multimodales","multipilar","multiplicidad","muros","mutua","mutuo","nace","nacido","nacidos","nacionalidades","naranja","naturista","nauta","navegables","negativas","negativo","negligencia","negociables","neta","netamente","niega","noches","nocivas","nodos","nombrar","non","nor","notable","notablemente","notebook","noticia","noticias","notificado","notorio","noventa","nspp","nulo","nutricionales","obesidad","obligando","observa","observar","obsoletos","obtenga","ocasionado","ocasionando","ocasiones","octubre","ocupa","ocurran","ocurrir","oea","ofrecer","ofrecerles","oligopolio","ollachea","olvidar","onerosa","onerosas","oportunamente","oportunas","oportunos","ops","optar","optativa","optimizando","ordenadamente","organice","organiza","organizan","organizando","organizativas","originado","originaria","originarias","osiptel","ositran","ot","otorgados","otorguen","pagada","paguen","paisaje","paisajes","palabra","pallasca","palma","palomino","paraderos","parapanamericanos","parar","paras","paridad","participe","partida","partidaria","partidarios","partiendo","pase","pasivas","pat","patria","patrias","paulatinamente","pauta","pca","peligros","pen","penalidades","penitenciario","penitenciarios","pensamos","pensionaria","pensionarios","perciben","percibir","perdida","perentorio","periodicidad","permanece","permanecen","permanentemente","permiso","permitidas","perseguir","persiste","persistente","personalizado","perspectivas","perversos","pesa","petrolera","petroleros","pib","pie","pierdan","pierden","pim","pisa","pj","plagas","plana","planificadas","planificado","planificador","planta","planteamientos","plata","pluralista","pluricultural","pluvial","pnud","poblacion","poderoso","ponerse","populismo","portuarias","porvenir","posgrados","posibilitan","posibiliten","positivamente","positivas","postor","postulantes","postura","potenciales","potenciamiento","potencias","potente","potestad","pozos","ppedc","ppss","practica","precipitadamente","precisamente","preciso","predecible","predecir","predictivos","predomine","preferencias","pregunta","preliminar","premiando","premie","preocupan","prepara","preparada","preparados","prepararse","preponderante","prerrogativa","presenciales","presenciando","presentadas","presentando","presentarle","prestados","prestan","prestatarios","prestigio","presupone","prevalencia","previniendo","prevista","pricos","primar","primordiales","priorizaciones","priorizada","priorizadas","proactividad","proactivo","probidad","procedimiento","procompite","producidas","profesionalizada","profesionalmente","programaticos","prohibir","prologo","prolongada","promocionando","promotora","promovemos","promovida","promovidos","pronabec","pronta","propenso","propicien","proporcionalmente","prospectivo","protagonista","protegemos","proveedoras","proveniente","provenir","provienen","provisionar","provocada","proyecta","proyectando","proyectarse","pte","publicado","publicados","publicar","pudiera","pudieran","puso","qua","quedarse","quejas","quemar","quiebra","quiebren","quiera","quieran","quiero","quinto","radica","rama","ramal","rasgo","ratificar","razonar","realizados","realizaremos","rebagliati","recaudados","recaudatoria","receptiva","rechazando","rechazar","recibida","recibieron","reciente","reclamaciones","reclamo","reclusos","recobrar","recogiendo","recojo","recomienda","reconocido","reconozca","recreativos","recuperan","recuperarlos","recuperativa","recurrentes","rednace","reduce","reducen","reduzcan","reemplazado","reenfocar","referencial","referentes","referidos","referir","reflejaba","reflejado","reflejados","refleje","reforestando","reforzada","reforzadas","reforzado","registrada","regla","reglamentaria","reglamentario","regresivo","regreso","regula","reguladas","regulador","regulando","regulares","regularizar","regulatorias","regule","reiniciar","reintegro","reiterativas","relacionado","relativa","relativas","religiosas","remoto","rendimos","renegociado","renovada","rentabilidades","reordenar","reorganizado","reorganizados","reorganizan","reorientar","repensar","replantearemos","reportados","reportar","repotenciaremos","repotencie","represas","representen","reproduciendo","reproductivas","reproductivos","republica","requerir","rer","rescatando","resguardando","resolutiva","resolviendo","respaldadas","respecta","respectivo","respetuosa","respetuosos","respiradores","restante","restauradas","restaurando","restos","restringido","restringir","resultante","resultar","retardarse","retener","retenidos","retomar","retomaremos","retome","retrasa","retrasos","retroceder","retrovirales","revisados","revisando","revolvente","riberas","rica","rigurosa","rinden","riquezas","rmv","road","robusta","rodean","rosa","rostro","sabiendas","sabiendo","sabogal","sagrado","saj","salas","salido","salinice","saltos","salubridad","salvaje","sancionadas","sancionador","sancionadores","saneados","sanidad","sanidades","santiago","saque","sba","scale","secos","secuelas","secuestro","secundarias","seguiremos","seman","semipresenciales","sencillo","sentando","sentenciados","sentimiento","separando","seriamente","serlo","serume","serums","servido","servidumbre","setenta","severidad","sexta","shell","shows","sientan","sienten","siga","sigan","sigersol","siglos","silencio","silvestres","sima","simplemente","simplicidad","simplificado","sinacyt","sinceraremos","sindicales","sine","sinergia","singular","sirva","sistematizaremos","snig","sobrevivir","solares","solidariamente","solidarios","solucionaremos","someter","soportes","sorpresa","sospechosos","statu","suat","subdesarrollada","submarina","subregional","subsidiados","subsidiaria","subsidiaridad","subsidiarios","subvenciones","subversivas","suceso","suficiencia","sufran","sufre","sufriendo","sugiere","suiza","sumamente","sumatoria","sumen","suministren","suministro","supeditado","superarnos","superficial","superfluo","supervisadas","supervivencia","suplementos","suplir","suponer","suprema","sustantiva","sustentadas","sustituir","tabletas","talara","talla","tangibles","tanques","taxis","teatro","tech","techos","teletrabajo","temporalmente","tempranas","tenerse","terapias","tercio","terminal","terna","terrestres","territorialidades","terrorista","tesis","testimonios","textil","tingo","tm","tomado","tomamos","tomarse","tome","toneladas","top","totales","tr","trabajado","trabajadoras","trabaje","trabajen","traducido","tradujo","traer","transable","transectorial","transferido","transferidos","transformados","transformando","transitabilidad","transitan","transmitir","trascendental","trasladando","trasladarse","traslados","tratado","trayectos","trenes","triangular","tributo","trimestrales","trinomio","triplicando","truck","tuesta","tumbes","turnos","ubicadas","unido","unifica","unificada","uniformizar","unilateral","unimos","unish","up","upstream","urbanizados","urgencias","usado","usados","usen","utilidad","utilizada","utilizadas","utilizarla","vab","vacantes","vale","valle","valora","valorada","valorar","variable","variedades","ve","vejez","velar","venideras","venir","ventanillas","veracidad","veredas","vertebral","verticales","verticalmente","vertientes","vertimientos","via","viaje","viales","viceministerios","victima","videna","vientre","vigilado","vigilante","vigilar","vii","vinculada","vinculado","vincularse","vino","violenta","virreinales","vision","visiones","vislumbrar","vitales","vitalicias","vivas","vivencial","vivenciales","vivido","vizcarra","vocacional","vocacionales","volumen","voluntarios","votar","vulnerados","vulneran","wasi","wawa","whistleblower","workings","xenofobia","yurimaguas","zanjar","zonales","zoofilia","abancay","abandonados","abandonando","abandonen","abaratar","abarca","abarcando","abastecera","abatir","abdominal","abiertamente","abismales","aboga","abogamos","abogaremos","abonos","abordada","abordamos","abordan","abordaremos","aborde","abra","abre","abriendo","abrigo","abrupto","absoluto","absorba","abstiene","abstractos","absurdo","abundante","abusa","abusan","abusen","abusivas","ac","acaecidos","acaparamiento","acatando","accedente","accedidos","accesoria","accesorio","accidentabilidad","accionarados","accionaria","accionariado","accionarios","acciopopulistas","acecho","aceitera","acelera","aceleradamente","aceleradoras","aceleran","acelere","acentuando","acepta","aceptable","aceptamos","aceptan","acercarse","acerquen","acertado","acidez","aclarar","aclararemos","acoge","acogedores","acogida","acogido","acogiendo","acogieron","acojan","acometer","acongojado","acordadas","acordado","acosadas","acosen","acoso","acostumbrada","acotado","acrecentado","acrecentar","acredite","acreedor","acta","actas","actitud","activistas","actuaciones","actuados","actualizada","actualizando","actualizarse","actuando","acudan","acumulando","acusatorio","adapta","adaptable","adaptado","adaptativa","adaptemos","adecuarlas","adelantan","adelantar","adelantarse","adelantos","adentro","adherimos","adiestramiento","adjudicadas","adjudicar","adjudicatarios","administradas","administradores","administran","admirada","admiramos","admiten","admitidos","adoptada","adoptan","adopten","adquieren","adquiridas","adquiridos","adquirientes","adquisicion","adquisitiva","adquisitivo","adscrito","aduaneros","aduce","adultas","adversa","adversarios","adversidad","advertencia","advertido","advertir","adyacentes","aeroportuaria","aeropuerto","afectiva","afectivas","afectividad","afectivo","afianzando","afilia","afiliada","afincadas","afincado","afirma","afirmaciones","afirman","afirmando","afligidas","aforos","afrontarla","afuera","agarra","agenciarse","agil","agilizadores","aglomeration","agobia","agobiados","agota","agradecerles","agradecimiento","agravar","agregando","agregar","agresivos","agri","agricultor","agroexportaciones","agroexportadoras","agroideas","agropecuario","agrotech","agrupados","agrupe","aguantar","agudizando","ahondada","ahondando","ahondar","aimara","aires","aislada","aislados","aislar","ajena","ajenas","ajustados","ajustarse","ajusten","alargar","albergamos","albergar","albergues","alcabala","alcabalas","alcalde","alcaldesa","alcaldesas","alcaldias","alcaloide","alcanzada","alcanzamos","alcanzarse","alcohol","alcoholismo","aleatoria","aleja","alejada","alejado","alejando","alejaremos","alejarnos","alentaremos","alfredo","alienta","aliente","alimenta","alimentarioa","alimenticio","alimento","alineada","alineando","alinearlas","alinearse","alivios","alma","almacenados","almenara","almuerzos","alojarse","altera","alternas","altitud","altura","alude","aludida","alumbrado","alza","amarillo","amas","ambiciosos","ambiguos","ambulantes","amenace","amenazado","amenazados","amenazan","americana","amigo","amor","amortiguador","amortiguar","ampara","amparada","amparos","ampliamente","ampliarlas","ampliarlo","amplias","amplifica","amplifican","analicen","analiza","analizando","ancash","ancestralmente","ancho","anchovetas","ancianos","anclaje","anclaremos","anda","angulares","anhelamos","anhelan","anillo","anita","anonimato","anorexia","anos","anotaciones","anotar","anps","antepasados","anteproyecto","anticipando","anticompetitivas","anticonceptivas","anticuada","antidrogas","antimonopolios","antinarcoticos","antis","antisocial","anunciado","anuncian","aoe","apalancamiento","apara","aparecen","aparejado","apartados","apec","apelado","apellidos","aplanar","aplausos","aplicabilidad","aplicante","aplicaremos","aportaban","aportaciones","aportando","aportante","apostaremos","apoyado","apoyados","apoyarse","apoye","apoyen","apreciablemente","aprecio","apremiantes","aprenderse","aprobaciones","aprobaron","apropia","apropiabilidad","apropiacion","apropiadamente","apropiados","apropian","aprovechable","aprovechada","aprovechadas","aprovechen","aproximada","aptos","apuntalando","ar","ara","arado","aranceles","arbitrajes","arbitrales","arbitraria","arbitrariedad","archivos","argollas","argumentan","argumento","aristas","arma","armado","armador","armados","armamento","armonice","armonicen","armoniosas","armonizan","armonizar","arquero","arquitectura","arraigo","arrancar","arrastra","arrastre","arreglarse","arrestos","arroja","arroyos","arroz","artemio","artera","artesano","articulaciones","articulan","artista","asalto","ascendente","ascender","ascensores","asentada","asentadas","asentarse","aseo","asequibilidad","aserrada","asesinato","asesinatos","asesorando","asesorar","asesore","asesores","asfixiante","asia","asigando","asigna","asignada","asignar","asignaremos","asignarle","asigne","asignen","asimetria","asista","asiste","asistenciales","asistencialista","asistenta","asociando","asociativas","asocien","aspiramos","aspirantes","aspiren","astas","asumido","asunto","ata","ataca","atacados","atacan","atacaremos","atalaya","atenderemos","atenta","atenuar","atiendan","atiende","atisbo","atractivas","atrae","atraen","atrapado","atrapados","atrasados","atravesar","atribuidas","atributos","atropella","audiencia","audio","auditiva","auge","aula","aulas","aumentado","aumentarlo","aunado","aunados","ausentarse","ausente","ausentes","auspicien","auspicio","austera","autentica","autocuidado","autoemplea","autoempleado","autofinanciadas","autogobierno","autogravado","autogravamenes","autogravar","automatizadas","automatizando","autor","autores","autoritario","autoriza","autorizadas","autorizando","autorizar","autosuficiente","auxiliar","auxiliares","avalada","avales","avanzado","avejentadas","aventura","aventuras","aventureros","avistamiento","awajun","ayacucho","ayni","ayudado","azangaro","azotar","azufre","bachiller","bajaba","bajen","balanceada","ballenas","bancarrota","bandas","barbados","barbecho","barrera","barriales","basara","basica","baste","batallando","baten","baterias","bebidas","bellavista","beneficiada","benefician","beneficiarias","beneficiario","beneficiaron","beneficiaros","beneficiarse","benigna","bfh","bi","bicameralidad","bienal","bienvenida","bilaterales","bimestrales","biocidas","biocomercio","blandos","blanqueo","blindada","bloque","bloquear","bloqueo","bloques","bluetooth","bodegas","boliviano","bolsa","bomberos","bondades","boom","boquichico","borde","borrados","bosta","botaderos","botadores","botellas","botes","bpp","brazo","brazos","break","bridgetown","brigadas","brindado","brindados","brindaremos","brote","brs","brt","brutal","buffer","building","bum","buque","burlados","burocratico","burocratizado","buscaba","buscarse","busquen","butantan","cabalmente","cabana","cabecillas","cabeza","cabida","cabotaje","cacao","caciquistas","cadaa","caducado","cae","caer","caida","caiga","caigan","calcen","calcula","calculada","calculado","calemar","calendario","calidez","califica","call","callejera","callejero","callejeros","calza","camara","cambiamos","cambiantes","caminables","caminen","campesina","campesinos","can","canalizados","canastas","cancelar","cancelatorio","canchaque","canchas","candidato","cansada","canteras","cantuarias","capilares","capilla","capitalistas","capitalizadas","capitalizando","capitanear","caprichosas","captados","capturados","capturas","car","carabaya","caracterizan","caracterizaron","caras","carcome","carcomido","cargar","caribe","caritas","caro","carpetas","carretero","carreteros","cars","cascas","casera","casma","casonas","castigan","castigue","catastral","caucho","caudal","caudillista","causan","causante","causantes","causen","cautela","cautelando","ccr","cedaw","celebraciones","celebradas","cementeras","cementerios","cenas","cenepred","censal","censos","centenares","centradas","centralice","centralidades","centraliza","centralizador","centralizando","centralizarlas","centralizarse","centran","centrando","centrase","centre","ceorg","cepas","cerebrales","cerebro","cerrada","cerrados","cerrando","cerremos","cerros","certificado","certificas","certifiquen","cerveceras","cesantes","cesar","cese","cetpros","cgr","chatarrear","checca","chicama","chiple","chips","chiquintirca","choferes","choque","chuco","chuquicara","ciber","ciberataques","cierran","cimentada","cimentar","cincuenta","cineteca","cinturones","circo","circulo","circunscrita","circunscrito","cisterna","cisternas","cita","citaciones","citado","civilidad","civilizaciones","civilizatorio","clamor","clarificando","clasificados","clasificando","cleptocracia","click","clientelaje","clientelares","climatico","cmp","coacta","coadministrados","coadyuvan","coadyuvando","coadyuvar","coalaque","coar","coasters","coautores","coaxial","cobijar","cobradores","cobrar","cochabamba","cocina","codisec","coercitivo","cofinanciadas","cofinanciar","cognitiva","cohabitan","coherentemente","cohesionado","coincide","coinciden","cola","colaboracion","colaboradores","colabore","colaboren","colabores","colapsadas","colapsados","colaterales","colecciones","colegas","colegiada","colegiados","colindantes","coliseo","coliseos","colisionar","collao","colmarlos","colocar","colonos","color","colude","comandadas","combaten","combatimos","combatirlo","combinarse","comenzaron","comer","comercializados","comerciantes","comercios","cometida","cometidos","comex","comience","comision","commodities","companero","compara","comparable","comparativas","compatencias","compatibilice","compatibilidad","compatibles","compensaciones","compensada","compensatorias","compense","compensen","compete","competidores","competidos","competitivamente","competividad","compitiendo","complace","complejas","complejizado","complementando","complementaremos","complementariedad","complemente","completado","completas","completen","complicaciones","complicado","complican","complique","comportamientos","comprador","compran","comprarle","comprenda","comprenden","comprendida","comprendiendo","comprobada","comprobadamente","comprobado","comprobar","comprometa","comprometen","comprometeremos","comprometerse","comprometida","compuesta","compuestos","computacional","computarizar","comunero","comunicacionales","comunistas","concatenados","concebido","concebimos","concentre","concertadamente","concertados","concertar","conchas","concibamos","conciliatoria","concluidos","concluyen","concretando","concretaron","concuerdan","concurrencial","concurrentes","concursales","concursar","condiciona","condicionada","condicionado","condicionados","condicionan","condicionantes","condicionar","condones","conducido","conducir","conductor","conductora","conduzca","conecta","conectada","conectan","conectarse","conecten","conei","coneis","conexa","confabularon","confesiones","confiabilidad","confiamos","confiar","confiep","confinamientos","confirmar","confirmatoria","confluencia","confluyan","conforma","conformada","conformadas","confortable","confrontaciones","confusa","confusas","confusos","congelada","congeladores","congelados","congestionados","congresal","conida","conjuga","conlleva","conllevando","conocemos","conocen","conocida","conococha","conozca","conozcamos","consecuentemente","conseguidos","consensuar","conservacionistas","conservadora","conservarlos","conservemos","conserven","conservera","consideraba","consideraciones","consideren","consiga","consigan","consigna","consignadas","consignados","consolidan","consolidaremos","consolidarse","consoliden","consonancia","consorciados","conspiraciones","constantemente","constantes","constata","consternados","constitucionalistas","constituida","constitutivos","constituya","constributivo","constructivos","constructor","constructoras","construdios","construido","construyamos","construye","construyeron","consulares","consultar","consultivo","consumiendo","consumimos","consumir","consustancial","contaban","contabilizadas","contado","contagiada","contagiados","contemplada","contemplar","contenga","conteniendo","contextualizar","contiene","contienen","continental","continente","contingencias","contingente","continuamente","continuaron","contracara","contractuales","contradicciones","contradicen","contradictorias","contrajo","contramarchas","contraparte","contrapeso","contrapesos","contraproducente","contrariamente","contrarrestarlos","contratadas","contratado","contratantes","contratarse","contraten","contratistas","contravenciones","contribuiremos","contributivo","controla","controladas","controlando","controlaremos","controle","contugas","contundentemente","convalidado","convenidos","conveniente","converja","conversar","convertible","convertidas","convertidos","convertirlos","convicciones","convirtieron","conviven","conviviendo","convocadas","convocando","convocatorias","convoquen","coolers","coopacs","cooperacion","cooperar","cooperativa","cooperativistas","cooptado","coordenadas","coordinaciones","coordinadamente","coordinado","coordinador","coordinadores","coordinen","cop","copale","copales","copare","copares","copiosa","coresec","corner","corporaciones","corporal","corporativa","corporativos","corregirla","correspondencia","correspondiendo","corresponsabilidad","corrigiendo","corrija","corroborar","corruptas","corta","cortapisa","cortaremos","cortas","cortoplacista","cosechar","cosmovisiones","costado","costas","coste","costeo","costero","costosas","costosos","costumbre","cotidianos","coworking","coworkings","cpp","cptpp","cras","creadas","creativo","creciera","crediticias","creen","creencias","crezca","crezcan","criar","critica","cronograma","cruceros","cruces","cruciales","cruz","csmc","cts","cuadro","cualitativa","cualitativos","cuantitativos","cuba","cubiertas","cubriendo","cubriremos","cuero","cuerpos","cuestionado","cuida","cuidadoras","cuidadores","cuidadosamente","cuidan","cuidaremos","culinarias","cultiva","cultivable","cultivada","cultivares","culto","culturalmente","cumplieran","cumplieron","cunas","curioso","curriculas","curvas","custodio","cutervo","cuy","damos","dance","darles","dato","dd","ddhh","dea","debatir","debidas","decano","decencia","decisivas","decisivo","decisoria","declaradas","declarados","declaran","declarando","declarare","declararemos","declararse","declaratorias","declare","declaren","declinando","decomiso","decreciendo","decretado","decuplicar","dedican","dediquen","dedsarrolla","deducible","defecto","defectuosa","defenderemos","defendiendo","defensora","deficit","defienda","defienden","definiciones","definiendo","definiremos","definitivo","definitivos","deforestados","defraudar","degenerativa","degradados","degradan","degradar","dejados","delate","delega","deliberaciones","deliberativo","delictivo","delimitaciones","delincuenciales","delincuente","demandados","demandamos","demandantes","demandar","demande","demoraba","demorada","demoras","demostrar","demostrativo","demostrativos","demuestre","denegado","denegatoria","denigra","denominacion","densidades","denunciantes","dependencias","depositado","depreda","depredar","depresivo","deprimidas","derivarlo","derogar","derrochador","derrotamos","derrumbes","des","desacertadas","desactivando","desactualizada","desactualizados","desaduanaje","desafiantes","desagregados","desague","desalentador","desalentaremos","desalienta","desalojados","desamparo","desaparece","desaparecen","desaprovecha","desaprovechado","desaprovechamos","desarraigo","desarrollada","desarrolladora","desarrolladoras","desarrollamos","desarrrollar","desarticulaciones","desarticuladas","desastrosa","desastrosamente","desatender","desbocado","desbordado","desbordan","desbordes","descalabro","descargadas","descarte","descensos","descentralice","descentralizando","desciende","descollado","descolmataremos","descolonizador","desconcentradas","desconcentrados","desconcentrando","desconcentrar","desconfianza","desconocidas","descontrolada","describiendo","describimos","descrita","descubrimiento","descubrimos","descuidar","descuido","desea","deseable","desechar","desee","desembalsado","desembocado","desembolso","desempleado","desempleados","desenvolverse","desenvuelve","deseo","desequibrio","desequilibrado","desesperanza","desfasadas","desfasado","desfase","desfavorecidas","desfigurado","desidia","designaremos","desincentivo","desinfectadas","desligadas","desligando","desmacchupicchar","desmantelado","desmedidamente","desmedido","desmesurado","desmitificando","desmoralizarla","desmoronan","desmotiva","desnudar","desnudaron","desnutrida","desnutridos","despacho","despegar","desperdicio","desperdigados","despiden","despilfarrando","desplazada","desplazamiento","desplazamientos","desplazarnos","desplegada","desplegar","desplegaremos","desplieguen","despojado","despojo","despotismo","desprecio","desprende","desprenden","desprestigio","desproporcionadas","desproporcionalmente","desproteger","desprotegido","destacable","destacaron","destapando","desterrado","destina","destinan","destinaremos","destinos","destrabados","destrabar","destrabaremos","destrezas","destructivo","destruirlos","destruya","destruyendo","destugurizar","desvalorando","desventajas","desventajosamente","desviado","desvincularse","desvincule","detalla","detalladamente","detallado","detalles","detectamos","detectives","detenciones","detener","detenidas","detenido","detenidos","deteriorada","deterioradas","deteriorarse","determinados","determinando","determinaremos","determine","determinen","detiene","detracciones","detrimento","detuvieron","deudor","devaluadas","devastadores","develada","devengados","devengaron","devida","deviene","devoluciones","devolveremos","devolviendo","devuelto","devuelvan","devuelve","diabetes","diagnosticado","diagnostico","dial","dialogan","dialogando","dialogante","dialogo","dialoguen","diariamiente","dicapi","dictadura","dictamine","dictaremos","diesel","dieta","diferenciada","diferenciado","diferenciador","diferenciar","diferendos","dificulte","difiere","difundida","difundiendo","difusos","digamos","digitalizan","digitalizando","digitalizar","dignamente","dignificada","dignificar","dilatados","dilatando","diligente","dimension","diminutas","dinamice","dinamicen","dinamiza","dinanciero","dios","diputados","direccionalidad","diresas","dirigiendo","dirigirnos","dirija","dirijan","discapacitados","disciplinarias","disciplinario","discos","discrecional","disculpa","disculpas","discursivas","discusiones","discutidas","discutido","disfruta","disfrutado","disfuncional","disfuncionales","disfuncionalidades","disminuida","disminuye","disminuyen","disminuyendo","disminuyeron","disparado","dispersas","disponen","disponiendo","disposiciones","disputaron","disrupciones","distan","distancias","distante","distinciones","distinga","distorsionado","distorsionan","distribuidas","distribuidor","distribuidora","distributivo","disuelto","disyuntiva","diversificadas","dividir","dividirnos","divisas","divisiones","divorcio","do","doblegados","doctor","doctrinario","documentado","documentales","documentario","dolencias","dolores","dolorosamente","doloroso","domiciliariamente","domiciliarios","dominada","dominado","dominantes","domingo","donaciones","dotado","dotados","dotando","dotarla","dotarles","dr","drama","drenaje","drivers","drones","drug","ductos","dudareros","dudas","duopolio","duplican","duplicaremos","duplicarlos","dura","durabilidad","duradero","duraderos","duramente","duran","duren","dureza","ece","ecoeficiencia","ecoeficientes","economicos","economies","edificaciones","edificados","edificatorio","edipymes","educacion","educadoras","educandos","educar","educarse","eejes","eess","ef","efectuadas","eficazmente","eficiencias","egional","egoismo","egresar","egresaron","egresos","ejecuta","ejecutada","ejecutaremos","ejecutarse","ejecutora","ejemplar","ejerce","ejercida","ejerciendo","ejerza","elabora","elaboradas","elaborando","elaborarse","elaboren","electa","electo","elector","electores","electrificado","electrificados","electrificar","elefantes","elegidas","elevan","elige","elija","elijan","elimina","eliminada","eliminados","eliminan","elitista","elitistas","eludido","eludidos","eludir","embajadores","embarque","embate","embellecer","emerge","emerger","emigraron","emitidas","emitidos","emitimos","emocionalmente","empalme","empelo","empeora","empeoramiento","empleada","empleador","empobrecimiento","empoderada","empoderadas","empoderado","emprendedoras","emprendedurismo","emprendidas","emprendido","empresariado","empujando","emulando","emular","enaho","enalteciendo","enamo","enapres","encadenamiento","encaminado","encaminamos","encaramados","encarar","encararemos","encarcelados","encarece","encarecer","encarga","encargarles","encargarse","encargos","encarnaron","encausados","encierro","encontraba","encontraban","encontrarlo","encontrarse","encubiertamente","encubiertas","endeuda","endeudada","endeudado","enemigas","enemigo","enemigos","energias","eneuu","enfatizado","enfatizan","enfatizando","enfatizar","enfermarse","enfermas","enfermera","enfermeras","enfermos","enfocadas","enfocamos","enfocan","enfocar","enforcement","enfrentadas","enfrentamientos","enfrentarla","enfrentarlos","enfrenten","engorrosa","engorrosos","enif","enlazar","enmarcan","enmarcarse","enorgullecen","enquistada","enrevesada","enriquecen","enriquecidos","enriquecimiento","enriquezca","ensancha","ensanchar","ensusalud","entendemos","entenderlas","entenderse","entendible","entendida","entera","enteramente","enteras","entierro","entorpece","entorpecen","entrado","entrecomillado","entregados","entregamos","entregando","entregar","entregas","entrelazarse","entren","entrenada","entrenar","entretenimiento","entrevistados","enumerar","enunciativamente","enviar","envidiarles","envilecida","enviromental","epi","epicentros","episodios","equilibran","equilibrando","equilibrar","equiparado","equiparemos","equitativos","equivalentes","equivocan","erb","errada","erradas","erradicadas","erradicado","escalado","escalonar","escape","escenicas","escindiendo","esclarecer","esclarecimiento","esclavizan","escolaridad","escolarizar","escrita","escrito","escrutadas","escuchado","escuchar","escudo","esferas","esfuercen","esfuerzan","eslabonada","espalda","espaldas","especialicen","especialista","especializan","especializarse","especificaciones","especificar","especificas","especificidad","especifique","espectador","especulativos","espejos","esperando","esperanzas","espina","espinoza","espirituales","esposa","estabilizada","estabilizan","estacional","estacionales","estafa","estamento","estampilla","estancaron","estandares","estandarice","estandarizando","estilos","estimaciones","estimado","estimados","estimando","estimar","estimaron","estimulada","estimulando","estimule","estipula","estipulados","estp","estragos","estrechamente","estrella","estrellado","estrellas","estructuradas","estructurados","estructuralmente","estructurantes","estudiadas","estudiado","estudian","estudiaron","estudie","estudien","etaria","etario","eternas","eucalipto","euro","europeas","europeos","evadir","evaluadas","evaluarde","evaluarse","evangelio","evento","evidenciadas","evidenciados","evidenciamos","evidencian","evidenciar","evidentes","evita","evitamiento","evitamos","evitaremos","evitarse","evolucionando","exacerbada","exactamente","exacto","examen","exclusiva","exclusivas","excluye","excluyentes","excusa","execrables","exhaustivo","exhibido","exigen","exigentes","exigidas","exigir","exigiremos","exigua","exiguas","eximen","existencias","existiendo","existieren","exitosamente","exitosos","exoesqueletos","exonerarse","expandido","expandimos","expansivo","expectativas","expedita","expeditiva","expeditos","expendio","expensas","experimenta","experimentado","experimental","experimentando","explicado","explorar","explosiva","explotando","explote","exponer","exporta","exportemos","exposiciones","expost","expresadas","expresan","expresar","expresas","expropiaciones","expropiado","expuestos","expulsados","extendiendo","extensas","extensiones","extensivos","externalidad","externamente","extiende","extra","extractivo","extrae","extrajudiciales","extraordinarias","extraordinarios","extremadamente","extremistas","fabrican","fabricarse","faciales","facilitarles","faciliten","factibles","facto","factoring","faculta","fala","falaz","falencia","falla","fallan","fallece","fallecen","fallecidas","fallida","fallo","falsos","falte","falto","fantasmales","faro","favorablemente","favorables","favorece","favorecida","favorecido","favorezcan","fe","federal","felices","femenina","femenino","femeninos","feminicidas","feriados","fermentar","feroz","ferrocarril","ferroviarias","ferroviario","ferrys","fertilidad","fertilizantes","fichas","fideicomisos","fiebre","figura","figuraba","fijamos","fijan","filiales","filtraciones","finalizan","finalizar","financiador","financieramente","firmados","firmantes","firmes","fiscalizaciones","fisco","fitel","fith","flagrancia","flamante","flancos","flexi","flores","fluida","fluidamente","fmi","fob","focalizadas","focalizados","focalizar","focalizaremos","focos","fomentada","fomentadas","fomentamos","fomentando","fomentarse","fonam","foncal","fondeo","fondep","fondepes","forjaron","forje","formaciones","formada","formador","formadoras","formadores","formalice","formalizadores","formalizan","formalizaremos","formamos","formando","formulada","formulador","formularse","formulen","foros","forrajeo","forsyth","fort","fortalecere","fortalecernos","fortificados","forzada","forzando","forzar","forzosa","fraccionada","fracturas","fragatas","fragilidad","fragmentados","francas","fraudes","fraudulento","frecuencia","frecuente","frecuentemente","frenada","frenado","frenando","frenar","friajes","frio","frita","frondosa","frontalmente","fronterizas","frustrado","frustrados","frutas","frutos","fuere","funamentales","fundacional","fundaciones","fundadas","fundador","fundamentalismo","fusionan","fusionar","gallos","gamitana","ganaban","ganadera","ganado","ganadora","ganarse","ganas","gangters","garantias","garantizados","garantizan","garantizarlo","garantizarnos","gaseoducto","gaseosas","gasoductos","gasoholes","gastado","gastando","gatillar","gemelo","generacion","generadas","generalizadas","generalizado","generalmente","generara","genero","genuinas","geo","george","gerencial","gerenciamiento","gerencias","germoplasma","gesta","gestante","gestiona","gestionando","gigantesca","gigantesco","gimnasia","giran","girar","gl","globalizar","glucosa","gobernador","gobierne","goce","goles","golpe","golpeada","golpes","govtech","gr","grabar","gracia","graduados","gradualmente","grandeza","granizadas","gratis","gratuidad","gratuitas","gravamen","gravitante","grc","grid","grillete","grises","guarda","guardan","guardia","guayaquil","gusto","haberes","habilita","habilitadas","habilitado","habilitadoras","habilitadores","habilitar","habilitaremos","habilitaron","habita","habitan","habitar","habitual","habladas","hacerles","hacernos","haku","hallazgos","hambrunas","hara","hecha","hechas","heladas","hemisferio","hermoso","hh","hibernar","hidro","hidrogeno","hidroviarias","hidroviario","higares","higuchi","hilo","hipotecarias","hipotecas","hispanoamericana","hombre","hombros","homicidas","homogeneizador","homogeneos","homologado","homologados","homologarse","honesto","hong","honor","honores","honramiento","horario","horizon","horizontalmente","hortelano","hospitalario","hostigamiento","hostilidad","hrt","https","huacaybamba","huacrachuco","huallaga","huallanca","huancayo","huandoval","huaraz","huari","huaura","huaycos","huayllay","hub","huelga","huertos","humanistas","humedales","humillados","huracanados","huyeron","ia","iao","ib","iba","iberoamericana","iberoamericanos","ica","idear","identifica","identificador","identificamos","identificando","identificaremos","ido","iees","iei","ignoran","ignorar","ignoraron","ignore","ilusorio","ilustra","ilustrado","imaginar","imbuida","imbuido","imitar","impactadas","impactando","impactar","impagas","impartan","imparten","impartidas","impartido","impartir","impedimentos","impensadas","impera","imperante","imperativos","imperdonable","impere","imperecedero","imperiosa","implantada","implantando","implementaran","implementarlos","implemente","implementos","implique","imponen","imponente","imponentes","impopularidad","importadores","importados","importan","importe","importemos","imposibilitan","imposible","imposibles","impositiva","impotente","impresa","imprescindibles","imprescriptibles","improcedencias","improvisadas","impuesta","impulkso","impulsarla","impulsarse","impulse","impulsor","impulsores","imputadas","inaccesibles","inaceptables","inafectaciones","inalienables","inambari","inaugurado","inaugurar","inc","inca","incapaces","incapacitantes","incautada","incentiva","incentividando","inciado","incipientes","incluyan","incluyente","incoherente","incompatibilidades","incompletos","inconducta","incongruente","inconstitucional","inconvenientes","incorporada","incorporadas","incorporaremos","incorporarles","incorporarlos","incorporaron","incorporarse","incremental","incrementan","incrementos","incuba","incubadores","incumplidos","incumplimientos","indda","indebida","indebidas","indeci","indefensos","indelegables","indemnidad","indemnizacion","indemnizar","independizar","indeseadas","indeterminado","index","india","indicado","indices","indicios","indiferencia","indiferente","indiferentes","indigencia","indirecto","individualismo","individualizado","individuos","indolente","indolentes","inducida","inducir","indumentaria","industrializados","inefectiva","ineptitud","inequidades","inequitativa","inequitativo","inercia","inescrupulosos","inexacta","inexistentes","inexorable","infames","infarto","infecciosas","infectadas","infectado","inferior","infes","inflacionaria","infligen","influenza","influye","influyente","infocarcel","infocarceles","infoconsultas","infocpvc","infoescuela","infoescuelas","informado","informalmente","informan","informar","informaron","information","informativa","informativas","informen","infosalud","infotrabajo","infracciones","infractoras","infraestrutra","ingemmet","ingenio","ingenua","ingenuo","ingesta","ingles","ingredientes","ingresan","ingresando","ingresaron","ingrese","inhibitorio","inhumano","inia","inicia","iniciados","iniciamos","inician","iniciaron","iniciemos","inicien","injuria","injustamente","injusticias","inmateriales","inmemoriales","inmensos","inmersos","inminente","inmobiliarias","inmundicia","inmunizada","innecesaria","innovaciones","innovadoramente","inocuas","inocuos","inoperativo","inopinadas","inquilinos","insatisfechos","inscribirse","insegura","insertada","insertado","insertando","insertarnos","insertarse","insertarte","insignificante","insitu","insolutos","insostenible","inspecciones","inspirada","inspiradores","inspirar","inspire","inspiren","instalado","instalan","instalaron","instalen","instauradas","instauraron","institucionaliza","institucionalizada","institucionalizados","instituido","instituiremos","instituirse","instructores","instrumentando","insuficiencia","insustituible","intachable","intangibilidad","intangibles","integardo","integra","integradores","integrambiente","integrarlas","integrarlo","intelligence","intemperie","intenciones","intensivistas","intenso","intensos","intentado","intentos","inter","interacciones","interactuante","interactuantes","interamericana","interamericano","intercambiar","intercepte","interconectados","interconectar","interconectarlas","interculturalmente","interdependientes","interdisciplinario","interdistritales","interesan","interesante","interesen","interfederaciones","interferencia","intermedia","intermedios","interminables","intermodal","intermodales","intermodalidad","internalizar","interoperable","interoperables","interoperar","interpretaciones","interpretar","interprovinciales","interregionales","interrelacionada","interrumpiendo","intersectorialmente","intervencionista","interviene","intervinientes","intra","intrafamiliares","intranet","intrapersonal","introduce","intrusivas","invadan","invadirlos","invariables","invenciones","inventariados","inventario","inventos","inversoras","invertiremos","investigado","investigador","investigarlo","investigarse","invetir","inviabilizado","inviolabilidad","invisibilidad","invitando","invocada","involucrarlos","inyectaron","ioarrs","ipe","ips","irradiar","irradie","irrelevante","irremediablemente","irrepetible","irresponsables","irreversibles","irrigaciones","irtp","itinerarios","its","javier","jefatura","jefes","jircan","jobs","jolgorios","jovenes","joyas","juanjui","jugaremos","juliaca","juntamente","jurada","jurado","juridico","jurisdiccional","jurisdiccionales","jus","justamente","justifica","justificaban","justificaciones","justifique","justiprecio","juzgadores","juzgando","juzgar","keiko","kindle","kms","kong","labora","laborar","laboratorial","laboriosidad","lactancia","lacustres","laderas","ladrillo","lagos","lambayeque","lamentable","lands","langostinos","lanzando","lanzarse","laptop","lastimosamente","lat","latam","latinoamericana","latinoamericanas","latinoamericano","latinoamericanos","latitudes","leal","lealtad","leasing","lee","leen","legalidad","legalizar","legar","legislaciones","legislativa","legista","legitimado","legitimar","lema","lenguado","lenguaje","lentamente","lentitud","leoninas","levantado","levantamiento","levante","liberamos","librarse","libras","libreta","licenciadas","licenciamientos","licenciatarios","licitadas","licitados","lidera","lideran","liderando","lideraremos","lidiar","lifelonglearning","limitante","limite","limites","lindo","lineal","lineales","listo","llama","llamada","llamados","llaman","llamar","llamativo","llegaba","llegada","llegaran","llenan","llevaron","lleven","lluvias","lms","locaciones","localizado","localizando","logisticas","logistico","logradas","logrados","lpa","luchan","luminoso","machismo","machistas","macroeconomico","macroregional","macrotendencias","madurez","magisterio","magna","magnitudes","mahal","majora","makers","malecones","malestar","mallado","mallas","malogrados","maltratados","mandarin","mandarlos","manejada","manejadas","manejado","manejaremos","maneras","manifestado","manifestar","manifestarse","manifiestamente","manifiesto","manipular","mantenga","mantenida","mantos","manuel","manufactureras","mapear","maquinaria","marasmo","maravillosa","marcada","marchas","mareomotriz","mareos","marginada","marginados","marginalidad","maricultura","marihuana","marketing","mascarilla","masculinos","mata","matarani","materializada","materializando","materializaran","matizado","matrices","matricula","mayas","mayoritarias","mazan","mazocruz","mclm","mcvsp","mediados","medianos","medicamento","medico","medido","medioambiente","mediocres","medir","medular","megaciudades","mejorada","mejorados","mejoramos","mejorarse","membrete","mencione","mendicidad","menester","menguar","mensaje","mensualmente","mentales","mentira","mentoring","menuda","meollo","merecedora","merecemos","meritoria","meritua","mermado","mers","mestizaje","metabolismo","metro","mexico","mezclas","michael","microfinanzas","micros","midan","mide","miden","midiendo","miedo","miembro","migracion","migraciones","migrando","migrante","migratorios","migren","militancia","militante","milla","millon","millonarias","millonescada","mimpv","mineral","mineroidentificados","minfsa","minicet","minifundios","minimalista","minimizando","minimo","mininter","minipandemias","minjus","minorista","minoristas","minoritario","mirando","mirar","miseria","miterreno","mitigables","mitigado","mitigarlos","mitiguen","mitos","mix","mllns","mnsa","mo","mobiliario","modales","modelada","modeling","moderada","moderados","modernidad","modernizada","modernizadas","modernizadora","modernizando","modificaremos","molestias","molinos","mollebamba","mollebaya","mollepata","moneda","monetarias","monetario","monitorables","monitorea","monitoreadas","monitorean","monitoreando","monitorearemos","monitoree","monitorice","mono","monocultivo","monopolice","monopolio","monroe","montado","montados","monten","montesinos","mora","morados","moralmente","moras","morbilidades","morirse","mortal","mosto","motines","motivando","motorizada","motorizado","motorizados","mototaxis","mover","movilice","movilicen","movilizada","movilizarse","mpc","mttic","mudanza","mudaremos","muestre","multados","multianuales","multicriterio","multideportivas","multideportivo","multideterminante","multidimensionales","multidisciplinario","multilateralismo","multimedia","multinacionales","multiplica","multiplicador","multiplicar","multipolaridad","multiservicios","multiusos","mundiales","municipalidad","muniejecutivos","murales","museales","mvcs","myperu","mypime","mypymes","nacionalidad","nacionalmente","naranjillo","narcontraficantes","nativa","naturalizar","naturalmente","navales","nave","navegable","naves","nazca","nazcan","ndc","necesitaba","necesitado","necesitando","necesitar","necesitaran","necesitaremos","necesitemos","nefasta","nefastas","negaba","negado","negar","negativamente","negociadas","negociado","negra","neocolonialismo","neoliberalismo","nepotismo","netback","neutralizar","neutro","nichos","nini","nivelar","nivelarse","noble","noche","nocionales","nombres","nominal","normado","normalizar","norteamericana","notas","notificaciones","notorias","novedosa","novena","nube","nueve","nulos","numeral","numerario","numerosos","nutraceuticos","nutran","nutritiva","obedece","obedecen","obejetivos","objetivas","objetos","obligados","obligatoriamente","obreros","obscuros","observado","observan","observando","obsoleta","obsoletas","obstaculizada","obstaculizan","obstetras","obtengan","obtenida","obtuvieron","obvia","ocasionadas","ocasionados","occidental","occidente","occipital","ocio","ocis","ocse","octanaje","ocultar","ocupacional","ocupaciones","ocupamos","ocupando","ocurra","ocurrencias","ocurriendo","odios","oefa","ofertas","off","office","offshore","oficializado","ofrecemos","ofrecido","oit","ojo","olas","oleducto","oleoductos","oligopolistica","oligopolizado","olivera","ollas","olvidadas","olvidados","olvidarse","omate","omc","omnipresentes","omv","ondas","oneroso","onerosos","ong","ongs","ontario","ontip","opacar","opacos","open","operacionales","operado","opina","opiniones","opone","oportunistas","optado","optaron","opten","optima","optimiza","optimizado","optimo","ordena","ordenadas","ordenando","ordenanzas","ordinario","orfandad","organigrama","organigramas","organizacionales","organizarse","orientadores","orientan","orientemos","originadas","originan","originario","ornato","osb","osce","oscilan","oscuridad","osignermin","osinergmin","osinfor","ostensible","otc","otca","otorgado","otorgaremos","otorgarle","otorgarse","overshooting","ovinos","oxfam","oxi","oxiperu","paccha","paciencia","pacifica","pacifico","pacifistas","pactada","pacte","padeciendo","pagaban","pagadera","pagador","pagados","paiche","palabras","palacio","palestina","paliativos","palta","paltas","pampa","paneles","paniagua","panorama","papeleo","par","paradeportivos","paradigmas","paradoja","paradojicamente","paralicen","paralizaciones","paralizada","paralizar","parc","parche","parches","parecen","parecer","pareciera","paredes","pareja","parental","parentales","pari","parietales","parta","parteras","participamos","participaremos","participativamente","participativos","particularidades","partidarias","partidario","pasadas","pasados","pasajero","pasajes","pasamos","pasan","pasaportes","pasarse","pasible","pasiva","passu","pasta","pastillas","pata","patahuasi","paternalista","paternidad","patriarcal","patrimoniales","patrimonios","patrocinada","patrocinado","patrocinio","patrullero","paulatinos","paulo","pavimentada","pbc","pcd","pdslt","peajes","peatonal","peatones","pec","pecuaria","pecuario","pecuniarias","pecuniario","pedidos","pedir","pel","peleas","penalizan","penalizando","penalizar","penetrado","penitenciaria","penitenciarias","pensadas","pensado","pensando","pensionable","pensionarias","pentur","percance","percepciones","perciban","percibe","perdedores","perdemos","perdieron","perdimos","perecibles","peregrinaje","perfeccionando","perfectamente","perillas","periodica","periodicamente","periurbano","perjudican","perjudicando","perjudiciales","perjuicios","permanecer","permanezcan","permisible","permitidos","permitiera","permitieran","permitieron","permitiremos","permitirse","perpetradores","perpetuador","perro","persa","persiga","persistan","personalmente","peruanidad","perversa","pesada","pescador","pescan","pesimista","pesos","pestes","petitorios","pett","pf","pias","pidieron","piedras","piel","piensan","pies","pieza","pileta","pilotos","pircas","pista","placista","plagados","planas","planeamos","planear","planearse","planifica","planificados","planificando","planteada","planteamiento","plantearemos","plantee","planteemos","plasmarlos","plasme","playas","plaza","plenitud","plenos","plng","plurinacional","plurinacionalidad","plus","pmo","pns","poartir","poblador","pocsi","podremos","poi","polideportivos","politicas","politizados","polivalente","polo","polobaya","ponemos","ponerla","ponerlo","populosos","portadoras","portal","portatiles","portavoces","porter","portuaria","posea","poseedores","posesiones","posibilitando","posibilite","posicionando","posicionarlas","posicionarse","posiciones","positividad","posta","postergada","postergados","postulaciones","postulamos","postularemos","postularon","pota","potenciados","potencialmente","potencian","potenciaran","potenciarlos","potenciarse","potencien","ppc","ppk","ppl","practicar","practicarse","practicas","practique","praxis","precaridad","precariza","precarizando","precauciones","precautoriamente","precautorio","precedente","precepto","precipitada","precisa","precisar","predictible","predictiva","predominio","preescolar","preexistentes","preferencia","preferido","prefieren","preguntas","prejuicios","preliminares","premeditada","premeditado","premiar","premio","prendas","preocupa","preocupacion","preocupante","preocupantes","preocupe","preparando","prepas","preprofesionales","prerrequisito","prescriben","presentacion","presentamos","presentaron","presentarse","presenten","presento","preserva","preserve","presida","presidenta","presionar","presiones","prestador","prestamistas","prestamos","prestar","preste","presupuestado","presupuestarias","pretenda","pretendemos","prevalece","prevalentes","prevencion","prevenga","prevenirse","prever","previamente","prico","primado","primarias","prime","primen","priorizado","prisiones","prisma","privacidad","privadamente","privatice","privativas","privilegiada","privilegiado","privilegiados","privilegiaremos","privilegien","privilegio","proactivamente","proactivas","probabilidad","probadas","probado","procedencia","procederemos","procesales","procesamineto","procesaremos","procesarlos","proclamar","proclive","procura","procuran","procurar","producciones","producente","productividades","produjo","produtivas","produzca","profesionalizadas","profesionalizado","profesionalizar","profesor","profundizadas","profundos","programados","progresividad","prohibiciones","prohibiremos","prohibitiva","project","proliferado","prolijidad","prolongado","prolonguen","promesas","promisorio","promociona","promocionar","promocionaremos","promovers","promoverse","promovido","promoviera","promovilidad","promulgando","pronamachs","pronatel","pronis","prontas","prontitud","pronunciado","propensos","propiamente","propiciado","propicie","propicio","proporciona","proporcionados","proporcionales","proporcionalidad","proporcionan","proporcione","propuestos","propugnando","propulsada","prosperamos","prosperar","protagonistas","protagonizados","protection","protector","protectoras","protegido","protegidos","protejamos","protestas","protocolo","provee","proveeremos","proveerse","provenga","provenimos","provisional","provisionales","provistos","provocadas","provocados","provocando","provocar","provocativamente","proyectan","prudente","psicosocial","psiquiatras","ptars","pu","publicaciones","publicadas","publicaremos","publicidad","publicos","pudiendo","pudieron","puedes","puestas","pugna","pugnamos","pugnas","pulpo","pulseras","punitiva","punitivo","punteros","puntual","puntuales","puquina","pura","pusieron","puyango","quebradas","quebrado","quebraron","quedar","queman","querer","queridos","quesada","quince","quinta","quintiles","quinua","quiroz","quispe","quita","racionalizados","racionalizar","racionalizaremos","racista","radial","radicalmente","radioactivo","radiquen","raee","ramales","ramificaciones","ramiro","rampas","rancha","rap","rapidamente","rapidez","rastrear","ratificamos","ratificando","ratios","razonable","razonadas","reaccionar","reacciones","reacias","reactivadora","reactivados","reactivos","reafirmar","reajustando","realce","realice","realinear","realismo","realizables","realizador","realizara","realizarlo","realizaron","reaprovechable","rebalancear","rebalancearse","rebalanceo","rebasa","recae","recaer","recalificados","recambio","recapitalizar","recargado","receptivo","receptores","receso","rechazan","rechazo","reciba","recibidas","recibidos","recibimos","reciclado","reciclados","recien","reclamado","reclaman","reclamantes","reclutados","reclutamiento","reclutar","recobraremos","recoge","recogerlo","recogido","recoja","recolectar","recolectores","recompensa","recompensas","recomponer","reconfigurado","reconfiguraremos","reconoceremos","reconstruccion","reconstruiremos","reconstruya","reconvertidas","reconvierten","recordamos","recordaran","recorrer","recortados","recortes","recreacionales","recreativa","rectificadora","rectora","rectores","recupera","recuperados","recuperando","recuperarla","recuperarlo","recuperarse","recupere","recuperen","recurrente","recurrido","recurrir","redactaron","redefiniremos","redimensionarse","redireccionadas","redireccionarse","redistributiva","reducciones","reducidas","reducidores","reducirse","redunda","redundancia","redundando","reelecciones","reembolso","reemplace","reemplazando","reencuentro","reenfocando","reentrenamiento","reentrenar","reestablecer","reestablezca","reestructuracion","reestructurada","reestructurado","reestructuran","reevaluando","referenciada","referenciadas","referidas","referimos","referirle","refinanciamiento","reflejen","reflexionar","reflotar","reformada","reformadas","reformula","reformularemos","reformularse","reforzados","refrigeradoras","refuerce","refugiar","refundaciones","refundado","regalia","regenerando","regida","regidas","regidos","regionalmente","registraron","registren","reglamentada","reglamentado","reglamentando","reglamente","regresan","regrese","regresen","regresiva","regulaciones","regulada","regulados","regularlo","regularmente","regulatorios","rehabiliten","reimpulso","reinado","reincorpora","reinsertarse","reinstaurar","reintegrando","reintegrarse","reiteramos","reivindicamos","reivindicar","reivindicativo","relacionada","relacionamiento","relacionan","relanzamiento","relanzar","relanzaremos","relativos","relectura","relegada","relegado","relevaremos","relieve","religiones","remanente","remanufactura","remates","remediados","remedian","remediar","remedio","remesa","remitidas","remover","remunerada","remype","renal","rencores","renombre","renovarla","renovarse","rentablemente","rentistas","rentrenamiento","renueva","renueve","renuncia","reorganiza","reorganizadas","reorientaremos","reorientarse","reoriente","reparatoria","repasando","repasar","repaso","repatriar","repensando","repentina","repercuta","repetimos","repetir","repetitivas","repitan","replanteamiento","replantear","replicando","replicaremos","reportado","repositorios","reposo","representaba","representaciones","representada","representante","representaron","representativa","reproche","reprogramaciones","reprogramar","requerida","resaltando","resarcimiento","rescataremos","rescataron","reservorios","resguardo","residan","residen","residual","resistentes","reskilling","resolveremos","resolverse","respaldar","respectiva","respetables","respetadas","respetado","respetamos","respete","respiramos","respondiendo","responsablemente","restablecida","restableciendo","restablecimiento","restan","restaurado","restauraremos","restaurativa","restaure","restrictiva","restrictivos","restringen","restringida","resuelto","resueltos","resuelve","resultan","resulten","resumida","resumirse","resurgimiento","retadora","retail","retando","retirado","retornando","retornos","retrasan","retrasando","retribuciones","retribuida","retroalimentar","retroceda","reuso","revaloran","revalore","revalorizando","revalorizarlos","revela","revelada","revelado","revelamos","reventa","reverdecidas","revertida","revertido","revertirse","revisada","revisado","revise","revisen","revisiones","revisores","revista","revistan","revitaliza","revitalizaremos","revocatoria","revolucionando","revolucionar","rezagados","riachuelos","ricardo","ricas","riegos","riesgosos","rige","rigidez","rimac","rm","rnie","robos","robustezcan","robustos","rodilla","roja","romano","rompa","rompe","ronda","ropa","rota","rotundamente","rotundo","roza","rrhh","rrmm","rudimentario","rueda","ruptura","rurarales","rusia","rutina","sacan","sacrificio","saga","sagasti","saharaui","saldar","saldos","salidas","salieran","salinidad","salitral","salmueras","salubristas","salvador","salvados","salvaguardas","salvaguardia","salvar","san","sanan","sanas","sancionada","sancionados","saneadas","sangre","sanitariamente","santificador","santo","sao","saquear","sarairiza","sarameriza","saramiriza","satisfactoriamente","satisfecho","satisfechos","saturado","saturan","sausal","sbn","scooters","secciones","seco","secretarios","secretismo","secreto","secuencia","secuestradas","sedapal","sede","sedguridad","segib","seguidos","seguirse","segundas","segundos","sela","sello","semanal","sembrado","sembrarlos","semestral","semestralmente","semilla","semillero","semilleros","senadores","sencilla","sendero","sensatas","sensibilidad","sensibilizan","sentir","sentiremos","sentirse","sepa","separan","sequias","serenos","seriedad","sesgadamente","sesgos","setiembre","severo","sexualidad","sexualmente","shamanes","siaf","siagie","sibe","sicariato","sicuani","sida","sienta","siente","sigma","signada","significado","significados","significan","significaron","significativas","signos","sihuas","simpatizantes","simultaneo","sinafor","sinagerd","sinapedis","sinasec","sinceramiento","sincerar","sindical","sineace","singapur","singulares","sinoe","sinovac","sintetizar","sinuosidad","siries","sirve","siseve","sistematice","sistematizada","sitemas","sitm","sits","situada","situando","situarse","small","smartphone","smv","snej","snfpc","soa","soberanas","soborno","sobornos","sobrecargado","sobrepeso","sobreponerse","sobreprecios","sobrevaloraciones","sobrevalorada","sobrevalorados","sobrevalorar","sobrevaluadas","socava","socavados","socavamiento","socavar","socialismo","socialista","societario","socioambientales","sociocultural","sol","solicitados","solicitan","solicitando","solicitaron","soluciona","solucionamos","solucionarlas","somete","someten","sometida","sometieron","soporta","soportada","sorprende","sorprender","sospechosa","sospechoso","sostenerse","sosteniblemente","sostenidas","sostienen","spij","spread","spreads","ssfd","stablishment","stakeholderismo","startups","subalternos","subastan","sube","subiendo","submarinos","subrayado","subrayando","subsecretario","subsector","subsidiando","subsidiariedad","subsidiario","subsisten","subsistencias","subsuelo","subutilizada","subvencionados","subversivos","suceden","suceder","sucesional","sucesiva","sucesos","sucursales","suficientemente","sufridos","sufrimiento","sufrimos","sufrir","sujetan","sujetarse","sullana","sumada","sumadas","sumar","sumaron","sumarse","sumas","sumido","suministradas","sunarp","sunas","sunass","supedita","supeditadas","supera","superada","superado","superaremos","superavit","superfluos","superintendencias","superintendente","supermercados","superposiciones","superpuesta","supervisado","supervise","supervisora","suplementario","suposiciones","suprarregional","supremos","supuestamente","supuestas","supuestos","supuso","surco","surgen","surgido","surgimiento","surja","surjan","surtidores","suscitan","suscribe","suscribimos","suspensiones","sustantivo","sustentabalidad","sustentan","sustentarse","sustituidos","sustituyan","sustituyendo","sutran","tabaco","tabla","tablero","tableros","tablets","tacna","tahuantinsuyo","taiwan","taj","taller","tarifarias","tarifario","tarjetas","tauca","tawantinsuyo","tca","tdcnr","teatros","tecnico","tecnifiquen","tejidos","telecom","telecontrol","telepresencia","telesalud","televisiva","temerosa","temperaturas","tendemos","tendiendo","tendiente","tendria","tenencias","tenerla","tensa","terapia","terceras","tercerizar","tercero","terminaba","terminados","termine","terrapuertos","terremoto","terremotos","terrible","terribles","territorializada","terror","terry","test","testear","textos","textura","tibio","tigres","tilapia","tir","titula","titulada","tituladas","titulares","tlc","tocado","tolera","toleran","tomada","tomados","toman","tomara","tomaron","torata","tormenta","torna","toro","torpe","torrenciales","totalizadora","trabajados","trabajaran","trabando","traducen","traducida","traduzca","traficantes","trafico","trailers","trajeran","tramiten","tramites","tramos","trampa","transandino","transciende","transcribir","transdisciplinares","transferencistas","transferida","transferirles","transformada","transformador","transformadoras","transformarnos","transformativas","transformativo","transforme","transita","transitado","transitados","transitoria","transitorios","transmisor","transnacionales","transparentarse","transporta","transportadas","transportar","transversalmente","trasladan","trasladar","trasmitir","trasparente","trastornos","tratada","tratando","trate","traumas","traves","traza","trazar","tremendamente","tremendas","tren","trends","trepar","tribales","tribunales","tributa","tributan","trinacionales","tripartita","triple","triplicar","triste","triunfo","tropical","tropicales","truchas","trunca","truncadas","truncamiento","truncas","trunco","ttp","tumba","turbulencia","turbulento","turista","tutela","tutor","tutores","ubica","ubican","ucayali","uchiza","uk","unan","unanimidad","unicef","uniendolos","unificaremos","unifique","unifiquen","uniformes","uniformidad","uniones","unirse","unit","unitarios","universalizando","universalizar","university","universo","upgrading","upskilling","uranio","urbanidad","urbanismo","urbanizable","urbanizaciones","urbes","urna","urquiza","usarlo","use","usinas","usuaria","usuarias","usufructo","usura","utilicemos","utilicen","utilizado","utilizan","utilizarlo","utilizaron","utilizarse","vaciante","vacunaciones","vacunada","vacunado","vacunara","vacunatorio","vacunatorios","vacune","valerosos","validada","valide","valorados","valoramos","valoran","valoraremos","valoremos","valorizar","variaciones","variado","variante","varones","vaso","vasto","vastos","veamos","velan","velaremos","velozmente","vencido","venda","vende","vendedores","venden","venezolana","venezolanos","ventajosa","venture","verbal","vergonzosa","vergonzosas","verifica","verificados","verificando","verificar","vertido","vesania","vestido","vestir","vetustas","vi","vialidad","viceministerial","viceministeriales","vicente","viceversa","victimario","victimas","victimizando","videojuegos","videos","vientos","vientres","vierte","vigilada","vigor","vigorosa","viii","vilipendiados","vilipendiarla","villas","vimos","vincula","vinculaciones","vinculando","vincular","vincularlos","vincule","violaciones","violadores","violentadas","violenten","viral","virales","virtualizar","virtud","visibiliza","visibilizadas","visibilizando","visible","visibles","visitables","visitados","visitar","visitas","visiten","vislumbra","viste","vistos","visuales","visualizar","vitalicia","vitrina","viuda","vivamos","vivencia","viveros","vivo","vladimiro","vocales","vocero","volatilidad","volcarnos","voluntariamente","volverlos","volviendo","volvieran","volvieron","vota","votaste","vouchers","vuelos","vulnera","vulneraciones","waymakos","world","xdsl","yachachic","yachachiq","yacimiento","yale","yantac","yauri","yoga","yungaypampa","yuxtaponen","zanjas","zf","zif","zika","zozobra"],"freq":[788,661,595,554,432,408,352,339,291,290,264,250,249,224,222,215,214,202,201,200,199,196,194,192,187,184,173,162,159,157,155,153,152,151,150,146,146,146,146,145,143,143,141,141,140,138,137,136,133,133,133,132,129,126,126,126,125,125,121,121,119,118,117,116,116,114,111,111,110,109,109,108,107,106,104,103,102,102,101,101,101,100,100,99,99,99,98,98,96,94,94,94,93,92,92,91,91,91,90,89,89,88,88,87,87,87,87,86,86,86,85,85,85,84,84,84,83,83,83,83,83,82,82,81,81,81,81,80,80,80,79,79,79,79,78,77,77,77,77,76,75,75,75,75,74,74,74,74,74,74,73,73,73,73,73,72,72,72,72,72,72,72,71,71,71,70,69,69,69,68,68,68,68,68,67,67,67,67,67,67,67,66,66,66,65,65,65,65,65,65,65,65,64,64,64,64,64,64,63,63,63,63,63,63,63,62,62,62,62,62,62,61,61,61,60,60,60,59,59,59,59,59,59,58,58,58,58,58,58,58,58,57,57,57,57,57,56,55,55,55,55,55,55,55,55,54,54,54,54,54,54,53,53,53,53,53,53,52,52,52,52,52,51,51,51,51,51,51,51,50,50,50,50,50,50,50,50,50,50,49,49,49,49,49,49,48,48,48,48,48,48,48,48,48,48,47,47,47,47,47,47,47,47,47,46,46,46,46,46,46,46,46,45,45,45,45,44,44,44,44,44,44,44,44,44,44,44,44,43,43,43,43,43,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,41,41,41,41,41,41,41,41,41,41,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,39,39,39,39,39,39,39,39,39,39,38,38,38,38,38,38,38,38,38,38,38,37,37,37,37,37,37,37,37,37,37,37,36,36,36,36,36,36,36,36,36,36,36,36,36,35,35,35,35,35,35,35,35,35,34,34,34,34,34,34,34,34,34,34,34,33,33,33,33,33,33,33,33,33,33,33,33,33,32,32,32,32,32,32,32,32,32,32,32,32,32,32,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],"fontFamily":"Segoe UI","fontWeight":"bold","color":"random-dark","minSize":"Hola todos","weightFactor":0.182741116751269,"backgroundColor":"white","gridSize":0,"minRotation":-0.3490658503988659,"maxRotation":0.3490658503988659,"shuffle":true,"rotateRatio":0.4,"shape":"circle","ellipticity":0.65,"figBase64":null,"hover":null},"evals":[],"jsHooks":{"render":[{"code":"function(el,x){\n console.log(123);\n if(!iii){\n window.location.reload();\n iii = False;\n\n }\n }","data":null}]}}&lt;/script>
&lt;p>The ten most repeated words demonstrate the primary political parties’ focus on the &lt;strong>development&lt;/strong> (&lt;em>desarrollo&lt;/em>) of the country, with a strong emphasis on &lt;strong>health&lt;/strong> (&lt;em>salud&lt;/em>) in line with the current health crisis. The proposal to improve the &lt;strong>system/services/government&lt;/strong> (&lt;em>sistema/servicios/gobierno&lt;/em>) aligns with the repetition of these terms.&lt;/p>
&lt;center>
&lt;pre>&lt;code>## # A tibble: 10 × 2
## word n
## &amp;lt;chr&amp;gt; &amp;lt;int&amp;gt;
## 1 nacional 788
## 2 desarrollo 661
## 3 salud 595
## 4 sistema 554
## 5 servicios 432
## 6 gobierno 408
## 7 social 352
## 8 plan 339
## 9 recursos 291
## 10 calidad 290
&lt;/code>&lt;/pre>
&lt;/center>
&lt;h2 id="global-sentiments">Global Sentiments&lt;/h2>
&lt;p>Certain words are associated with negative sentiments (e.g., &lt;em>problemas&lt;/em> [problems], &lt;em>pobreza&lt;/em> [poverty], &lt;em>crisis&lt;/em> [crisis], etc.) and positive sentiments (e.g., &lt;em>reforma&lt;/em> [reform], &lt;em>propuesta&lt;/em> [proposal], &lt;em>bienestar&lt;/em> [well-being], etc.). By counting these words, we can infer which sentiment is associated with the overall discourse:&lt;/p>
&lt;p>&lt;img src="https://luis-zapatabobadilla.netlify.app/project/presidential-elections-analysis/index.en_files/figure-html/unnamed-chunk-6-1.png" width="672" />&lt;/p>
&lt;p>Negative sentiments are observed in words such as &lt;em>pobreza&lt;/em> [poverty], &lt;em>crisis&lt;/em> [crisis], and &lt;em>lucha&lt;/em> [struggle]. Similarly, positive sentiments are present in words like &lt;em>reforma&lt;/em> [reform], &lt;em>derecho&lt;/em> [rights], and &lt;em>capacidad&lt;/em> [capacity].&lt;/p>
&lt;p>We can infer that the government plans generally position their discourse against &lt;strong>crisis/poverty&lt;/strong> (&lt;em>crisis/pobreza&lt;/em>), offering &lt;strong>reforms/improvements&lt;/strong> (&lt;em>reformas/mejoras&lt;/em>) focused on &lt;strong>rights/capacities&lt;/strong> (&lt;em>derechos/capacidades&lt;/em>).&lt;/p>
&lt;h1 id="comparison-between-parties">Comparison Between Parties&lt;/h1>
&lt;p>Now we will compare the government plans of each party. Below is a word cloud representing the most relevant words for each of the main parties.&lt;/p>
&lt;p>&lt;img src="https://luis-zapatabobadilla.netlify.app/project/presidential-elections-analysis/index.en_files/figure-html/unnamed-chunk-7-1.png" width="768" />&lt;/p>
&lt;h3 id="total-word-comparison">Total Word Comparison&lt;/h3>
&lt;p>When looking at the most repeated words in each government plan, it is evident that the word &lt;strong>salud&lt;/strong> [health] ranks among the top in all plans (except in the plan from Victoria Nacional, which emphasizes introductory terms more heavily).&lt;/p>
&lt;p>The following positions provide more heterogeneous ideas about the themes relevant to each plan. It is worth mentioning that the following words were removed for being &lt;strong>related to the general topic of governance&lt;/strong>: Nacional [National], Sistema [System], Servicios [Services], Gobierno [Government], Programa [Program], Propuesta [Proposal], Plan [Plan], and Servicios [Services]. Additionally, the following words were removed for lacking contextual relevance: Millones [Millions], Niveles [Levels], Enfoque [Focus], Forma [Form], Proponemos [We Propose], Inclusive [Inclusive], and Impulsaremos [We Will Promote].&lt;/p>
&lt;p>&lt;img src="https://luis-zapatabobadilla.netlify.app/project/presidential-elections-analysis/index.en_files/figure-html/unnamed-chunk-8-1.png" width="672" style="display: block; margin: auto;" />&lt;/p>
&lt;p>As mentioned earlier, the most repeated words &lt;strong>(Nacional [National], Sistema [System], Desarrollo [Development], Servicios [Services], Gobierno [Government])&lt;/strong> are common across all parties and have been excluded. These words are all related to a shared theme within the documents: &lt;strong>A government plan for a country&lt;/strong>. However, topics related to &lt;strong>Salud [Health]&lt;/strong> and &lt;strong>Desarrollo [Development]&lt;/strong> are common across all plans due to the context of COVID-19 and the economic crisis following the pandemic.&lt;/p>
&lt;p>An interesting approach might be to extract the most repeated words within a single government plan that are not as commonly repeated across the other plans.&lt;/p>
&lt;h3 id="tf-idf-comparison">TF-IDF Comparison&lt;/h3>
&lt;p>The following approach uses &lt;a href="https://useo.es/tf-idf-relevancia/" target="_blank" rel="noopener">&lt;strong>tf-idf&lt;/strong>&lt;/a>, a widely-used technique in information retrieval and text analysis to identify the most distinctive and relevant terms in a document.&lt;/p>
&lt;ul>
&lt;li>&lt;strong>TF (Term Frequency)&lt;/strong>: Measures how often a word appears in a specific document. Words that occur frequently in a document have higher TF values.&lt;/li>
&lt;li>&lt;strong>IDF (Inverse Document Frequency)&lt;/strong>: Weighs how unique a word is across an entire collection of documents. Words that appear in many documents (e.g., “government” in this context) have a lower IDF score, as they are less distinctive.&lt;/li>
&lt;/ul>
&lt;p>By combining these measures, &lt;strong>tf-idf&lt;/strong> highlights words that are important to a single document but not common across the collection. This makes it ideal for comparing government plans, as it allows us to uncover terms that are particularly relevant to each party’s proposals while filtering out generic or overly common words.&lt;/p>
&lt;p>In the plot below, the highest &lt;strong>tf-idf&lt;/strong> words for each party are visualized, showcasing the terms that differentiate their plans from the others.&lt;/p>
&lt;p>&lt;img src="https://luis-zapatabobadilla.netlify.app/project/presidential-elections-analysis/index.en_files/figure-html/unnamed-chunk-9-1.png" width="576" style="display: block; margin: auto;" />&lt;/p>
&lt;p>The TF-IDF analysis highlights the unique focus of each political party. &lt;strong>Acción Popular&lt;/strong> emphasizes pension systems (e.g., &lt;em>SNP&lt;/em>, &lt;em>SPP&lt;/em>, &lt;em>CIC&lt;/em>) and references historical figures like &lt;em>Belaúnde&lt;/em>. &lt;strong>Fuerza Popular&lt;/strong> focuses on public health and pandemic-related terms like &lt;em>infectados&lt;/em> (infected) and &lt;em>defendemos&lt;/em> (we defend), along with political events such as &lt;em>Noviembre&lt;/em> (November protests). &lt;strong>Juntos por el Perú&lt;/strong> centers on social rights and minorities, with words like &lt;em>LGBTI&lt;/em>, &lt;em>Afroperuanos&lt;/em>, and &lt;em>solidarias&lt;/em> (solidarity).&lt;/p>
&lt;p>&lt;strong>Partido Morado&lt;/strong> highlights innovation and societal issues, referencing &lt;em>talento&lt;/em> (talent), &lt;em>deporte&lt;/em> (sports), and &lt;em>maltrato&lt;/em> (abuse). &lt;strong>Podemos&lt;/strong> prioritizes economic relief with terms like &lt;em>IGV&lt;/em> (tax), &lt;em>deudas&lt;/em> (debts), and &lt;em>planillas&lt;/em> (payrolls). &lt;strong>Victoria Nacional&lt;/strong> focuses on infrastructure and judicial reforms, with terms like &lt;em>Ernc&lt;/em> (renewable energy), &lt;em>crudo&lt;/em> (crude oil), and &lt;em>jurados&lt;/em> (juries). These unique keywords underline each party’s strategic priorities.&lt;/p>
&lt;p>There are some abbreviations:&lt;/p>
&lt;table>
&lt;thead>
&lt;tr>
&lt;th>&lt;strong>Party&lt;/strong>&lt;/th>
&lt;th>&lt;strong>Acronym&lt;/strong>&lt;/th>
&lt;th>&lt;strong>Meaning&lt;/strong>&lt;/th>
&lt;/tr>
&lt;/thead>
&lt;tbody>
&lt;tr>
&lt;td>&lt;strong>Acción Popular&lt;/strong>&lt;/td>
&lt;td>SNP&lt;/td>
&lt;td>National Pension System (&lt;em>Sistema Nacional de Pensiones&lt;/em>)&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>&lt;/td>
&lt;td>SPP&lt;/td>
&lt;td>Private Pension System (&lt;em>Sistema Privado de Pensiones&lt;/em>)&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>&lt;/td>
&lt;td>OECD&lt;/td>
&lt;td>Organization for Economic Cooperation and Development (&lt;em>Organización para la Cooperación y el Desarrollo Económicos&lt;/em>)&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>&lt;/td>
&lt;td>FCRP&lt;/td>
&lt;td>Consolidated Reserve Fund of Pensions (&lt;em>Fondo Consolidado de Reservas Previsionales&lt;/em>)&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>&lt;/td>
&lt;td>CIC&lt;/td>
&lt;td>Individual Capitalization Account (&lt;em>Cuenta Individual de Capitalización&lt;/em>)&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>&lt;strong>JP&lt;/strong>&lt;/td>
&lt;td>APS&lt;/td>
&lt;td>Primary Health Care (&lt;em>Atención Primaria de Salud&lt;/em>)&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>&lt;/td>
&lt;td>LGBTI&lt;/td>
&lt;td>Lesbian, Gay, Bisexual, Transgender, and Intersex Community (&lt;em>Comunidad: Lesbianas, Gays, Bisexuales, Transgénero e Intersexuales&lt;/em>)&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>&lt;/td>
&lt;td>SSR&lt;/td>
&lt;td>Sexual and Reproductive Health (&lt;em>Salud Sexual y Reproductiva&lt;/em>)&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>&lt;/td>
&lt;td>RDNFO&lt;/td>
&lt;td>National Fiber Optic Backbone (&lt;em>Red Dorsal Nacional de Fibra Óptica&lt;/em>)&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>&lt;/td>
&lt;td>SPC&lt;/td>
&lt;td>Peruvian Care System (&lt;em>Sistema Peruano de Cuidados - Proposal&lt;/em>)&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>&lt;strong>Podemos&lt;/strong>&lt;/td>
&lt;td>FAE&lt;/td>
&lt;td>Business Support Fund (&lt;em>Fondo de Apoyo Empresarial - FAE Agro&lt;/em>)&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>&lt;/td>
&lt;td>IGV&lt;/td>
&lt;td>General Sales Tax (&lt;em>Impuesto General a las Ventas&lt;/em>)&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>&lt;/td>
&lt;td>LIC&lt;/td>
&lt;td>Criminal Investigation Institute (&lt;em>Instituto de Investigación Criminal - Proposal&lt;/em>)&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>&lt;/td>
&lt;td>PYME&lt;/td>
&lt;td>Small and Medium Enterprises (&lt;em>Pequeña y Mediana Empresa&lt;/em>)&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>&lt;/td>
&lt;td>EIRLS&lt;/td>
&lt;td>Limited Liability Individual Enterprises (&lt;em>Empresas Individuales de Responsabilidad Limitada&lt;/em>)&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>&lt;/td>
&lt;td>Tele&lt;/td>
&lt;td>Prefix (e.g., Tele-work or remote work)&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>&lt;strong>Fuerza Popular&lt;/strong>&lt;/td>
&lt;td>—&lt;/td>
&lt;td>No specific acronyms mentioned&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>&lt;strong>Partido Morado&lt;/strong>&lt;/td>
&lt;td>—&lt;/td>
&lt;td>No specific acronyms mentioned&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>&lt;strong>Victoria Nacional&lt;/strong>&lt;/td>
&lt;td>ERNC&lt;/td>
&lt;td>Non-conventional Renewable Energies (&lt;em>Energías Renovables No Convencionales&lt;/em>)&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>&lt;/td>
&lt;td>CTI&lt;/td>
&lt;td>Science, Technology, and Innovation (&lt;em>Ciencia, Tecnología e Innovación&lt;/em>)&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>&lt;/td>
&lt;td>Lesa&lt;/td>
&lt;td>Crimes Against Humanity (&lt;em>Crímenes de Lesa Humanidad&lt;/em>)&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>&lt;/td>
&lt;td>FONDEM&lt;/td>
&lt;td>Trust Fund for Financing Sustainable Balanced Development (&lt;em>Fondos de Fideicomiso para Financiar el Desarrollo Equilibrado Sostenible&lt;/em>)&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>&lt;/td>
&lt;td>—&lt;/td>
&lt;td>Multisectoral Zones of Natural Resource Concessions (&lt;em>Multisectorial de Zonas de Influencia de Concesiones de Recursos Naturales - Proposal&lt;/em>)&lt;/td>
&lt;/tr>
&lt;/tbody>
&lt;/table>
&lt;center>
&lt;figure>
&lt;img src="Acronimos.png" alt="Acronimos" />
&lt;figcaption aria-hidden="true">Acronimos&lt;/figcaption>
&lt;/figure>
&lt;/center>
&lt;p>We can apply the same TF-IDF analysis using combinations of words (bigrams):&lt;/p>
&lt;p>&lt;img src="https://luis-zapatabobadilla.netlify.app/project/presidential-elections-analysis/index.en_files/figure-html/unnamed-chunk-10-1.png" width="768" style="display: block; margin: auto;" />&lt;/p>
&lt;p>The bigram TF-IDF analysis highlights unique combinations of terms that define each party’s priorities. &lt;strong>Acción Popular&lt;/strong> focuses on governance and opportunities with phrases like &lt;em>Fernando Belaúnde&lt;/em> and &lt;em>Mejores Oportunidades&lt;/em>. &lt;strong>Fuerza Popular&lt;/strong> emphasizes educational and social programs, using terms like &lt;em>Programas Sociales&lt;/em> and &lt;em>Brecha Digital&lt;/em> (digital gap). &lt;strong>Juntos por el Perú&lt;/strong> underscores social justice with bigrams like &lt;em>Derechos Colectivos&lt;/em> (collective rights) and &lt;em>Diversidad Sexual&lt;/em> (sexual diversity).&lt;/p>
&lt;p>&lt;strong>Partido Morado&lt;/strong> prioritizes innovation and sustainability, evident in phrases like &lt;em>Servicios Digitales&lt;/em> (digital services) and &lt;em>Manifestaciones Culturales&lt;/em> (cultural manifestations). &lt;strong>Podemos&lt;/strong> highlights economic concerns with terms like &lt;em>Baja Productividad&lt;/em> (low productivity) and &lt;em>Futuras Pandemias&lt;/em> (future pandemics). &lt;strong>Victoria Nacional&lt;/strong> focuses on infrastructure and legal reforms, with bigrams such as &lt;em>Gas Natural&lt;/em> (natural gas) and &lt;em>Centros Poblados&lt;/em> (populated centers). These combinations offer deeper insights into each party’s distinct focus areas.&lt;/p>
&lt;p>So far, we have interpreted words as carriers of meaning, identifying those that are most relevant to each government plan. This has allowed us to highlight unique terms and ideas across the parties. Now, we will shift our focus to interpret words as carriers of &lt;strong>sentiments&lt;/strong> and examine which government plans make greater use of positive or negative sentiments.&lt;/p>
&lt;h2 id="sentiment-comparison">Sentiment Comparison&lt;/h2>
&lt;p>First, let’s identify the most frequently mentioned words associated with positive (Positivo) and negative (Negativo) sentiments in the government plans:&lt;/p>
&lt;p>&lt;img src="https://luis-zapatabobadilla.netlify.app/project/presidential-elections-analysis/index.en_files/figure-html/unnamed-chunk-11-1.png" width="768" style="display: block; margin: auto;" />&lt;/p>
&lt;p>The plot reveals a mix of positive and negative sentiments across the parties’ government plans. Positive sentiments dominate with words like &lt;em>reforma&lt;/em> (reform), &lt;em>derechos&lt;/em> (rights), &lt;em>sostenible&lt;/em> (sustainable), and &lt;em>capacidades&lt;/em> (capacities), highlighting a focus on social change, sustainability, and empowerment. Negative sentiments, while less frequent overall, are concentrated in terms like &lt;em>pobreza&lt;/em> (poverty), &lt;em>crisis&lt;/em> (crisis), and &lt;em>deudas&lt;/em> (debts), reflecting concerns about socio-economic challenges.&lt;/p>
&lt;p>Overall, parties like &lt;strong>Juntos por el Perú&lt;/strong> and &lt;strong>Partido Morado&lt;/strong> emphasize positive framing, focusing on opportunities and rights, while &lt;strong>Acción Popular&lt;/strong> and &lt;strong>Podemos&lt;/strong> lean more on negative sentiments, addressing pressing issues like poverty and financial instability. These contrasts underscore the varied approaches to addressing Peru’s challenges.&lt;/p>
&lt;p>This visualization highlights the words contributing most significantly to positive and negative sentiments in each government plan. The distribution of these words offers insight into the tone and emotional framing each party uses in their proposals.&lt;/p>
&lt;p>By summing the number of positive words and subtracting the number of negative words in each government plan, we can calculate a &lt;em>score&lt;/em> that provides an indication of the overall sentiment (positive/negative) expressed in each document.&lt;/p>
&lt;p>&lt;img src="https://luis-zapatabobadilla.netlify.app/project/presidential-elections-analysis/index.en_files/figure-html/unnamed-chunk-12-1.png" width="768" style="display: block; margin: auto;" />&lt;/p>
&lt;p>From the results, it is evident that &lt;strong>Partido Morado&lt;/strong> and &lt;strong>Juntos por el Perú&lt;/strong> use more words that convey positive sentiments (e.g., &lt;em>derechos&lt;/em> [rights], &lt;em>reforma&lt;/em> [reform], &lt;em>sostenible&lt;/em> [sustainable], &lt;em>integral&lt;/em> [comprehensive], etc.). On the other hand, &lt;strong>Podemos&lt;/strong> and &lt;strong>Acción Popular&lt;/strong> use more words that express negative sentiments (e.g., &lt;em>pobreza&lt;/em> [poverty], &lt;em>baja&lt;/em> [decline], &lt;em>crisis&lt;/em> [crisis], &lt;em>deuda&lt;/em> [debt], etc.). This provides insight into the emotional tone each party aims to evoke through their government plan.&lt;/p>
&lt;h2 id="correlation-between-parties">Correlation Between Parties&lt;/h2>
&lt;p>Finally, we can examine the correlation between the parties by analyzing the percentage of usage for each word and comparing how similar their usage patterns are across the government plans.
If you cant see the page, click &lt;a href="https://luis-jose-zapata-bobadilla.shinyapps.io/Presidentes/" target="_blank" rel="noopener">here&lt;/a>.&lt;/p>
&lt;iframe src="https://luis-jose-zapata-bobadilla.shinyapps.io/Presidentes/?showcase=0" width="768" height="800px" data-external="1">
&lt;/iframe>
&lt;p>This analysis reveals the likelihood that two government plans use similar words at comparable frequencies. By identifying these correlations, we can gauge how aligned or distinct the parties are in their language and focus areas. It reveals the linguistic similarities between the political parties’ government plans.&lt;/p>
&lt;p>&lt;img src="https://luis-zapatabobadilla.netlify.app/project/presidential-elections-analysis/index.en_files/figure-html/unnamed-chunk-14-1.png" width="1152" style="display: block; margin: auto;" />
&lt;strong>Victoria Nacional&lt;/strong> and &lt;strong>Podemos&lt;/strong> share the highest correlation (0.8), suggesting significant overlap in their vocabulary and thematic focus. &lt;strong>Partido Morado&lt;/strong> also shows high correlations with &lt;strong>JP&lt;/strong> (0.8) and &lt;strong>Podemos&lt;/strong> (0.7), indicating shared themes or priorities. &lt;strong>Acción Popular&lt;/strong> exhibits the lowest correlations (0.6) across all comparisons, reflecting its distinct linguistic and thematic approach. These relationships highlight the varying degrees of alignment or divergence in the parties’ proposals.&lt;/p>
&lt;h1 id="conclusions">Conclusions&lt;/h1>
&lt;p>Finally, we can draw comparisons between the different political parties based on their government plans. It is important to clarify that all political parties refer to general, demagogic topics such as Education, Health, Employment, Economic Recovery, etc. Therefore, the conclusions below aim to highlight the subtle characteristics that make each plan stand out.&lt;/p>
&lt;h3 id="acción-popular">Acción Popular&lt;/h3>
&lt;ul>
&lt;li>
&lt;p>Unlike other government plans, &lt;strong>Acción Popular&lt;/strong> has a notable emphasis on terms related to &lt;strong>pensions&lt;/strong> (e.g., &lt;em>pension&lt;/em>, &lt;em>SNP&lt;/em>, &lt;em>SPP&lt;/em>, &lt;em>CIC&lt;/em>, &lt;em>affiliates&lt;/em>, etc.), which is reflected in the frequency of these words.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>Sentiment analysis indicates that the plan leans towards &lt;strong>negative sentiments&lt;/strong>, focusing on words like &lt;em>poverty&lt;/em>, &lt;em>debts&lt;/em>, &lt;em>taxation&lt;/em>, and &lt;em>abusive&lt;/em>.&lt;/p>
&lt;/li>
&lt;/ul>
&lt;h3 id="fuerza-popular">Fuerza Popular&lt;/h3>
&lt;ul>
&lt;li>
&lt;p>Displays a strong presence of terms related to &lt;strong>social assistance&lt;/strong> and &lt;strong>support for small businesses&lt;/strong> (e.g., &lt;em>social&lt;/em>, &lt;em>plan&lt;/em>, &lt;em>programs&lt;/em>, &lt;em>resources&lt;/em>, etc.). Additionally, it highlights the &lt;strong>current pandemic&lt;/strong> and the distribution of vaccines/tests.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>Sentiment analysis shows a balanced use of positive and negative words. While it includes terms related to &lt;strong>poverty&lt;/strong> (e.g., &lt;em>struggle&lt;/em>, &lt;em>crisis&lt;/em>, &lt;em>problems&lt;/em>), it also incorporates a similar number of words related to &lt;strong>support&lt;/strong> (e.g., &lt;em>rights&lt;/em>, &lt;em>rescue&lt;/em>, &lt;em>social programs&lt;/em>, &lt;em>we defend&lt;/em>).&lt;/p>
&lt;/li>
&lt;li>
&lt;p>Makes an uncommon reference (compared to other plans) to the November 2020 protests against Manuel Merino, emphasizing that the protests “negatively affected” the police’s public image.&lt;/p>
&lt;/li>
&lt;/ul>
&lt;h3 id="juntos-por-el-perú-jp">Juntos por el Perú (JP)&lt;/h3>
&lt;ul>
&lt;li>
&lt;p>&lt;strong>Juntos por el Perú&lt;/strong> differs from other government plans by focusing heavily on &lt;strong>social rights&lt;/strong> and &lt;strong>assistance for minorities&lt;/strong> (e.g., &lt;em>social&lt;/em>, &lt;em>cultural&lt;/em>, &lt;em>communities&lt;/em>, &lt;em>services&lt;/em>, &lt;em>LGBTI&lt;/em>, &lt;em>Afro-Peruvians&lt;/em>, etc.).&lt;/p>
&lt;/li>
&lt;li>
&lt;p>Sentiment analysis indicates that the plan emphasizes &lt;strong>positive sentiments&lt;/strong>, using terms such as &lt;em>rights&lt;/em>, &lt;em>capabilities&lt;/em>, and &lt;em>strengthen&lt;/em>.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>Includes topics related to education and sexual diversity, which are not widely addressed in other plans.&lt;/p>
&lt;/li>
&lt;/ul>
&lt;h3 id="partido-morado">Partido Morado&lt;/h3>
&lt;ul>
&lt;li>
&lt;p>This government plan closely resembles others by extensively addressing &lt;strong>common topics in government plans&lt;/strong> (e.g., &lt;em>health&lt;/em>, &lt;em>education&lt;/em>, &lt;em>services&lt;/em>, etc.) without adding or omitting much compared to other plans.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>However, it also addresses unique topics, though in a less detailed manner, such as &lt;strong>support for talent and sports, republicanism, leveraging the fourth industrial revolution, animal abuse prevention, support for families and adolescents&lt;/strong>, among others.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>Sentiment analysis shows a &lt;strong>strong emphasis on positive sentiments&lt;/strong>, making little reference (as a proportion of total words) to social problems or negative words such as &lt;em>poverty&lt;/em>, &lt;em>risk&lt;/em>, or &lt;em>diseases&lt;/em>.&lt;/p>
&lt;/li>
&lt;/ul>
&lt;h3 id="podemos">Podemos&lt;/h3>
&lt;ul>
&lt;li>
&lt;p>The plan prominently references &lt;strong>tax relief&lt;/strong> and &lt;strong>business support&lt;/strong> (e.g., &lt;em>IGV&lt;/em>, &lt;em>businesses&lt;/em>, &lt;em>debts&lt;/em>, &lt;em>payrolls&lt;/em>, &lt;em>SMEs [PYME]&lt;/em>, &lt;em>limited liability enterprises [EIRLS]&lt;/em>, &lt;em>mortgages&lt;/em>, &lt;em>collections&lt;/em>, etc.). Additionally, it highlights &lt;strong>remote services&lt;/strong> (e.g., &lt;em>telemedicine&lt;/em>, &lt;em>tele-education&lt;/em>).&lt;/p>
&lt;/li>
&lt;li>
&lt;p>Sentiment analysis indicates a &lt;strong>strong emphasis on negative sentiments&lt;/strong>, frequently using words related to shortcomings and problems (e.g., &lt;em>decline&lt;/em>, &lt;em>crisis&lt;/em>, &lt;em>debts&lt;/em>, etc.).&lt;/p>
&lt;/li>
&lt;/ul>
&lt;h3 id="victoria-nacional">Victoria Nacional&lt;/h3>
&lt;ul>
&lt;li>
&lt;p>This government plan places a strong focus on &lt;strong>projects&lt;/strong> (e.g., &lt;em>gas&lt;/em>, &lt;em>crude oil&lt;/em>, &lt;em>supply chains&lt;/em>, &lt;em>infrastructure&lt;/em>, etc.) and &lt;strong>judicial topics&lt;/strong> (e.g., &lt;em>law&lt;/em>, &lt;em>juries&lt;/em>, &lt;em>crimes against humanity&lt;/em>, &lt;em>penal court&lt;/em>, &lt;em>international criminal court&lt;/em>, etc.). Notably, Forzyth has recently mentioned plans to reform the Peruvian judicial system.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>Sentiment analysis shows a &lt;strong>balanced use of positive and negative sentiments&lt;/strong>. While it includes words related to &lt;strong>problems&lt;/strong> (e.g., &lt;em>lack&lt;/em>, &lt;em>poverty&lt;/em>), it also incorporates an equal number of terms related to &lt;strong>projects&lt;/strong> (e.g., &lt;em>reform&lt;/em>, &lt;em>sustainable&lt;/em>, &lt;em>competencies&lt;/em>, etc.).&lt;/p>
&lt;/li>
&lt;/ul>
&lt;h1 id="final-conclusion">Final Conclusion&lt;/h1>
&lt;p>This text analysis of the 2021 Peruvian presidential election government plans offers a detailed comparison of the linguistic and thematic elements used by the six major political parties. The primary goal was to uncover distinct patterns, highlight the emotional tone, and identify the focus areas of each party while remaining impartial.&lt;/p>
&lt;h3 id="tools-used">Tools Used&lt;/h3>
&lt;p>The analysis was conducted using the following tools and libraries:&lt;/p>
&lt;ul>
&lt;li>&lt;strong>Text Mining Tools&lt;/strong>: &lt;code>tidytext&lt;/code>, &lt;code>widyr&lt;/code>, &lt;code>igraph&lt;/code>, &lt;code>ggraph&lt;/code>, and &lt;code>wordcloud2&lt;/code> for processing, tokenization, and visualization of textual data.&lt;/li>
&lt;li>&lt;strong>Visualization Libraries&lt;/strong>: &lt;code>ggplot2&lt;/code> and &lt;code>GGally&lt;/code> for plotting sentiment trends, correlations, and word frequencies.&lt;/li>
&lt;li>&lt;strong>Sentiment Analysis&lt;/strong>: Using a custom sentiment dictionary, the analysis classified words into positive or negative categories and calculated sentiment scores for each party.&lt;/li>
&lt;li>&lt;strong>TF-IDF Analysis&lt;/strong>: To highlight words unique to each government plan, we implemented the Term Frequency-Inverse Document Frequency (TF-IDF) methodology, filtering out common terms across all plans.&lt;/li>
&lt;li>&lt;strong>Data Wrangling&lt;/strong>: &lt;code>tidyverse&lt;/code> libraries for organizing, cleaning, and summarizing data.&lt;/li>
&lt;/ul>
&lt;h3 id="key-insights">Key Insights&lt;/h3>
&lt;ol>
&lt;li>&lt;strong>Common Themes&lt;/strong>: Across all plans, terms related to education, health, economic recovery, and governance were prevalent, emphasizing their broad appeal and political salience.&lt;/li>
&lt;li>&lt;strong>Sentiment Distribution&lt;/strong>: While most parties addressed similar issues, their emotional framing varied. &lt;strong>Juntos por el Perú&lt;/strong> and &lt;strong>Partido Morado&lt;/strong> stood out for their positive sentiment, emphasizing rights and progressive reforms, whereas &lt;strong>Podemos&lt;/strong> and &lt;strong>Acción Popular&lt;/strong> leaned towards negative sentiments, focusing on crisis and problems. This divergence highlights strategic attempts to evoke specific emotional responses from their audience.&lt;/li>
&lt;li>&lt;strong>Distinct Focus Areas&lt;/strong>:
&lt;ul>
&lt;li>&lt;strong>Acción Popular&lt;/strong> emphasized pension reform and taxation.&lt;/li>
&lt;li>&lt;strong>Fuerza Popular&lt;/strong> focused on social assistance and small business support, including pandemic-related issues.&lt;/li>
&lt;li>&lt;strong>Juntos por el Perú&lt;/strong> highlighted minority rights and social equality, with a unique focus on education and sexual diversity.&lt;/li>
&lt;li>&lt;strong>Partido Morado&lt;/strong> addressed common governance topics but also touched on innovation, republican values, and family support.&lt;/li>
&lt;li>&lt;strong>Podemos&lt;/strong> prioritized tax relief and remote services like telemedicine and tele-education.&lt;/li>
&lt;li>&lt;strong>Victoria Nacional&lt;/strong> focused on infrastructure projects and judicial reform.&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;strong>TF-IDF Highlights&lt;/strong>: This analysis employed advanced text-mining techniques such as TF-IDF to identify distinct patterns in government plans, allowing for a more nuanced understanding beyond mere descriptive analysis. These techniques were essential for filtering out generic terms and spotlighting unique priorities, enabling the extraction of actionable insights. Additionally, sentiment analysis provided a structured way to interpret the emotional undertones in each document, offering a comprehensive picture of the strategies employed by political parties. Together, these approaches demonstrate the power of data-driven methods in uncovering meaningful patterns in complex textual data.&lt;/li>
&lt;li>&lt;strong>Correlations&lt;/strong>: &lt;strong>Partido Morado&lt;/strong> showed the highest overlap in vocabulary with other parties, indicating thematic alignment, while others demonstrated distinct linguistic patterns.&lt;/li>
&lt;/ol>
&lt;h3 id="implications">Implications&lt;/h3>
&lt;p>This analysis provides voters and researchers with a structured overview of the linguistic and thematic strategies employed in political discourse. It highlights the importance of sentiment and word frequency analysis in understanding how political parties frame their priorities and connect with their audience. Additionally, by identifying unique terms through TF-IDF, we can better distinguish the distinctive focuses of each party, beyond the generic promises common in election campaigns.&lt;/p>
&lt;p>These results demonstrate the potential to extract key terms from diverse texts, providing valuable input for Machine Learning or AI systems. By leveraging this structured data, such systems can organize and interpret multiple documents more accurately, minimizing the risk of hallucinations and enhancing overall reliability.&lt;/p>
&lt;p>By combining qualitative interpretation with robust text analysis tools, this study underscores the power of data-driven approaches in political and social research.&lt;/p>
&lt;p>&lt;strong>Final Note&lt;/strong>: This analysis reveals a common bias in political research: an overemphasis on urban areas and mainstream perspectives. The victory of a smaller party campaigning in rural Peru demonstrates the importance of considering diverse regions and populations in political studies. This lesson emphasizes the need for inclusive research methods that capture the full complexity of political dynamics.&lt;/p>
&lt;h1 id="election-results-update">Election Results Update&lt;/h1>
&lt;p>The 2021 Peruvian general elections resulted in a significant political shift. &lt;strong>Pedro Castillo&lt;/strong>, representing &lt;strong>Perú Libre&lt;/strong>, narrowly won the presidency with 50.13% of the votes in the second round, defeating &lt;strong>Keiko Fujimori&lt;/strong> of &lt;strong>Fuerza Popular&lt;/strong>, who secured 49.87%. This tight margin highlights the country’s deep political polarization.&lt;/p>
&lt;p>In the congressional elections, the distribution of seats presents a fragmented political landscape. &lt;strong>Perú Libre&lt;/strong> emerged as the largest single party with 37 seats, followed by &lt;strong>Fuerza Popular&lt;/strong> with 24 seats. Other notable parties include &lt;strong>Acción Popular&lt;/strong> (16 seats), &lt;strong>Alianza para el Progreso&lt;/strong> (15 seats), and &lt;strong>Renovación Popular&lt;/strong> (13 seats). Smaller parties such as &lt;strong>Juntos por el Perú&lt;/strong>, &lt;strong>Somos Perú&lt;/strong>, and &lt;strong>Podemos Perú&lt;/strong> captured fewer seats, reflecting diverse political representation.&lt;/p>
&lt;p>&lt;img src="https://luis-zapatabobadilla.netlify.app/project/presidential-elections-analysis/index.en_files/figure-html/unnamed-chunk-15-1.png" width="672" />&lt;/p>
&lt;p>This demonstrates the electorate’s divided support across a wide range of ideologies and priorities, showcasing the complexity of Peru’s political landscape.
The fragmented composition of Peru’s Congress, with no party holding a clear majority, has significantly contributed to the nation’s political instability in recent years. This division has made coalition-building and legislative consensus challenging, reflecting the electorate’s diverse ideological preferences. The lack of a dominant party in Congress set the stage for subsequent turmoil, including President Pedro Castillo’s failed attempt to dissolve Congress in December 2022, which led to his impeachment and arrest. This event further exacerbated the political crisis, resulting in a government perceived as lacking broad representation and struggling to achieve stability.&lt;/p>
&lt;p>Among the parties analyzed in the blog, &lt;strong>Fuerza Popular&lt;/strong>, &lt;strong>Acción Popular&lt;/strong>, &lt;strong>Podemos Perú&lt;/strong>, &lt;strong>Juntos por el Perú&lt;/strong>, and &lt;strong>Partido Morado&lt;/strong> were central to the textual and sentiment analysis. Their performance in the election was varied, reflecting the disconnect between campaign messaging and voter behavior.&lt;/p>
&lt;ol>
&lt;li>&lt;strong>Fuerza Popular&lt;/strong> secured 24 seats in Congress, demonstrating its ability to maintain a significant political presence. Its campaign, which balanced both negative and positive sentiments, might have appealed to voters seeking stability amid economic and social challenges.&lt;/li>
&lt;/ol>
&lt;p>Fuerza Popular’s discourse reflects a balance between addressing immediate societal challenges and proposing support-based solutions. Key words like “pobreza” (poverty), “crecimiento” (growth), “rescate” (rescue), and “defendemos” (we defend) reveal a focus on societal problems and the promise of interventions. Additionally, terms such as “segmentos poblacionales” (population segments) and “programas sociales” (social programs) suggest a tailored approach to addressing diverse needs, potentially resonating with voters concerned about inclusivity and systemic support. The emphasis on “infectados” (infected) and “pruebas” (tests) highlights an active response to pandemic-related challenges, a pressing issue during the election. These targeted messages, combined with a balance of positive sentiments such as “derecho” (rights) and negative sentiments addressing critical issues, may have attracted voters seeking pragmatic and immediate solutions to national crises. This blend of problem acknowledgment and actionable solutions likely positioned Fuerza Popular as a relatable choice for many Peruvians.&lt;/p>
&lt;ol start="2">
&lt;li>
&lt;p>&lt;strong>Acción Popular&lt;/strong>, with 16 seats, highlighted pensions and social reforms, consistent with its focus on words like &lt;em>reforma&lt;/em> (reform) and &lt;em>sostenible&lt;/em> (sustainable). However, its emphasis on negative sentiments may have limited broader appeal.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Podemos Perú&lt;/strong> captured only five seats, possibly due to its strong focus on tax relief and economic challenges but a heavier reliance on negative sentiments like &lt;em>deudas&lt;/em> (debts) and &lt;em>crisis&lt;/em> (crisis).&lt;/p>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Juntos por el Perú&lt;/strong> obtained five seats despite its strong emphasis on social rights and positive sentiments, which were reflected in its use of terms like &lt;em>derechos&lt;/em> (rights) and &lt;em>capacidad&lt;/em> (capacity). This outcome suggests that its appeal may have been concentrated in specific demographic or ideological niches.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Partido Morado&lt;/strong>, with three seats, showed alignment with themes of innovation and republicanism but struggled to resonate broadly, as indicated by its minimal representation in Congress.&lt;/p>
&lt;/li>
&lt;/ol>
&lt;p>The &lt;strong>Partido Morado&lt;/strong> focused on a highly positive discourse, emphasizing concepts like “reforma” (reform), “sostenible” (sustainable), “servicio” (service), and “derechos” (rights), which aligned with progressive and optimistic sentiments. Its unique themes included “servicios digitales” (digital services), “manifestaciones culturales” (cultural manifestations), and “republicanismo” (republicanism), as well as topics like animal welfare and environmental concerns. These ideas reflected a forward-thinking and modern platform.&lt;/p>
&lt;p>However, the party’s discourse may have struggled to resonate with the broader Peruvian electorate for a few reasons. First, its topics, while innovative, might have seemed distant or abstract to voters concerned with immediate and tangible issues like poverty and crisis, which were heavily addressed by other parties like &lt;strong>Fuerza Popular&lt;/strong>. Second, the highly technical or niche focus on topics like “datos abiertos” (open data) and “biomasa” (biomass) might not have connected with the needs or priorities of rural or economically vulnerable populations. Lastly, the lack of significant negative sentiments in their plan may have made it seem disconnected from the reality of many voters who were experiencing hardship and expected a party to explicitly address such struggles.&lt;/p>
&lt;p>Ultimately, &lt;strong>Partido Morado’s&lt;/strong> progressive and technocratic approach, while valuable, might have been perceived as elitist or overly idealistic, limiting its appeal among a diverse electorate facing immediate socio-economic challenges.&lt;/p>
&lt;p>These results underscore the complexities of Peruvian voter preferences, which favored &lt;strong>Perú Libre&lt;/strong>—a party not initially included in the blog’s analysis. This demonstrates the challenges of relying solely on media and surveys centered in Lima, highlighting the importance of addressing the full spectrum of voter priorities, particularly in rural areas.&lt;/p></description></item><item><title>Hello R Markdown</title><link>https://luis-zapatabobadilla.netlify.app/post/2020-12-01-r-rmarkdown/</link><pubDate>Thu, 01 Dec 2022 21:13:14 -0500</pubDate><guid>https://luis-zapatabobadilla.netlify.app/post/2020-12-01-r-rmarkdown/</guid><description>
&lt;div id="r-markdown" class="section level1">
&lt;h1>R Markdown&lt;/h1>
&lt;p>This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see &lt;a href="http://rmarkdown.rstudio.com" class="uri">http://rmarkdown.rstudio.com&lt;/a>.&lt;/p>
&lt;p>You can embed an R code chunk like this:&lt;/p>
&lt;pre class="r">&lt;code>summary(cars)
## speed dist
## Min. : 4.0 Min. : 2.00
## 1st Qu.:12.0 1st Qu.: 26.00
## Median :15.0 Median : 36.00
## Mean :15.4 Mean : 42.98
## 3rd Qu.:19.0 3rd Qu.: 56.00
## Max. :25.0 Max. :120.00
fit &amp;lt;- lm(dist ~ speed, data = cars)
fit
##
## Call:
## lm(formula = dist ~ speed, data = cars)
##
## Coefficients:
## (Intercept) speed
## -17.579 3.932&lt;/code>&lt;/pre>
&lt;/div>
&lt;div id="including-plots" class="section level1">
&lt;h1>Including Plots&lt;/h1>
&lt;p>You can also embed plots. See Figure &lt;a href="#fig:pie">1&lt;/a> for example:&lt;/p>
&lt;pre class="r">&lt;code>par(mar = c(0, 1, 0, 1))
pie(
c(280, 60, 20),
c(&amp;#39;Sky&amp;#39;, &amp;#39;Sunny side of pyramid&amp;#39;, &amp;#39;Shady side of pyramid&amp;#39;),
col = c(&amp;#39;#0292D8&amp;#39;, &amp;#39;#F7EA39&amp;#39;, &amp;#39;#C4B632&amp;#39;),
init.angle = -50, border = NA
)&lt;/code>&lt;/pre>
&lt;div class="figure">&lt;span style="display:block;" id="fig:pie">&lt;/span>
&lt;img src="https://luis-zapatabobadilla.netlify.app/post/2020-12-01-r-rmarkdown/index.en_files/figure-html/pie-1.png" alt="A fancy pie chart." width="672" />
&lt;p class="caption">
Figure 1: A fancy pie chart.
&lt;/p>
&lt;/div>
&lt;/div></description></item><item><title>Webscraping 201</title><link>https://luis-zapatabobadilla.netlify.app/project/webscraping-201/</link><pubDate>Sun, 19 Sep 2021 00:00:00 +0000</pubDate><guid>https://luis-zapatabobadilla.netlify.app/project/webscraping-201/</guid><description>&lt;p>More and more central government institutions are centralizing their main websites on the &lt;a href="www.gob.pe">www.gob.pe&lt;/a> platform. While the government also has a dedicated data website (&lt;a href="https://www.datosabiertos.gob.pe/" target="_blank" rel="noopener">Open Data Platform&lt;/a>), unstructured information (like reports or PDFs) often contains more details.&lt;/p>
&lt;p>For this example, we will retrieve the links to daily temperature reports from the main ports of the country, which are published daily in the &lt;strong>Daily Oceanographic Bulletin&lt;/strong> by IMARPE and made available on the government website. Since individual links do not follow a simple query structure, it is not possible to predict the daily URL. Therefore, we will use the government&amp;rsquo;s search tool to obtain the daily links.&lt;/p>
&lt;h2 id="gobpe-search-tool">Gob.pe Search Tool&lt;/h2>
&lt;p>To scrape information from the government website, we will use its search tool. This tool also operates with a query mechanism, simplifying the search process.&lt;/p>
&lt;p>To review the parameters used, visit &lt;a href="http://www.gob.pe">www.gob.pe&lt;/a> and search for the desired information. At first glance, the query starts with the term &lt;strong>/busquedas?&lt;/strong>.&lt;/p>
&lt;p>For example, if we need to view IMARPE&amp;rsquo;s latest publications within a defined interval, we use the query:&lt;/p>
&lt;p>We start with &lt;strong>/busquedas?&lt;/strong> to indicate we are using the search tool, followed by the type of content, which in this case is publications: &lt;strong>contenido[]=publicaciones&lt;/strong>, and the institution: &lt;strong>institucion[]=imarpe&lt;/strong>.&lt;/p>
&lt;p>Next, we specify the search parameters. To define a time interval, we use the parameters &lt;code>desde&lt;/code> (from) and &lt;code>hasta&lt;/code> (to): &lt;strong>desde=04-07-2018&amp;amp;hasta=16-09-2021&lt;/strong>. Since IMARPE also publishes weekly reports, we include a term to filter results with the word &amp;ldquo;diario&amp;rdquo; (daily): &lt;strong>term=Diario&lt;/strong>.&lt;/p>
&lt;p>Thus, the data request URL would be as follows:&lt;/p>
&lt;blockquote>
&lt;p>&lt;a href="https://www.gob.pe/">https://www.gob.pe/&lt;/a>&lt;strong>busquedas?&lt;strong>contenido[]&lt;/strong>=publicaciones&lt;/strong>&amp;amp;institucion[]&lt;strong>=imarpe&lt;/strong>&amp;amp;desde**=04-09-2021**&amp;amp;hasta**=16-09-2021**&amp;amp;term=**Diario**&lt;/p>
&lt;/blockquote>
&lt;p>Entering this address into a web browser directs us to IMARPE&amp;rsquo;s latest daily bulletin publications. This approach can be adapted to various types of information across institutions by experimenting with the search tool and reviewing the query.&lt;/p>
&lt;p>This allows us to access the daily bulletin publications.&lt;/p>
&lt;h2 id="webscraping-with-rvest">Webscraping with Rvest&lt;/h2>
&lt;p>With the web address defined, we proceed to retrieve the links to each publication.&lt;/p>
&lt;pre>&lt;code class="language-r">path = &amp;quot;https://www.gob.pe/busquedas?contenido[]=publicaciones&amp;amp;institucion[]=imarpe&amp;amp;reason=sheet&amp;amp;sheet=1&amp;quot;
&lt;/code>&lt;/pre>
&lt;p>For web scraping, we will use the &lt;strong>Rvest&lt;/strong> library, which provides tools to read the HTML content of a webpage and extract information, such as URLs. The tool to download HTML content from a web address is &lt;strong>read_html&lt;/strong>.&lt;/p>
&lt;pre>&lt;code class="language-r">library(tidyverse)
library(lubridate)
library(stringr)
library(rvest)
imarpe = read_html(path)
imarpe
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## {html_document}
## &amp;lt;html lang=&amp;quot;es-pe&amp;quot;&amp;gt;
## [1] &amp;lt;head&amp;gt;\n&amp;lt;meta http-equiv=&amp;quot;Content-Type&amp;quot; content=&amp;quot;text/html; charset=UTF-8 ...
## [2] &amp;lt;body&amp;gt;\n&amp;lt;!-- Google Tag Manager (noscript) --&amp;gt;\n &amp;lt;noscript&amp;gt;&amp;lt;iframe s ...
&lt;/code>&lt;/pre>
&lt;p>Using the &lt;strong>read_html&lt;/strong> function on the Peruvian government results webpage, we obtain a set of HTML information stored in the variable &lt;em>imarpe&lt;/em>.&lt;/p>
&lt;p>The variable &lt;em>imarpe&lt;/em> now contains a set of instructions for web browsers, organized in various tags. To extract the tags, we use the &lt;strong>html_head&lt;/strong> function, and to retrieve the text within these tags, we use the &lt;strong>html_text&lt;/strong> function. Next, we use text extraction functions (refer to Regex on Google) to extract the URLs of IMARPE publications using text patterns.&lt;/p>
&lt;pre>&lt;code class="language-r">listas = imarpe %&amp;gt;%
html_node(&amp;quot;head&amp;quot;) %&amp;gt;% # Extract URLs from the head section
html_text() %&amp;gt;%
str_extract_all(paste(&amp;quot;href(.*?)&amp;quot;,year(today()),sep=&amp;quot;&amp;quot;)) %&amp;gt;% # Pattern: Starts with href and ends with 2021
as.data.frame(col.names = &amp;quot;Text&amp;quot;) %&amp;gt;%
as_tibble() %&amp;gt;%
filter(str_detect(Text, pattern = &amp;quot;diario&amp;quot;)) %&amp;gt;% # Filter URLs containing &amp;quot;diario&amp;quot;
mutate(Text = paste(&amp;quot;https://www.gob.pe&amp;quot;,
str_remove_all(Text, &amp;quot;href=\\\\\\\&amp;quot;&amp;quot;),
sep = &amp;quot;&amp;quot;)) %&amp;gt;% # Convert to full web address
mutate(Date = dmy(str_sub(Text, -10, -1))) %&amp;gt;% # Extract the date
arrange(Date)
imarpe %&amp;gt;%
html_node(&amp;quot;head&amp;quot;) %&amp;gt;% # Extract URLs from the head section
html_text() %&amp;gt;%
str_extract_all(&amp;quot;href(.*?)2024&amp;quot;) %&amp;gt;% # Pattern: Starts with href and ends with 2021
as.data.frame(col.names = &amp;quot;Text&amp;quot;) %&amp;gt;%
as_tibble() %&amp;gt;%
filter(str_detect(Text, pattern = &amp;quot;diario&amp;quot;))
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## # A tibble: 2 × 1
## Text
## &amp;lt;chr&amp;gt;
## 1 &amp;quot;href=\\\&amp;quot;/institucion/imarpe/informes-publicaciones/6204259-boletin-diario-o…
## 2 &amp;quot;href=\\\&amp;quot;/institucion/imarpe/informes-publicaciones/6200693-boletin-diario-o…
&lt;/code>&lt;/pre>
&lt;p>To process the text, we must first review the HTML text and its characteristics. The text processing functions are as follows:&lt;/p>
&lt;ul>
&lt;li>
&lt;p>First, extract text (&lt;strong>str_extract_all&lt;/strong>) that starts with &lt;strong>href&lt;/strong> (the tag indicating a URL in HTML) and ends with &lt;strong>2021&lt;/strong> (the web addresses of interest include the year in their query). Using Regex, the dot (.) matches all characters. The asterisk (*) matches one or more, while the question mark ensures that the Regex is not greedy (captures the minimum number of characters possible to end before 2021).&lt;/p>
&lt;/li>
&lt;li>
&lt;p>Convert the extracted vectors into a dataset.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>Filter URLs containing the word &amp;ldquo;&lt;strong>diario&lt;/strong>&amp;rdquo; since we are looking for IMARPE&amp;rsquo;s &lt;strong>Daily Oceanographic Bulletins&lt;/strong>, which include this word in their URLs.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>Remove the &lt;strong>href&lt;/strong> HTML tag from the text using the &lt;strong>str_remove_all&lt;/strong> function.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>Extract the dates by taking the last 10 characters of the URL (the query includes the date at the end of the URL).&lt;/p>
&lt;/li>
&lt;/ul>
&lt;pre>&lt;code class="language-r">listas
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## # A tibble: 2 × 2
## Text Date
## &amp;lt;chr&amp;gt; &amp;lt;date&amp;gt;
## 1 https://www.gob.pe/institucion/imarpe/informes-publicaciones/62006… 2024-11-19
## 2 https://www.gob.pe/institucion/imarpe/informes-publicaciones/62042… 2024-11-20
&lt;/code>&lt;/pre>
&lt;p>This provides a list of URLs, which can later be used to download each publication.&lt;/p>
&lt;blockquote>
&lt;p>Rvest is not the only method for web scraping with R. Additionally, more advanced tools, such as headless browsers (simulated web browsers capable of clicking and entering data like a normal browser), can be used. Examples include &lt;strong>Rselenium&lt;/strong> (more complex) or &lt;strong>Webdriver&lt;/strong> (simpler).&lt;/p>
&lt;/blockquote>
&lt;h2 id="conclusion">Conclusion&lt;/h2>
&lt;p>Using web scraping techniques and text manipulation, it is possible to extract the URLs of IMARPE publications via the search tool on the government website (&lt;a href="http://www.gob.pe">www.gob.pe&lt;/a>).&lt;/p>
&lt;p>Using similar web scraping techniques, each publication can be accessed through a download loop to retrieve the uploaded information, which will be demonstrated in a future post.&lt;/p></description></item><item><title>Office Skills with Word</title><link>https://luis-zapatabobadilla.netlify.app/project/office-skills-with-word/</link><pubDate>Fri, 02 Jul 2021 00:00:00 +0000</pubDate><guid>https://luis-zapatabobadilla.netlify.app/project/office-skills-with-word/</guid><description>&lt;h1 id="tips-for-office-skills-in-microsoft-word">Tips for Office Skills in Microsoft Word&lt;/h1>
&lt;p>Word is the text processing tool in Microsoft Office, frequently used to create documents. While it is very user-friendly, there are some tips to accelerate text editing. This can be particularly important when regularly working with a large number of documents.&lt;/p>
&lt;h2 id="word-shortcuts">Word Shortcuts&lt;/h2>
&lt;ol>
&lt;li>
&lt;p>&lt;strong>You can select a sentence within a paragraph by pressing &amp;ldquo;Ctrl + Click&amp;rdquo;&lt;/strong>. This allows you to quickly select a sentence, for example, when you want the first sentence to be bold (&lt;strong>Ctrl + B&lt;/strong>).&lt;/p>
&lt;/li>
&lt;li>
&lt;p>You can move any selection by dragging it with the mouse.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>Use the combination &amp;ldquo;&lt;strong>Alt + Shift + Arrow Up/Down&lt;/strong>&amp;rdquo; to move a paragraph.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>Justify a paragraph with the combination &amp;ldquo;&lt;strong>Ctrl + J&lt;/strong>.&amp;rdquo;&lt;/p>
&lt;/li>
&lt;li>
&lt;p>Adjust line spacing using different combinations: &lt;strong>&amp;ldquo;Ctrl + 1&amp;rdquo;&lt;/strong> (single spacing), &lt;strong>&amp;ldquo;Ctrl + 2&amp;rdquo;&lt;/strong> (double spacing), &lt;strong>&amp;ldquo;Ctrl + 5&amp;rdquo;&lt;/strong> (1.5 spacing), and &lt;strong>&amp;ldquo;Ctrl + 0&amp;rdquo;&lt;/strong> (adds a blank line before the paragraph).&lt;/p>
&lt;/li>
&lt;li>
&lt;p>Delete text faster (word by word instead of letter by letter) by pressing &lt;strong>&amp;ldquo;Ctrl + DELETE&amp;rdquo;&lt;/strong> or &lt;strong>&amp;ldquo;Ctrl + BACKSPACE&amp;rdquo;&lt;/strong>.&lt;/p>
&lt;p>&lt;img src="Imagen1.png" alt="">&lt;/p>
&lt;/li>
&lt;li>
&lt;p>The &lt;strong>Clipboard&lt;/strong> stores all copied items in chronological order. Access it by clicking the arrow in the lower-right corner of the &lt;strong>Clipboard&lt;/strong> section under &lt;strong>Home&lt;/strong>.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>Insert a page break with the combination &amp;ldquo;&lt;strong>Ctrl + Enter&lt;/strong>.&amp;rdquo;&lt;/p>
&lt;/li>
&lt;/ol>
&lt;h2 id="styles">Styles&lt;/h2>
&lt;p>Manually changing formatting repeatedly can be inefficient. You can save formatting to reuse in the future. Styles are located under the &lt;strong>Home&lt;/strong> tab in the &lt;strong>Styles&lt;/strong> section.&lt;/p>
&lt;p>&lt;img src="Imagen2.png" alt="">&lt;/p>
&lt;p>Modify a style by right-clicking it and selecting &amp;ldquo;Modify.&amp;rdquo; You can adjust indentation, justification, font type, font size, and more. You can also select all instances (paragraphs) where the style is used.&lt;/p>
&lt;p>The following video explains the process well:&lt;/p>
&lt;iframe width="560" height="315" src="https://www.youtube.com/embed/TQb1k1-iDfM" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen>
&lt;/iframe>
&lt;p>You can also update a style to match an existing paragraph. Select the paragraph and, in the &lt;strong>Styles&lt;/strong> section, right-click the style, choosing &lt;strong>&amp;ldquo;Update &amp;hellip; to Match Selection&amp;rdquo;&lt;/strong>.&lt;/p>
&lt;p>Additionally, you can &lt;strong>create a new style&lt;/strong>. Select the paragraph with the modified style, and a window will appear with options. Click on &lt;strong>Styles&lt;/strong> and then &lt;strong>Create Style&lt;/strong>. This allows new text to adopt the predefined style.&lt;/p>
&lt;p>Styles can be saved for the current document or for all documents created using the same template.&lt;/p>
&lt;h2 id="locking-styles">Locking Styles&lt;/h2>
&lt;p>An organization may require a corporate format template and prevent modifications to the formatting. In this case, you can lock the style settings. Note that this will restrict changes to font type, size, spacing, indentation, etc., except for the predefined styles. Ensure all required styles are created before locking.&lt;/p>
&lt;p>To lock formatting, go to &lt;strong>Review&lt;/strong>, click on &lt;strong>Restrict Editing&lt;/strong> under &lt;strong>Protect&lt;/strong>, and a window will open on the left. Choose &lt;strong>Formatting Restrictions&lt;/strong> and its settings.&lt;/p>
&lt;p>&lt;img src="imagen3.png" alt="">&lt;/p>
&lt;p>In the settings, deselect all styles except the corporate ones previously created.&lt;/p>
&lt;p>Finally, you will see three format options, including &amp;ldquo;Block Theme or Scheme Changes&amp;rdquo; and &amp;ldquo;Prevent Quick Style Set Changes.&amp;rdquo; The first prevents theme changes (set of styles), and the second blocks changes to quick styles. It is recommended to enable both.&lt;/p>
&lt;p>Press &amp;ldquo;&lt;strong>Yes, Apply Protection&lt;/strong>&amp;rdquo; to finalize. Optionally, Word allows you to create a password to prevent disabling the formatting restrictions.&lt;/p>
&lt;h2 id="ruler">Ruler&lt;/h2>
&lt;p>Clicking on &lt;strong>the ruler&lt;/strong> (above the document) will create an &amp;ldquo;L&amp;rdquo; marker. This marker sets where the cursor moves after pressing &lt;strong>Tab&lt;/strong>. Clicking on the symbol to the left of the ruler changes it to an inverted &amp;ldquo;T.&amp;rdquo; Clicking on the ruler again adds another marker, indicating where the cursor will move (centered). This is a simple way to center titles and content. Experiment with various symbols and ruler functions.&lt;/p>
&lt;h2 id="titles-for-figurestables">Titles for Figures/Tables&lt;/h2>
&lt;p>You can add titles to figures and tables. The title formatting can also be modified under the &lt;strong>Styles&lt;/strong> tab. This allows for numbering figures and tables and implementing a list of figures and tables.&lt;/p>
&lt;p>Sources:&lt;/p>
&lt;ul>
&lt;li>
&lt;p>&lt;a href="http://www.reading.ac.uk/web/files/its/WordEssen13.pdf" target="_blank" rel="noopener">Microsoft Word 2013 A Beginners' Guide (reading.ac.uk)&lt;/a>&lt;/p>
&lt;/li>
&lt;li>
&lt;p>&lt;a href="http://www.reading.ac.uk/web/files/its/WordInter13_2.pdf" target="_blank" rel="noopener">Microsoft Word 2013 An Intermediate Guide (reading.ac.uk)&lt;/a>&lt;/p>
&lt;/li>
&lt;li>
&lt;p>&lt;a href="http://www.reading.ac.uk/web/files/its/Graphics2013.pdf" target="_blank" rel="noopener">Microsoft Word 2013 Graphics (reading.ac.uk)&lt;/a>&lt;/p>
&lt;/li>
&lt;li>
&lt;p>&lt;a href="https://wordexperto.com/2020/05/28/proteger-documentos-restringir-estilos/" target="_blank" rel="noopener">Protect Documents, Restrict Styles - WordExperto&lt;/a>&lt;/p>
&lt;/li>
&lt;li>
&lt;p>&lt;a href="https://wordexperto.com/2016/02/08/por-que-usar-estilos/" target="_blank" rel="noopener">Reasons to Use Styles Instead of Direct Formatting (wordexperto.com)&lt;/a>&lt;/p>
&lt;/li>
&lt;/ul></description></item><item><title>Webscraping 101</title><link>https://luis-zapatabobadilla.netlify.app/project/webscraping-101/</link><pubDate>Sun, 28 Mar 2021 00:00:00 +0000</pubDate><guid>https://luis-zapatabobadilla.netlify.app/project/webscraping-101/</guid><description>&lt;p>The internet offers a wealth of free and easily accessible information. There are two types of available data: data that can be easily downloaded through a &amp;ldquo;&lt;em>download&lt;/em>&amp;rdquo; button and data visible on web pages.&lt;/p>
&lt;p>To obtain both types of data, it is not necessary to manually download them. It is possible to automate the process through code.&lt;/p>
&lt;p>In this post, I will introduce how to download the first type of data (data requiring only pressing a &amp;ldquo;&lt;em>download&lt;/em>&amp;rdquo; button) automatically via code. However, to achieve this, it is important to understand the mechanisms that enable downloading data online. Today, we will discuss two such mechanisms: the &lt;strong>POST&lt;/strong> and &lt;strong>GET&lt;/strong> methods.&lt;/p>
&lt;h2 id="http-get-and-post">HTTP: GET and POST&lt;/h2>
&lt;p>The &lt;strong>HTTP&lt;/strong> protocol is the communication protocol used by browsers to access web pages. HTTP regulates how the server (where the web page is hosted) sends resources to the client (the web browser). These resources contain the &amp;ldquo;&lt;em>instructions&lt;/em>&amp;rdquo; a web browser (e.g., Chrome) uses to display and interact with the web page.&lt;/p>
&lt;p>A &lt;strong>URL&lt;/strong> is a &lt;em>web address&lt;/em> that defines how a resource is located on the internet (e.g., &lt;a href="https://www.google.com">https://www.google.com&lt;/a>). When entering this address into a browser, it sends an HTTP request to the server, asking for the web resource (using a &lt;strong>GET&lt;/strong> or &lt;strong>POST&lt;/strong> method). The server receives the request, searches for the file in question (an HTML page, Excel file, etc.), and sends a &lt;strong>header&lt;/strong> back to the browser. The &lt;strong>header&lt;/strong> is essentially a message indicating whether the search was successful (whether the file exists). If successful, the server also sends the requested file.&lt;/p>
&lt;p>For data downloads, two primary HTTP methods are commonly used: &lt;strong>GET&lt;/strong> and &lt;strong>POST&lt;/strong>. The &lt;strong>GET&lt;/strong> method is used to &amp;ldquo;&lt;em>retrieve&lt;/em>&amp;rdquo; resources from the server via a request. The &lt;strong>POST&lt;/strong> method allows for &amp;ldquo;&lt;em>retrieving&lt;/em>&amp;rdquo; and &amp;ldquo;&lt;em>saving&lt;/em>&amp;rdquo; resources on the server by including additional data in the request.&lt;/p>
&lt;ul>
&lt;li>
&lt;p>&lt;strong>GET&lt;/strong>: This HTTP method is used to &lt;em>retrieve information&lt;/em> from a server. It sends a request to obtain a response (e.g., an Excel file or data we want to download) to the client (web page). A key feature of the GET method is that it allows the data to be transmitted &amp;ldquo;visibly&amp;rdquo; in the browser through the URL using &lt;strong>queries&lt;/strong>. A query is a message added to the &lt;strong>URL&lt;/strong> specifying the required information. For example, suppose we want to request visitor data for November from a hypothetical website, &lt;a href="http://www.luis.com">www.luis.com&lt;/a>. The variables might include &lt;code>variable = visits&lt;/code> and &lt;code>month = November&lt;/code>. The query would look like: &lt;a href="http://www.luis.com/">www.luis.com/&lt;/a>&lt;strong>download?variable=visits&amp;amp;month=november&lt;/strong>. The bold section is called the &lt;strong>query&lt;/strong>. This query sends the request to the server and receives a response in return (e.g., an Excel file). Each website has its own syntax for how to structure such requests.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>POST&lt;/strong>: Another HTTP method, which, unlike GET, &lt;em>sends information&lt;/em> to be processed and stored on the server. The POST method can also be used to download data. The uniqueness of POST for downloading data lies in the use of two URLs. This improves server security. To download a file with the POST method, a &lt;strong>query&lt;/strong> is sent similar to GET. However, instead of immediately providing a response, the server opens a &lt;em>temporary link&lt;/em> at another URL for the file download.&lt;/p>
&lt;/li>
&lt;/ul>
&lt;h3 id="example-of-downloading-with-get-and-post">Example of Downloading with GET and POST&lt;/h3>
&lt;p>To better understand the GET and POST protocols, we will use both methods to download data available on the &lt;a href="https://www.coes.org.pe/portal/" target="_blank" rel="noopener">COES&lt;/a> website. The site contains data that can be downloaded using both methods.&lt;/p>
&lt;h4 id="example-post-method">Example: POST Method&lt;/h4>
&lt;p>The COES Indicators Portal allows for downloading daily electricity production data up to the previous day.&lt;/p>
&lt;p>To access this section, go to the &lt;strong>Indicators Portal&lt;/strong> on the COES website. Clicking the export button sends a &lt;strong>query&lt;/strong> containing the selected date range in the &lt;strong>request&lt;/strong>, and in return, an Excel file with the data is provided. &lt;em>How do we determine whether the method is POST or GET?&lt;/em> It’s easy, using web analysis tools like the &lt;strong>Chrome Developer Tools&lt;/strong>.&lt;/p>
&lt;div class="figure" style="text-align: center">
&lt;img src="images/HTMLI.png" alt="Chrome Developer Tools" width="600px" />
&lt;p class="caption">&lt;span id="fig:unnamed-chunk-1">&lt;/span>Figure 1: Chrome Developer Tools&lt;/p>
&lt;/div>
&lt;p>Clicking on it reveals several tools, the most relevant being &lt;strong>Network&lt;/strong>. Selecting Network shows the interaction between our client (web page) and the COES server. First, click &lt;em>Clear&lt;/em> to clean up the workspace and focus on future interactions. Then, click the &lt;strong>Export&lt;/strong> button on the COES webpage (after selecting the date range) to download the Excel file. In the &lt;em>Network&lt;/em> area, two interactions appear. The presence of two interactions suggests the use of a POST method (one URL for sending and another for downloading).&lt;/p>
&lt;div class="figure" style="text-align: center">
&lt;img src="images/HTMLII.png" alt="Network" width="700px" />
&lt;p class="caption">&lt;span id="fig:unnamed-chunk-2">&lt;/span>Figure 2: Network&lt;/p>
&lt;/div>
&lt;p>Click the first interaction (&lt;strong>exportargeneracion&lt;/strong>) for more details. Since it’s the first interaction, it should contain the &lt;strong>request&lt;/strong> sent to the server.&lt;/p>
&lt;div class="figure" style="text-align: center">
&lt;img src="images/request.png" alt="Headers - POST" width="600px" />
&lt;p class="caption">&lt;span id="fig:unnamed-chunk-3">&lt;/span>Figure 3: Headers - POST&lt;/p>
&lt;/div>
&lt;p>We can see that the &lt;strong>Request Method&lt;/strong> is &lt;strong>POST&lt;/strong>. Additionally, the request URL is &lt;em>&amp;quot;&lt;a href="https://www.coes.org.pe/Portal/portalinformacion/exportargeneracion">https://www.coes.org.pe/Portal/portalinformacion/exportargeneracion&lt;/a>&amp;quot;&lt;/em>. Finally, the request sends three pieces of data: the start date (&lt;strong>fechaInicial&lt;/strong>), the end date (&lt;strong>fechaFinal&lt;/strong>), and an indicator (&lt;strong>indicador&lt;/strong>).&lt;/p>
&lt;p>Note the date format: &lt;em>day/month/year&lt;/em>, where both the day and month always have two digits. This format is crucial when sending the request.&lt;/p>
&lt;p>A &lt;strong>header&lt;/strong> acts as metadata (additional descriptive information) included in the request (request) and response. There are 15 &lt;strong>request headers&lt;/strong> in the image. While not mandatory, they can be helpful, as we will see later.&lt;/p>
&lt;p>Finally, the &lt;strong>Status Code = 200&lt;/strong> indicates a successful interaction.&lt;/p>
&lt;p>Thus, we can conclude that the method for obtaining this information is &lt;strong>POST&lt;/strong>, including the requested date range in the query.&lt;/p>
&lt;blockquote>
&lt;p>Since it’s a POST method, the request does not provide an immediate response. We must check the second interaction to find the URL for downloading the data.&lt;/p>
&lt;/blockquote>
&lt;p>Clicking on the second interaction (&lt;strong>descargargeneracion&lt;/strong>) reveals the following information:&lt;/p>
&lt;div class="figure" style="text-align: center">
&lt;img src="images/response.png" alt="Headers - GET" width="700px" />
&lt;p class="caption">&lt;span id="fig:unnamed-chunk-4">&lt;/span>Figure 4: Headers - GET&lt;/p>
&lt;/div>
&lt;p>Here, a &amp;ldquo;&lt;em>gateway&lt;/em>&amp;rdquo; to the data was opened at the URL: &amp;ldquo;&lt;a href="https://www.coes.org.pe/Portal/portalinformacion/descargargeneracion" target="_blank" rel="noopener">&lt;em>https://www.coes.org.pe/Portal/portalinformacion/descargargeneracion&lt;/em>&lt;/a>&amp;rdquo;. This interaction uses the GET method, meaning that entering the URL automatically retrieves the data from the server. Since the request data was already sent in the previous interaction, no additional &lt;strong>query&lt;/strong> is needed.&lt;/p>
&lt;h4 id="example-get-method">Example: GET Method&lt;/h4>
&lt;p>In this example, we will download data from the Daily Operation Evaluation Report (IEOD). This report provides more granular daily electricity consumption data, such as demand by geographic zones, large companies, resources, and more. To access this data, first, visit the IEOD platform and verify whether the download function uses &lt;strong>POST&lt;/strong> or &lt;strong>GET&lt;/strong>.&lt;/p>
&lt;div class="figure" style="text-align: center">
&lt;img src="images/IEOD_GET.png" alt="IEOD" width="500px" />
&lt;p class="caption">&lt;span id="fig:unnamed-chunk-5">&lt;/span>Figure 5: IEOD&lt;/p>
&lt;/div>
&lt;p>After selecting a date on the IEOD platform and choosing the desired Excel file (&amp;quot;&lt;strong>Anexo1_Resumen_0709.xlsx&lt;/strong>&amp;quot;), &lt;strong>right-click on the link&lt;/strong> to copy the URL. In this case, the copied URL is: &amp;ldquo;&lt;a href="https://www.coes.org.pe/portal/browser/">https://www.coes.org.pe/portal/browser/&lt;/a>&lt;strong>download?url=Post%20Operaci%C3%B3n%2FReportes%2FIEOD%2F2020%2F09%20Setiembre%2F07%2FAnexo1_Resumen_0709.xlsx&lt;/strong>&amp;rdquo;. From the bold portion, it is evident that this is a &lt;strong>GET&lt;/strong> method (data added to the &lt;strong>request&lt;/strong> is visible in the URL, unlike POST). But which parts of the request change, and what do characters like &lt;strong>%2F&lt;/strong>, &lt;strong>%20&lt;/strong>, or &lt;strong>%C3%B3&lt;/strong> mean?&lt;/p>
&lt;p>Using the &lt;strong>Network&lt;/strong> section of the &lt;strong>Chrome Developer Tools&lt;/strong>, we can see that the &lt;strong>query&lt;/strong> starts after &lt;em>download?url=&lt;/em>.&lt;/p>
&lt;div class="figure" style="text-align: center">
&lt;img src="images/query1.png" alt="Headers - GET" width="500px" />
&lt;p class="caption">&lt;span id="fig:unnamed-chunk-6">&lt;/span>Figure 6: Headers - GET&lt;/p>
&lt;/div>
&lt;p>From this, we can infer that the &lt;strong>GET&lt;/strong> portion carrying the data, or the &lt;strong>query&lt;/strong>, is: &amp;ldquo;Post Operación/Reportes/IEOD/**2020&lt;/p></description></item><item><title>Electricity for Economists I</title><link>https://luis-zapatabobadilla.netlify.app/project/electricidad-para-economistas-1/</link><pubDate>Sun, 14 Mar 2021 00:00:00 +0000</pubDate><guid>https://luis-zapatabobadilla.netlify.app/project/electricidad-para-economistas-1/</guid><description>&lt;p>Electricity demand is an excellent predictor of GDP. This information has a lag of only one day, which can help us quickly predict whether current GDP is growing or declining. However, it is essential to understand some basic concepts before using it.&lt;/p>
&lt;h2 id="technical-aspects">Technical Aspects&lt;/h2>
&lt;p>Electric energy is defined as the movement of electrons through a conductor over a given period. The physical force or pressure that induces this movement is called voltage, measured in volts (V). The rate at which the electrons flow is called current intensity, measured in amperes (I).&lt;/p>
&lt;p>Electric current (I) is produced by the movement of electrons caused by a voltage difference (V).&lt;/p>
&lt;p>The &lt;strong>electric power&lt;/strong>, measured in watts (W), quantifies the amount of energy consumed, produced, or transferred per unit of time. &lt;strong>Electric energy&lt;/strong>, on the other hand, represents the total amount of energy consumed, produced, or transferred during a specific period and is measured in watt-hours (Wh).&lt;/p>
&lt;p>For example, if the power of a lightbulb is 100 W and it remains on for two hours, the electric energy consumed would be 200 Wh.&lt;/p>
&lt;div class="figure" style="text-align: center">
&lt;img src="images/electricidad.png" alt="Electricity" width="700px" />
&lt;p class="caption">&lt;span id="fig:unnamed-chunk-1">&lt;/span>Figure 1: Electricity&lt;/p>
&lt;/div>
&lt;div class="figure" style="text-align: center">
&lt;img src="images/watt.png" alt="Energy vs Power" width="630px" />
&lt;p class="caption">&lt;span id="fig:unnamed-chunk-2">&lt;/span>Figure 2: Energy vs Power&lt;/p>
&lt;/div>
&lt;p>It’s common to find these units with the following prefixes. We will frequently use the &lt;em>giga&lt;/em> unit when conducting analyses:&lt;/p>
&lt;table>
&lt;thead>
&lt;tr>
&lt;th>Prefix&lt;/th>
&lt;th>Symbol&lt;/th>
&lt;th>&lt;code>\(10^n\)&lt;/code>&lt;/th>
&lt;th>Equivalent&lt;/th>
&lt;/tr>
&lt;/thead>
&lt;tbody>
&lt;tr>
&lt;td>kilo&lt;/td>
&lt;td>K&lt;/td>
&lt;td>&lt;code>\(10^3\)&lt;/code>&lt;/td>
&lt;td>1,000&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>mega&lt;/td>
&lt;td>M&lt;/td>
&lt;td>&lt;code>\(10^6\)&lt;/code>&lt;/td>
&lt;td>1,000,000&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>giga&lt;/td>
&lt;td>G&lt;/td>
&lt;td>&lt;code>\(10^9\)&lt;/code>&lt;/td>
&lt;td>1,000,000,000&lt;/td>
&lt;/tr>
&lt;/tbody>
&lt;/table>
&lt;h3 id="demand">Demand&lt;/h3>
&lt;p>Electricity&amp;rsquo;s utility doesn’t derive from its direct consumption but from its ability to power equipment, making it a derived demand from other economic agents' needs (industries, households, and governments).&lt;/p>
&lt;p>In Peru, there are two types of users in the national electricity system:&lt;/p>
&lt;p>&lt;img src="images/Demanda.png" alt="Clientes COES">&lt;/p>
&lt;ul>
&lt;li>
&lt;p>&lt;strong>Regulated Users:&lt;/strong> These are agents with a demand of less than 200 KW, typically residential users and small businesses. Their prices are regulated by the government entity OSINERGMIN.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Free Users:&lt;/strong> These are agents with a demand of over 200 KW, usually large factories and mines that can negotiate electricity prices. Users with a demand between 200 KW and 2500 KW can choose to be either regulated or free.&lt;/p>
&lt;/li>
&lt;/ul>
&lt;h3 id="generation-transmission-and-distribution">Generation, Transmission, and Distribution&lt;/h3>
&lt;p>Electricity cannot be stored on a large scale at viable costs, necessitating its simultaneous production and consumption. This requires an infrastructure capable of &lt;strong>generation&lt;/strong>, &lt;strong>transportation&lt;/strong>, and &lt;strong>distribution&lt;/strong> in real time.&lt;/p>
&lt;div class="figure">
&lt;img src="images/gtd.png" alt="Generation and Distribution" width="680px" />
&lt;p class="caption">&lt;span id="fig:unnamed-chunk-3">&lt;/span>Figure 3: Generation and Distribution&lt;/p>
&lt;/div>
&lt;h3 id="generation">Generation&lt;/h3>
&lt;p>This first step transforms other energy forms (coal, gas, water flow) into electric energy. Generation relies on diverse technologies such as hydroelectric, thermal, solar, and wind plants, depending on the market size and energy resource availability.&lt;/p>
&lt;p>In Peru, hydroelectric energy has historically dominated, but the development of the &lt;strong>Camisea&lt;/strong> natural gas field has expanded gas-based electricity generation. &lt;center>&lt;/p>
&lt;div class="figure">
&lt;img src="images/generacion.png" alt="Generacion" width="650px" />
&lt;p class="caption">&lt;span id="fig:unnamed-chunk-4">&lt;/span>Figure 4: Generacion&lt;/p>
&lt;/div>
&lt;/center>
&lt;h3 id="transmission">Transmission&lt;/h3>
&lt;p>This step transports electricity from generation centers to consumption areas via high-capacity transmission lines. Due to economies of scale, this segment exhibits natural monopoly characteristics.&lt;/p>
&lt;center>
&lt;div class="figure">
&lt;img src="images/cable.png" alt="Cables de Transmision" width="370px" />
&lt;p class="caption">&lt;span id="fig:unnamed-chunk-5">&lt;/span>Figure 5: Cables de Transmision&lt;/p>
&lt;/div>
&lt;/center>
&lt;p>In Peru, most transmission lines are 138 kV, 220 kV, and 500 kV. Higher capacity lines allow for greater energy transport, which is crucial for supporting industrial growth.&lt;/p>
&lt;h3 id="distribution">Distribution&lt;/h3>
&lt;p>Distribution involves delivering electricity to end-users through medium- and low-voltage networks. In Peru, this segment is often managed by state companies, except in large cities like Lima, where private companies like Luz del Sur operate.&lt;/p>
&lt;h3 id="key-institutions">Key Institutions&lt;/h3>
&lt;ul>
&lt;li>&lt;strong>Ministry of Energy and Mines:&lt;/strong> Responsible for legislating energy-related matters.&lt;/li>
&lt;li>&lt;strong>OSINERGMIN:&lt;/strong> Supervises compliance and sets regulated user prices.&lt;/li>
&lt;li>&lt;strong>COES (Committee for Economic Operation of the System):&lt;/strong> Coordinates the electricity system, manages the short-term market, and plans long-term energy needs.&lt;/li>
&lt;/ul>
&lt;div class="figure">
&lt;img src="images/coes.png" alt="Modelo del Mercado Peruano" width="600px" />
&lt;p class="caption">&lt;span id="fig:unnamed-chunk-6">&lt;/span>Figure 6: Modelo del Mercado Peruano&lt;/p>
&lt;/div>
&lt;/center>
&lt;p>The COES exists to maintain the proper balance between energy demand and supply, managing the agents involved (Generators-Distributors) through the electricity market.&lt;/p>
&lt;p>The decisions of the COES are mandatory for its members (generation, transmission, and distribution companies). Electricity generation is dispatched in order of the marginal cost of production. As a result, the first energy to be dispatched comes from the most efficient technologies (solar, wind, etc.).&lt;/p>
&lt;center>
&lt;div class="figure">
&lt;img src="images/coes2.png" alt="COES Despacho" width="300px" />
&lt;p class="caption">&lt;span id="fig:unnamed-chunk-7">&lt;/span>Figure 7: COES Despacho&lt;/p>
&lt;/div>
&lt;/center></description></item><item><title>Electricity for Economists II</title><link>https://luis-zapatabobadilla.netlify.app/project/electricity-for-economists-2/</link><pubDate>Sun, 14 Mar 2021 00:00:00 +0000</pubDate><guid>https://luis-zapatabobadilla.netlify.app/project/electricity-for-economists-2/</guid><description>&lt;h1 id="sources-of-information-in-peru">Sources of Information in Peru&lt;/h1>
&lt;h1 id="coes">COES&lt;/h1>
&lt;p>The COES manages the technical aspect of electricity flow (supply and demand) in the National Interconnected Electric System or &lt;a href="https://es.wikipedia.org/wiki/Sistema_El%c3%a9ctrico_Interconectado_Nacional" target="_blank" rel="noopener">SEIN&lt;/a>. If you want to review the technical aspects of electricity, you can find them &lt;a href="https://rpubs.com/luisjo819/electricidad" target="_blank" rel="noopener">here&lt;/a>.&lt;/p>
&lt;p>As mentioned earlier, &lt;strong>COES manages information on electricity generation, transmission, and demand&lt;/strong> in real time, ensuring the electrical system remains balanced (Supply = Demand).&lt;/p>
&lt;p>COES also &lt;strong>publishes this information on its website &lt;a href="https://www.coes.org.pe/portal/">https://www.coes.org.pe/portal/&lt;/a>&lt;/strong>.&lt;/p>
&lt;p>There is a variety of information available on the COES website. Below, we will describe the most relevant aspects for our work:&lt;/p>
&lt;h2 id="indicators-of-the-peruvian-energy-sector">&lt;strong>Indicators of the Peruvian Energy Sector&lt;/strong>&lt;/h2>
&lt;p>This is the most accessible information on the COES website. There is a link on the homepage:&lt;/p>
&lt;div class="figure" style="text-align: center">
&lt;img src="images/COESII.png" alt="Indicador de generación total" width="700px" />
&lt;p class="caption">&lt;span id="fig:unnamed-chunk-1">&lt;/span>Figure 1: Indicador de generación total&lt;/p>
&lt;/div>
&lt;p>This is the most accessible information on the COES website. There is a link on the homepage:&lt;/p>
&lt;div class="figure" style="text-align: center">
&lt;img src="images/COESII.png" alt="Total Generation Indicator" width="700px" />
&lt;p class="caption">&lt;span id="fig:unnamed-chunk-2">&lt;/span>Figure 2: Total Generation Indicator&lt;/p>
&lt;/div>
&lt;p>Here, we can access various information provided by agents in the electricity sector, such as:&lt;/p>
&lt;ul>
&lt;li>&lt;strong>Electricity generation by all Peruvian generating companies within the SEIN.&lt;/strong>&lt;/li>
&lt;li>An estimate of electricity demand.&lt;/li>
&lt;li>Announcements of failures and repairs within SEIN.&lt;/li>
&lt;li>Information on the volume and capacity of hydroelectric company reservoirs.&lt;/li>
&lt;/ul>
&lt;p>The most relevant information for day-to-day economic analysis is &lt;strong>electricity generation&lt;/strong>. Users can select a date range and view data on the website or download it as an Excel file. The website provides executed measurements every 30 minutes and projections for the rest of the current day. For dates prior to today, only executed data is available.&lt;/p>
&lt;div class="figure" style="text-align: center">
&lt;img src="images/COESIII.png" alt="View Generation Data" width="700px" />
&lt;p class="caption">&lt;span id="fig:unnamed-chunk-3">&lt;/span>Figure 3: View Generation Data&lt;/p>
&lt;/div>
&lt;p>Information is categorized by generating company and resource type (hydroelectric, gas, etc.).&lt;/p>
&lt;h2 id="operations">&lt;strong>Operations&lt;/strong>&lt;/h2>
&lt;p>Within the options available in the website&amp;rsquo;s top menu, we find various operation-related features of COES.&lt;/p>
&lt;p>&lt;img src="images/coesIV-01.png" alt="" title="Operación del COES">&lt;/p>
&lt;p>This section provides access to COES operation data, including the most important options::&lt;/p>
&lt;h3 id="database">Database&lt;/h3>
&lt;h3 id="database-1">Database&lt;/h3>
&lt;p>Under the &amp;ldquo;Database&amp;rdquo; section, users can access automated data before it is published in official reports. The most relevant option for us is the &lt;strong>Generation Meters&lt;/strong>:&lt;/p>
&lt;ul>
&lt;li>&lt;strong>Generation Meters:&lt;/strong> Contains information on &lt;strong>monthly electricity generation&lt;/strong> in the country, based on the selected date range. The most important data is &lt;strong>Total Energy (MWh)&lt;/strong>. The data for the previous month is uploaded &lt;strong>on the third day of the month&lt;/strong>.&lt;/li>
&lt;/ul>
&lt;blockquote>
&lt;p>This section provides official data on the previous month&amp;rsquo;s electricity generation &lt;strong>directly and before publication elsewhere&lt;/strong>.&lt;/p>
&lt;/blockquote>
&lt;h3 id="operation-program">Operation Program&lt;/h3>
&lt;p>The &amp;ldquo;Operation Program&amp;rdquo; section includes projections for future electricity demand and corresponding generation planning. The projections are more reliable when closer to the current date. For instance, &lt;strong>daily projections&lt;/strong> are highly reliable, whereas &lt;strong>weekly&lt;/strong> and &lt;strong>medium-term&lt;/strong> projections are less so.&lt;/p>
&lt;blockquote>
&lt;p>This information is not very relevant to our day-to-day work and does not need to be mastered; however, it can be useful to know for certain special requests.&lt;/p>
&lt;/blockquote>
&lt;p>Electricity demand can be mathematically divided into two parts: an almost invariant trend and a variable component that fluctuates according to the economic cycle. It is generally considered that the consumption of free users (industries, mines, etc.) constitutes the variable component, while the consumption of regulated users (households) represents the invariant trend. For &lt;strong>medium-term&lt;/strong> projections, both free-user and regulated-user demand are calculated. The &lt;strong>Vegetative Demand&lt;/strong> is the term commonly used to describe the trend component of electricity demand.&lt;/p>
&lt;p>To project demand, COES calculates vegetative demand using an &lt;strong>ARIMA model&lt;/strong>, while the variable component is obtained through a survey of all free users. This combined approach allows for medium-term projections.&lt;/p>
&lt;p>To view this projection, click on &lt;strong>Medium-Term Operation Program&lt;/strong>, select the date, and in the &lt;strong>2_Reports&lt;/strong> section, download the file PMPO_&amp;ldquo;Date&amp;rdquo;.zip. Within the zip file, extract another zip file &lt;strong>Demand_&amp;ldquo;Date&amp;rdquo;.zip&lt;/strong> and open the Excel file **Medium-Term Demand Projection_ARIMA_&amp;ldquo;Date&amp;rdquo;.xlsx**. Inside, you will find the projection. However, it is important to note that the free-user data is only obtained through an annual survey, making the projection less reliable. Nonetheless, it is useful for planning investments in the electricity sector.&lt;/p>
&lt;h3 id="international-exchanges">International Exchanges&lt;/h3>
&lt;p>The international exchanges section contains information on the import and export of electricity. The most relevant option within this section is &lt;strong>Energy Meter Logs&lt;/strong>, which provides data on electricity imports and exports measured in MWh.&lt;/p>
&lt;p>Electricity is transmitted in loads, which can be either positive or negative depending on the direction, i.e., whether the demand originates from one side or the other. This allows the load direction to be measured at substations located on the border.&lt;/p>
&lt;blockquote>
&lt;p>Peru&amp;rsquo;s most significant international electricity exchange is with the neighboring country of Ecuador. This exchange is closely linked to the energy conditions in the northern region of Peru (demand or surplus energy), which is usually related to its economic activity.&lt;/p>
&lt;/blockquote>
&lt;h3 id="single-line-diagram">Single-Line Diagram&lt;/h3>
&lt;p>Finally, the most relevant feature within the operations section is the &lt;em>single-line diagram&lt;/em>. The single-line diagram is a map (in PDF format) that contains the name and location of each electricity measurement point within the SEIN.&lt;/p>
&lt;p>The map allows us to observe electricity transmission lines, which are subdivided into smaller lines feeding smaller sectors. This way, if we have more granular information on regionally focused demand (&lt;strong>Post-Operation - Agent Demand - Distributors&lt;/strong>), we can determine with certainty whether one measurement point includes the data of another point (i.e., if it is the &amp;ldquo;parent&amp;rdquo; of another line), avoiding overestimating demand when aggregating all information.&lt;/p>
&lt;h2 id="post-operation">&lt;strong>Post-Operation&lt;/strong>&lt;/h2>
&lt;p>Within the options available in the top menu of the website, we find various features, including the post-operation options of COES. This section contains information processed after passing through the &lt;strong>Operation&lt;/strong> section. It allows access to more granular and processed data on national electricity demand.&lt;/p>
&lt;div class="figure" style="text-align: center">
&lt;img src="images/COESV.png" alt="Post Operation" width="700px" />
&lt;p class="caption">&lt;span id="fig:unnamed-chunk-4">&lt;/span>Figure 4: Post Operation&lt;/p>
&lt;/div>
&lt;h3 id="ieod">&lt;strong>IEOD&lt;/strong>&lt;/h3>
&lt;p>The most important information we work with comes from the &lt;strong>Daily Operation Evaluation Report&lt;/strong> (IEOD). This report contains all the detailed data from COES operations conducted on a specific day.&lt;/p>
&lt;p>By accessing this section, we can select the desired date and download the most relevant Excel file: &lt;strong>Anexo1_Resumen_&lt;em>&amp;ldquo;Date&amp;rdquo;&lt;/em>.xlsx&lt;/strong>.&lt;/p>
&lt;p>Part of the information divides the country into three regions: North, Center, and South, as shown in the following map:&lt;/p>
&lt;div class="figure" style="text-align: center">
&lt;img src="images/region.jpeg" alt="Diagrama unifilar" width="700px" />
&lt;p class="caption">&lt;span id="fig:unnamed-chunk-5">&lt;/span>Figure 5: Diagrama unifilar&lt;/p>
&lt;/div>
In this context, the central region is defined as the area excluding the northern and southern regions. Iquitos is not part of SEIN and is considered an independent system.
&lt;p>Within the IEOD Excel file, we find various useful sheets, the most relevant of which are:&lt;/p>
&lt;ul>
&lt;li>&lt;strong>Demanda_UL:&lt;/strong> This sheet shows the power demand of Large Free Users (unlike free users [&amp;gt;2,500 KW], large free users are those demanding even more electricity [&amp;gt;10,000 KW]). The companies are categorized by their location in the North, Center, or South. Since the information is in power and provided every 30 minutes, to obtain the daily demand in GWh, the data must be summed, multiplied by 1,000, and divided by 2 (to convert the unit to 1 hour).&lt;/li>
&lt;/ul>
&lt;blockquote>
&lt;p>This data allows us to infer the demand of &lt;strong>mining and manufacturing sectors&lt;/strong>. Companies are not legally obligated to provide this data (though there are monetary penalties), so the information may have gaps, represented by a demand of 0. Researchers must use their discretion to impute the missing data.&lt;/p>
&lt;/blockquote>
&lt;ul>
&lt;li>&lt;strong>Demanda_Areas:&lt;/strong> This sheet shows the total power demand in the country, separated by Areas and Sub-Areas. The most reliable data is by Areas (North, Center, and South). To calculate the daily data, the values recorded every 30 minutes are summed and then divided by 2. The total corresponds to the energy observed by COES-affiliated companies, so it is slightly less than the total demand measured in SEIN (Indicators of the Peruvian Energy Sector).&lt;/li>
&lt;/ul>
&lt;p>These two sheets are the most relevant. However, the Excel file also includes information on generation by resource (hydroelectric, natural gas, etc.), which can be useful depending on the researcher’s needs.&lt;/p>
&lt;h3 id="reports---evaluation">Reports - Evaluation&lt;/h3>
&lt;p>This section displays the reports prepared by COES for the public. The most relevant report is the &lt;strong>Monthly Report&lt;/strong>, which provides the official data on generation and the percentage variation for a given month. &lt;em>The monthly data does not match the sum of the daily data collected due to measurement errors.&lt;/em>&lt;/p>
&lt;p>The report is published on the 15th of each month. However, the official monthly generation data can be accessed earlier in the Operations -&amp;gt; Database section.&lt;/p>
&lt;h3 id="agent-demand">Agent Demand&lt;/h3>
&lt;p>This section shows the demand of two COES agents: Free Users and Distribution Companies:&lt;/p>
&lt;ul>
&lt;li>
&lt;p>&lt;strong>Free Users:&lt;/strong> Displays the demand of some free users affiliated with COES. Each month, some free users voluntarily provide their daily demand data to COES, while others opt out, making &lt;strong>this information variable&lt;/strong>. Compared to the IEOD, this section includes data from more companies and is subdivided by each company’s measurement points (e.g., each factory).&lt;/p>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Distribution Companies:&lt;/strong> Shows the electrical demand in the region assigned to each distribution company. A measurement point may include data from another measurement point, which is why it’s important to review the &lt;em>Single-Line Diagram&lt;/em> to ensure the information is consistent. The most relevant data in this section comes from higher-level measurement points (e.g., substations in the regional capital). To locate these, it is also useful to consult the single-line diagram. This information is somewhat complex to process and relatively new, so I conducted an analysis &lt;a href="https://rpubs.com/luisjo819/Distribuidores" target="_blank" rel="noopener">here&lt;/a>.&lt;/p>
&lt;/li>
&lt;/ul>
&lt;blockquote>
&lt;p>Distribution companies are often state-owned and inefficient, so &lt;strong>the data is variable and unreliable&lt;/strong>. This information is still being implemented and is not available for all districts. However, COES is working to ensure that, in the future, each distribution company will automatically report its demand data.&lt;/p>
&lt;/blockquote>
&lt;h2 id="members">Members&lt;/h2>
&lt;p>Finally, another option in the top menu is &amp;ldquo;Members.&amp;rdquo; By clicking on &lt;strong>&amp;ldquo;List of Members&amp;rdquo;&lt;/strong>, we can view the members of COES, whether they are Generators, Distributors, or Free Users.&lt;/p>
&lt;h4 id="additionally-coes-responds-to-any-inquiries-we-may-have-this-is-useful-for-example-if-we-suspect-a-data-error-to-contact-them-simply-click-on-the-blue-button-located-at-the-top-labeled-contact-us-when-you-hover-over-it">Additionally, COES responds to any inquiries we may have. This is useful, for example, if we suspect a data error. To contact them, simply click on the blue button located at the top, labeled &amp;ldquo;Contact Us&amp;rdquo; when you hover over it.&lt;/h4>
&lt;h1 id="osinergmin">OSINERGMIN&lt;/h1>
&lt;p>OSINERGMIN is the entity responsible for overseeing the members of COES. An interesting feature is the SEIN map, which contains the geographic location of SEIN components: &lt;a href="https://www.osinergmin.gob.pe/newweb/uploads/Publico/MapaSEIN/">https://www.osinergmin.gob.pe/newweb/uploads/Publico/MapaSEIN/&lt;/a>.&lt;/p>
&lt;p>Additionally, it is possible to access information on &lt;strong>the demand of all free users in the country&lt;/strong> through the following link, under Publications -&amp;gt; Monthly Reports -&amp;gt; Free Electricity Market:&lt;/p>
&lt;p>&lt;a href="https://www.osinergmin.gob.pe/seccion/institucional/regulacion-tarifaria/publicaciones/regulacion-tarifaria">https://www.osinergmin.gob.pe/seccion/institucional/regulacion-tarifaria/publicaciones/regulacion-tarifaria&lt;/a>&lt;/p>
&lt;p>However, this information is delayed by 2 months, making it less useful for recent data needs.&lt;/p>
&lt;h1 id="ministry-of-energy-and-mines">MINISTRY OF ENERGY AND MINES&lt;/h1>
&lt;p>Finally, the Ministry of Energy and Mines also conducts an annual review of the electricity sector. Their reports are delayed by 1 or 2 years but contain a wealth of historical information, such as &lt;strong>the total demand in the country by industrial activity&lt;/strong>.&lt;/p>
&lt;p>The information can be downloaded from: &lt;a href="http://www.minem.gob.pe/_estadisticaSector.php?idSector=6">http://www.minem.gob.pe/_estadisticaSector.php?idSector=6&lt;/a>&lt;/p></description></item><item><title>Writing technical content in Academic</title><link>https://luis-zapatabobadilla.netlify.app/post/writing-technical-content/</link><pubDate>Fri, 12 Jul 2019 00:00:00 +0000</pubDate><guid>https://luis-zapatabobadilla.netlify.app/post/writing-technical-content/</guid><description>&lt;p>Academic is designed to give technical content creators a seamless experience. You can focus on the content and Academic handles the rest.&lt;/p>
&lt;p>&lt;strong>Highlight your code snippets, take notes on math classes, and draw diagrams from textual representation.&lt;/strong>&lt;/p>
&lt;p>On this page, you&amp;rsquo;ll find some examples of the types of technical content that can be rendered with Academic.&lt;/p>
&lt;h2 id="examples">Examples&lt;/h2>
&lt;h3 id="code">Code&lt;/h3>
&lt;p>Academic supports a Markdown extension for highlighting code syntax. You can enable this feature by toggling the &lt;code>highlight&lt;/code> option in your &lt;code>config/_default/params.toml&lt;/code> file.&lt;/p>
&lt;pre>&lt;code>```python
import pandas as pd
data = pd.read_csv(&amp;quot;data.csv&amp;quot;)
data.head()
```
&lt;/code>&lt;/pre>
&lt;p>renders as&lt;/p>
&lt;pre>&lt;code class="language-python">import pandas as pd
data = pd.read_csv(&amp;quot;data.csv&amp;quot;)
data.head()
&lt;/code>&lt;/pre>
&lt;h3 id="charts">Charts&lt;/h3>
&lt;p>Academic supports the popular &lt;a href="https://plot.ly/" target="_blank" rel="noopener">Plotly&lt;/a> chart format.&lt;/p>
&lt;p>Save your Plotly JSON in your page folder, for example &lt;code>chart.json&lt;/code>, and then add the &lt;code>{{&amp;lt; chart data=&amp;quot;chart&amp;quot; &amp;gt;}}&lt;/code> shortcode where you would like the chart to appear.&lt;/p>
&lt;p>Demo:&lt;/p>
&lt;div id="chart-372986145" class="chart">&lt;/div>
&lt;script>
(function() {
let a = setInterval( function() {
if ( typeof window.Plotly === 'undefined' ) {
return;
}
clearInterval( a );
Plotly.d3.json("./line-chart.json", function(chart) {
Plotly.plot('chart-372986145', chart.data, chart.layout, {responsive: true});
});
}, 500 );
})();
&lt;/script>
&lt;p>You might also find the &lt;a href="http://plotly-json-editor.getforge.io/" target="_blank" rel="noopener">Plotly JSON Editor&lt;/a> useful.&lt;/p>
&lt;h3 id="math">Math&lt;/h3>
&lt;p>Academic supports a Markdown extension for $\LaTeX$ math. You can enable this feature by toggling the &lt;code>math&lt;/code> option in your &lt;code>config/_default/params.toml&lt;/code> file.&lt;/p>
&lt;p>To render &lt;em>inline&lt;/em> or &lt;em>block&lt;/em> math, wrap your LaTeX math with &lt;code>$...$&lt;/code> or &lt;code>$$...$$&lt;/code>, respectively.&lt;/p>
&lt;p>Example &lt;strong>math block&lt;/strong>:&lt;/p>
&lt;pre>&lt;code class="language-latex">$$\gamma_{n} = \frac{
\left | \left (\mathbf x_{n} - \mathbf x_{n-1} \right )^T
\left [\nabla F (\mathbf x_{n}) - \nabla F (\mathbf x_{n-1}) \right ] \right |}
{\left \|\nabla F(\mathbf{x}_{n}) - \nabla F(\mathbf{x}_{n-1}) \right \|^2}$$
&lt;/code>&lt;/pre>
&lt;p>renders as&lt;/p>
&lt;p>$$\gamma_{n} = \frac{ \left | \left (\mathbf x_{n} - \mathbf x_{n-1} \right )^T \left [\nabla F (\mathbf x_{n}) - \nabla F (\mathbf x_{n-1}) \right ] \right |}{\left |\nabla F(\mathbf{x}_{n}) - \nabla F(\mathbf{x}_{n-1}) \right |^2}$$&lt;/p>
&lt;p>Example &lt;strong>inline math&lt;/strong> &lt;code>$\nabla F(\mathbf{x}_{n})$&lt;/code> renders as $\nabla F(\mathbf{x}_{n})$.&lt;/p>
&lt;p>Example &lt;strong>multi-line math&lt;/strong> using the &lt;code>\\\\&lt;/code> math linebreak:&lt;/p>
&lt;pre>&lt;code class="language-latex">$$f(k;p_{0}^{*}) = \begin{cases}p_{0}^{*} &amp;amp; \text{if }k=1, \\\\
1-p_{0}^{*} &amp;amp; \text{if }k=0.\end{cases}$$
&lt;/code>&lt;/pre>
&lt;p>renders as&lt;/p>
&lt;p>$$f(k;p_{0}^{*}) = \begin{cases}p_{0}^{*} &amp;amp; \text{if }k=1, \\&lt;br>
1-p_{0}^{*} &amp;amp; \text{if }k=0.\end{cases}$$&lt;/p>
&lt;h3 id="diagrams">Diagrams&lt;/h3>
&lt;p>Academic supports a Markdown extension for diagrams. You can enable this feature by toggling the &lt;code>diagram&lt;/code> option in your &lt;code>config/_default/params.toml&lt;/code> file or by adding &lt;code>diagram: true&lt;/code> to your page front matter.&lt;/p>
&lt;p>An example &lt;strong>flowchart&lt;/strong>:&lt;/p>
&lt;pre>&lt;code>```mermaid
graph TD
A[Hard] --&amp;gt;|Text| B(Round)
B --&amp;gt; C{Decision}
C --&amp;gt;|One| D[Result 1]
C --&amp;gt;|Two| E[Result 2]
```
&lt;/code>&lt;/pre>
&lt;p>renders as&lt;/p>
&lt;pre>&lt;code class="language-mermaid">graph TD
A[Hard] --&amp;gt;|Text| B(Round)
B --&amp;gt; C{Decision}
C --&amp;gt;|One| D[Result 1]
C --&amp;gt;|Two| E[Result 2]
&lt;/code>&lt;/pre>
&lt;p>An example &lt;strong>sequence diagram&lt;/strong>:&lt;/p>
&lt;pre>&lt;code>```mermaid
sequenceDiagram
Alice-&amp;gt;&amp;gt;John: Hello John, how are you?
loop Healthcheck
John-&amp;gt;&amp;gt;John: Fight against hypochondria
end
Note right of John: Rational thoughts!
John--&amp;gt;&amp;gt;Alice: Great!
John-&amp;gt;&amp;gt;Bob: How about you?
Bob--&amp;gt;&amp;gt;John: Jolly good!
```
&lt;/code>&lt;/pre>
&lt;p>renders as&lt;/p>
&lt;pre>&lt;code class="language-mermaid">sequenceDiagram
Alice-&amp;gt;&amp;gt;John: Hello John, how are you?
loop Healthcheck
John-&amp;gt;&amp;gt;John: Fight against hypochondria
end
Note right of John: Rational thoughts!
John--&amp;gt;&amp;gt;Alice: Great!
John-&amp;gt;&amp;gt;Bob: How about you?
Bob--&amp;gt;&amp;gt;John: Jolly good!
&lt;/code>&lt;/pre>
&lt;p>An example &lt;strong>Gantt diagram&lt;/strong>:&lt;/p>
&lt;pre>&lt;code>```mermaid
gantt
section Section
Completed :done, des1, 2014-01-06,2014-01-08
Active :active, des2, 2014-01-07, 3d
Parallel 1 : des3, after des1, 1d
Parallel 2 : des4, after des1, 1d
Parallel 3 : des5, after des3, 1d
Parallel 4 : des6, after des4, 1d
```
&lt;/code>&lt;/pre>
&lt;p>renders as&lt;/p>
&lt;pre>&lt;code class="language-mermaid">gantt
section Section
Completed :done, des1, 2014-01-06,2014-01-08
Active :active, des2, 2014-01-07, 3d
Parallel 1 : des3, after des1, 1d
Parallel 2 : des4, after des1, 1d
Parallel 3 : des5, after des3, 1d
Parallel 4 : des6, after des4, 1d
&lt;/code>&lt;/pre>
&lt;p>An example &lt;strong>class diagram&lt;/strong>:&lt;/p>
&lt;pre>&lt;code>```mermaid
classDiagram
Class01 &amp;lt;|-- AveryLongClass : Cool
&amp;lt;&amp;lt;interface&amp;gt;&amp;gt; Class01
Class09 --&amp;gt; C2 : Where am i?
Class09 --* C3
Class09 --|&amp;gt; Class07
Class07 : equals()
Class07 : Object[] elementData
Class01 : size()
Class01 : int chimp
Class01 : int gorilla
class Class10 {
&amp;lt;&amp;lt;service&amp;gt;&amp;gt;
int id
size()
}
```
&lt;/code>&lt;/pre>
&lt;p>renders as&lt;/p>
&lt;pre>&lt;code class="language-mermaid">classDiagram
Class01 &amp;lt;|-- AveryLongClass : Cool
&amp;lt;&amp;lt;interface&amp;gt;&amp;gt; Class01
Class09 --&amp;gt; C2 : Where am i?
Class09 --* C3
Class09 --|&amp;gt; Class07
Class07 : equals()
Class07 : Object[] elementData
Class01 : size()
Class01 : int chimp
Class01 : int gorilla
class Class10 {
&amp;lt;&amp;lt;service&amp;gt;&amp;gt;
int id
size()
}
&lt;/code>&lt;/pre>
&lt;p>An example &lt;strong>state diagram&lt;/strong>:&lt;/p>
&lt;pre>&lt;code>```mermaid
stateDiagram
[*] --&amp;gt; Still
Still --&amp;gt; [*]
Still --&amp;gt; Moving
Moving --&amp;gt; Still
Moving --&amp;gt; Crash
Crash --&amp;gt; [*]
```
&lt;/code>&lt;/pre>
&lt;p>renders as&lt;/p>
&lt;pre>&lt;code class="language-mermaid">stateDiagram
[*] --&amp;gt; Still
Still --&amp;gt; [*]
Still --&amp;gt; Moving
Moving --&amp;gt; Still
Moving --&amp;gt; Crash
Crash --&amp;gt; [*]
&lt;/code>&lt;/pre>
&lt;h3 id="todo-lists">Todo lists&lt;/h3>
&lt;p>You can even write your todo lists in Academic too:&lt;/p>
&lt;pre>&lt;code class="language-markdown">- [x] Write math example
- [x] Write diagram example
- [ ] Do something else
&lt;/code>&lt;/pre>
&lt;p>renders as&lt;/p>
&lt;ul>
&lt;li>&lt;input checked="" disabled="" type="checkbox"> Write math example&lt;/li>
&lt;li>&lt;input checked="" disabled="" type="checkbox"> Write diagram example&lt;/li>
&lt;li>&lt;input disabled="" type="checkbox"> Do something else&lt;/li>
&lt;/ul>
&lt;h3 id="tables">Tables&lt;/h3>
&lt;p>Represent your data in tables:&lt;/p>
&lt;pre>&lt;code class="language-markdown">| First Header | Second Header |
| ------------- | ------------- |
| Content Cell | Content Cell |
| Content Cell | Content Cell |
&lt;/code>&lt;/pre>
&lt;p>renders as&lt;/p>
&lt;table>
&lt;thead>
&lt;tr>
&lt;th>First Header&lt;/th>
&lt;th>Second Header&lt;/th>
&lt;/tr>
&lt;/thead>
&lt;tbody>
&lt;tr>
&lt;td>Content Cell&lt;/td>
&lt;td>Content Cell&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>Content Cell&lt;/td>
&lt;td>Content Cell&lt;/td>
&lt;/tr>
&lt;/tbody>
&lt;/table>
&lt;h3 id="callouts">Callouts&lt;/h3>
&lt;p>Academic supports a &lt;a href="https://wowchemy.com/docs/content/writing-markdown-latex/#callouts" target="_blank" rel="noopener">shortcode for callouts&lt;/a>, also referred to as &lt;em>asides&lt;/em>, &lt;em>hints&lt;/em>, or &lt;em>alerts&lt;/em>. By wrapping a paragraph in &lt;code>{{% callout note %}} ... {{% /callout %}}&lt;/code>, it will render as an aside.&lt;/p>
&lt;pre>&lt;code class="language-markdown">{{% callout note %}}
A Markdown aside is useful for displaying notices, hints, or definitions to your readers.
{{% /callout %}}
&lt;/code>&lt;/pre>
&lt;p>renders as&lt;/p>
&lt;div class="alert alert-note">
&lt;div>
A Markdown aside is useful for displaying notices, hints, or definitions to your readers.
&lt;/div>
&lt;/div>
&lt;h3 id="spoilers">Spoilers&lt;/h3>
&lt;p>Add a spoiler to a page to reveal text, such as an answer to a question, after a button is clicked.&lt;/p>
&lt;pre>&lt;code class="language-markdown">{{&amp;lt; spoiler text=&amp;quot;Click to view the spoiler&amp;quot; &amp;gt;}}
You found me!
{{&amp;lt; /spoiler &amp;gt;}}
&lt;/code>&lt;/pre>
&lt;p>renders as&lt;/p>
&lt;details class="spoiler " id="spoiler-2">
&lt;summary>Click to view the spoiler&lt;/summary>
&lt;p>You found me!&lt;/p>
&lt;/details>
&lt;h3 id="icons">Icons&lt;/h3>
&lt;p>Academic enables you to use a wide range of &lt;a href="https://sourcethemes.com/academic/docs/page-builder/#icons" target="_blank" rel="noopener">icons from &lt;em>Font Awesome&lt;/em> and &lt;em>Academicons&lt;/em>&lt;/a> in addition to &lt;a href="https://sourcethemes.com/academic/docs/writing-markdown-latex/#emojis" target="_blank" rel="noopener">emojis&lt;/a>.&lt;/p>
&lt;p>Here are some examples using the &lt;code>icon&lt;/code> shortcode to render icons:&lt;/p>
&lt;pre>&lt;code class="language-markdown">{{&amp;lt; icon name=&amp;quot;terminal&amp;quot; pack=&amp;quot;fas&amp;quot; &amp;gt;}} Terminal
{{&amp;lt; icon name=&amp;quot;python&amp;quot; pack=&amp;quot;fab&amp;quot; &amp;gt;}} Python
{{&amp;lt; icon name=&amp;quot;r-project&amp;quot; pack=&amp;quot;fab&amp;quot; &amp;gt;}} R
&lt;/code>&lt;/pre>
&lt;p>renders as&lt;/p>
&lt;p>
&lt;i class="fas fa-terminal pr-1 fa-fw">&lt;/i> Terminal&lt;br>
&lt;i class="fab fa-python pr-1 fa-fw">&lt;/i> Python&lt;br>
&lt;i class="fab fa-r-project pr-1 fa-fw">&lt;/i> R&lt;/p>
&lt;h3 id="did-you-find-this-page-helpful-consider-sharing-it-">Did you find this page helpful? Consider sharing it 🙌&lt;/h3></description></item><item><title>An example preprint / working paper</title><link>https://luis-zapatabobadilla.netlify.app/publication/preprint/</link><pubDate>Sun, 07 Apr 2019 00:00:00 +0000</pubDate><guid>https://luis-zapatabobadilla.netlify.app/publication/preprint/</guid><description>&lt;div class="alert alert-note">
&lt;div>
Create your slides in Markdown - click the &lt;em>Slides&lt;/em> button to check out the example.
&lt;/div>
&lt;/div>
&lt;p>Supplementary notes can be added here, including &lt;a href="https://wowchemy.com/docs/writing-markdown-latex/" target="_blank" rel="noopener">code, math, and images&lt;/a>.&lt;/p></description></item><item><title>Display Jupyter Notebooks with Academic</title><link>https://luis-zapatabobadilla.netlify.app/post/jupyter/</link><pubDate>Tue, 05 Feb 2019 00:00:00 +0000</pubDate><guid>https://luis-zapatabobadilla.netlify.app/post/jupyter/</guid><description>&lt;pre>&lt;code class="language-python">from IPython.core.display import Image
Image('https://www.python.org/static/community_logos/python-logo-master-v3-TM-flattened.png')
&lt;/code>&lt;/pre>
&lt;p>&lt;img src="./index_1_0.png" alt="png">&lt;/p>
&lt;pre>&lt;code class="language-python">print(&amp;quot;Welcome to Academic!&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>Welcome to Academic!
&lt;/code>&lt;/pre>
&lt;h2 id="install-python-and-jupyterlab">Install Python and JupyterLab&lt;/h2>
&lt;p>&lt;a href="https://www.anaconda.com/distribution/#download-section" target="_blank" rel="noopener">Install Anaconda&lt;/a> which includes Python 3 and JupyterLab.&lt;/p>
&lt;p>Alternatively, install JupyterLab with &lt;code>pip3 install jupyterlab&lt;/code>.&lt;/p>
&lt;h2 id="create-or-upload-a-jupyter-notebook">Create or upload a Jupyter notebook&lt;/h2>
&lt;p>Run the following commands in your Terminal, substituting &lt;code>&amp;lt;MY-WEBSITE-FOLDER&amp;gt;&lt;/code> and &lt;code>&amp;lt;SHORT-POST-TITLE&amp;gt;&lt;/code> with the file path to your Academic website folder and a short title for your blog post (use hyphens instead of spaces), respectively:&lt;/p>
&lt;pre>&lt;code class="language-bash">mkdir -p &amp;lt;MY-WEBSITE-FOLDER&amp;gt;/content/post/&amp;lt;SHORT-POST-TITLE&amp;gt;/
cd &amp;lt;MY-WEBSITE-FOLDER&amp;gt;/content/post/&amp;lt;SHORT-POST-TITLE&amp;gt;/
jupyter lab index.ipynb
&lt;/code>&lt;/pre>
&lt;p>The &lt;code>jupyter&lt;/code> command above will launch the JupyterLab editor, allowing us to add Academic metadata and write the content.&lt;/p>
&lt;h2 id="edit-your-post-metadata">Edit your post metadata&lt;/h2>
&lt;p>The first cell of your Jupter notebook will contain your post metadata (&lt;a href="https://sourcethemes.com/academic/docs/front-matter/" target="_blank" rel="noopener">front matter&lt;/a>).&lt;/p>
&lt;p>In Jupter, choose &lt;em>Markdown&lt;/em> as the type of the first cell and wrap your Academic metadata in three dashes, indicating that it is YAML front matter:&lt;/p>
&lt;pre>&lt;code>---
title: My post's title
date: 2019-09-01
# Put any other Academic metadata here...
---
&lt;/code>&lt;/pre>
&lt;p>Edit the metadata of your post, using the &lt;a href="https://sourcethemes.com/academic/docs/managing-content" target="_blank" rel="noopener">documentation&lt;/a> as a guide to the available options.&lt;/p>
&lt;p>To set a &lt;a href="https://sourcethemes.com/academic/docs/managing-content/#featured-image" target="_blank" rel="noopener">featured image&lt;/a>, place an image named &lt;code>featured&lt;/code> into your post&amp;rsquo;s folder.&lt;/p>
&lt;p>For other tips, such as using math, see the guide on &lt;a href="https://sourcethemes.com/academic/docs/writing-markdown-latex/" target="_blank" rel="noopener">writing content with Academic&lt;/a>.&lt;/p>
&lt;h2 id="convert-notebook-to-markdown">Convert notebook to Markdown&lt;/h2>
&lt;pre>&lt;code class="language-bash">jupyter nbconvert index.ipynb --to markdown --NbConvertApp.output_files_dir=.
&lt;/code>&lt;/pre>
&lt;h2 id="example">Example&lt;/h2>
&lt;p>This post was created with Jupyter. The orginal files can be found at &lt;a href="https://github.com/gcushen/hugo-academic/tree/master/exampleSite/content/post/jupyter">https://github.com/gcushen/hugo-academic/tree/master/exampleSite/content/post/jupyter&lt;/a>&lt;/p></description></item><item><title>Slides</title><link>https://luis-zapatabobadilla.netlify.app/slides/example/</link><pubDate>Tue, 05 Feb 2019 00:00:00 +0000</pubDate><guid>https://luis-zapatabobadilla.netlify.app/slides/example/</guid><description>&lt;h1 id="create-slides-in-markdown-with-wowchemy">Create slides in Markdown with Wowchemy&lt;/h1>
&lt;p>&lt;a href="https://wowchemy.com/" target="_blank" rel="noopener">Wowchemy&lt;/a> | &lt;a href="https://owchemy.com/docs/managing-content/#create-slides" target="_blank" rel="noopener">Documentation&lt;/a>&lt;/p>
&lt;hr>
&lt;h2 id="features">Features&lt;/h2>
&lt;ul>
&lt;li>Efficiently write slides in Markdown&lt;/li>
&lt;li>3-in-1: Create, Present, and Publish your slides&lt;/li>
&lt;li>Supports speaker notes&lt;/li>
&lt;li>Mobile friendly slides&lt;/li>
&lt;/ul>
&lt;hr>
&lt;h2 id="controls">Controls&lt;/h2>
&lt;ul>
&lt;li>Next: &lt;code>Right Arrow&lt;/code> or &lt;code>Space&lt;/code>&lt;/li>
&lt;li>Previous: &lt;code>Left Arrow&lt;/code>&lt;/li>
&lt;li>Start: &lt;code>Home&lt;/code>&lt;/li>
&lt;li>Finish: &lt;code>End&lt;/code>&lt;/li>
&lt;li>Overview: &lt;code>Esc&lt;/code>&lt;/li>
&lt;li>Speaker notes: &lt;code>S&lt;/code>&lt;/li>
&lt;li>Fullscreen: &lt;code>F&lt;/code>&lt;/li>
&lt;li>Zoom: &lt;code>Alt + Click&lt;/code>&lt;/li>
&lt;li>&lt;a href="https://github.com/hakimel/reveal.js#pdf-export" target="_blank" rel="noopener">PDF Export&lt;/a>: &lt;code>E&lt;/code>&lt;/li>
&lt;/ul>
&lt;hr>
&lt;h2 id="code-highlighting">Code Highlighting&lt;/h2>
&lt;p>Inline code: &lt;code>variable&lt;/code>&lt;/p>
&lt;p>Code block:&lt;/p>
&lt;pre>&lt;code class="language-python">porridge = &amp;quot;blueberry&amp;quot;
if porridge == &amp;quot;blueberry&amp;quot;:
print(&amp;quot;Eating...&amp;quot;)
&lt;/code>&lt;/pre>
&lt;hr>
&lt;h2 id="math">Math&lt;/h2>
&lt;p>In-line math: $x + y = z$&lt;/p>
&lt;p>Block math:&lt;/p>
&lt;p>$$
f\left( x \right) = ;\frac{{2\left( {x + 4} \right)\left( {x - 4} \right)}}{{\left( {x + 4} \right)\left( {x + 1} \right)}}
$$&lt;/p>
&lt;hr>
&lt;h2 id="fragments">Fragments&lt;/h2>
&lt;p>Make content appear incrementally&lt;/p>
&lt;pre>&lt;code>{{% fragment %}} One {{% /fragment %}}
{{% fragment %}} **Two** {{% /fragment %}}
{{% fragment %}} Three {{% /fragment %}}
&lt;/code>&lt;/pre>
&lt;p>Press &lt;code>Space&lt;/code> to play!&lt;/p>
&lt;p>&lt;span class="fragment " >
One
&lt;/span>
&lt;span class="fragment " >
&lt;strong>Two&lt;/strong>
&lt;/span>
&lt;span class="fragment " >
Three
&lt;/span>&lt;/p>
&lt;hr>
&lt;p>A fragment can accept two optional parameters:&lt;/p>
&lt;ul>
&lt;li>&lt;code>class&lt;/code>: use a custom style (requires definition in custom CSS)&lt;/li>
&lt;li>&lt;code>weight&lt;/code>: sets the order in which a fragment appears&lt;/li>
&lt;/ul>
&lt;hr>
&lt;h2 id="speaker-notes">Speaker Notes&lt;/h2>
&lt;p>Add speaker notes to your presentation&lt;/p>
&lt;pre>&lt;code class="language-markdown">{{% speaker_note %}}
- Only the speaker can read these notes
- Press `S` key to view
{{% /speaker_note %}}
&lt;/code>&lt;/pre>
&lt;p>Press the &lt;code>S&lt;/code> key to view the speaker notes!&lt;/p>
&lt;aside class="notes">
&lt;ul>
&lt;li>Only the speaker can read these notes&lt;/li>
&lt;li>Press &lt;code>S&lt;/code> key to view&lt;/li>
&lt;/ul>
&lt;/aside>
&lt;hr>
&lt;h2 id="themes">Themes&lt;/h2>
&lt;ul>
&lt;li>black: Black background, white text, blue links (default)&lt;/li>
&lt;li>white: White background, black text, blue links&lt;/li>
&lt;li>league: Gray background, white text, blue links&lt;/li>
&lt;li>beige: Beige background, dark text, brown links&lt;/li>
&lt;li>sky: Blue background, thin dark text, blue links&lt;/li>
&lt;/ul>
&lt;hr>
&lt;ul>
&lt;li>night: Black background, thick white text, orange links&lt;/li>
&lt;li>serif: Cappuccino background, gray text, brown links&lt;/li>
&lt;li>simple: White background, black text, blue links&lt;/li>
&lt;li>solarized: Cream-colored background, dark green text, blue links&lt;/li>
&lt;/ul>
&lt;hr>
&lt;section data-noprocess data-shortcode-slide
data-background-image="/media/boards.jpg"
>
&lt;h2 id="custom-slide">Custom Slide&lt;/h2>
&lt;p>Customize the slide style and background&lt;/p>
&lt;pre>&lt;code class="language-markdown">{{&amp;lt; slide background-image=&amp;quot;/media/boards.jpg&amp;quot; &amp;gt;}}
{{&amp;lt; slide background-color=&amp;quot;#0000FF&amp;quot; &amp;gt;}}
{{&amp;lt; slide class=&amp;quot;my-style&amp;quot; &amp;gt;}}
&lt;/code>&lt;/pre>
&lt;hr>
&lt;h2 id="custom-css-example">Custom CSS Example&lt;/h2>
&lt;p>Let&amp;rsquo;s make headers navy colored.&lt;/p>
&lt;p>Create &lt;code>assets/css/reveal_custom.css&lt;/code> with:&lt;/p>
&lt;pre>&lt;code class="language-css">.reveal section h1,
.reveal section h2,
.reveal section h3 {
color: navy;
}
&lt;/code>&lt;/pre>
&lt;hr>
&lt;h1 id="questions">Questions?&lt;/h1>
&lt;p>&lt;a href="https://github.com/wowchemy/wowchemy-hugo-modules/discussions" target="_blank" rel="noopener">Ask&lt;/a>&lt;/p>
&lt;p>&lt;a href="https://wowchemy.com/docs/managing-content/#create-slides" target="_blank" rel="noopener">Documentation&lt;/a>&lt;/p></description></item><item><title>An example journal article</title><link>https://luis-zapatabobadilla.netlify.app/publication/journal-article/</link><pubDate>Tue, 01 Sep 2015 00:00:00 +0000</pubDate><guid>https://luis-zapatabobadilla.netlify.app/publication/journal-article/</guid><description>&lt;div class="alert alert-note">
&lt;div>
Click the &lt;em>Cite&lt;/em> button above to demo the feature to enable visitors to import publication metadata into their reference management software.
&lt;/div>
&lt;/div>
&lt;div class="alert alert-note">
&lt;div>
Create your slides in Markdown - click the &lt;em>Slides&lt;/em> button to check out the example.
&lt;/div>
&lt;/div>
&lt;p>Supplementary notes can be added here, including &lt;a href="https://wowchemy.com/docs/writing-markdown-latex/" target="_blank" rel="noopener">code, math, and images&lt;/a>.&lt;/p></description></item><item><title>An example conference paper</title><link>https://luis-zapatabobadilla.netlify.app/publication/conference-paper/</link><pubDate>Mon, 01 Jul 2013 00:00:00 +0000</pubDate><guid>https://luis-zapatabobadilla.netlify.app/publication/conference-paper/</guid><description>&lt;div class="alert alert-note">
&lt;div>
Click the &lt;em>Cite&lt;/em> button above to demo the feature to enable visitors to import publication metadata into their reference management software.
&lt;/div>
&lt;/div>
&lt;div class="alert alert-note">
&lt;div>
Create your slides in Markdown - click the &lt;em>Slides&lt;/em> button to check out the example.
&lt;/div>
&lt;/div>
&lt;p>Supplementary notes can be added here, including &lt;a href="https://wowchemy.com/docs/writing-markdown-latex/" target="_blank" rel="noopener">code, math, and images&lt;/a>.&lt;/p></description></item><item><title/><link>https://luis-zapatabobadilla.netlify.app/admin/config.yml</link><pubDate>Mon, 01 Jan 0001 00:00:00 +0000</pubDate><guid>https://luis-zapatabobadilla.netlify.app/admin/config.yml</guid><description/></item><item><title>Electricity for for Economists III</title><link>https://luis-zapatabobadilla.netlify.app/project/electricity-for-economist/</link><pubDate>Mon, 01 Jan 0001 00:00:00 +0000</pubDate><guid>https://luis-zapatabobadilla.netlify.app/project/electricity-for-economist/</guid><description>&lt;p>Finally, we arrive at the third part of this series of blog posts introducing the electricity sector for economists. This time, we will explore how to automate the downloading and processing of electricity data to use it in our prediction models. As mentioned in previous posts, electricity information is useful due to its high correlation with GDP and its quick and easy accessibility.&lt;/p>
&lt;h1 id="processing">Processing&lt;/h1>
&lt;p>The processing of COES data is done through web scraping: a technique used to extract data from web pages using software. Various techniques and software can be employed, but we will use the R software and HTML code to download the data.&lt;/p>
&lt;p>If you want to review the information available on the COES website, you can do so &lt;a href="https://rpubs.com/luisjo819/electricidad_2" target="_blank" rel="noopener">here&lt;/a>.&lt;/p>
&lt;h2 id="http-get-and-post">HTTP: GET and POST&lt;/h2>
&lt;p>To download information from the COES website (&lt;a href="https://www.coes.org.pe/portal/" target="_blank" rel="noopener">https://www.coes.org.pe/portal/&lt;/a>), we will use HTML code. &lt;strong>HTML&lt;/strong> is a markup language used for creating web pages. It contains the &amp;ldquo;&lt;em>instructions&lt;/em>&amp;rdquo; that a web browser (such as Chrome) uses to display and interact with the web page.&lt;/p>
&lt;p>For data downloads, two primary methods of data transfer in HTTP are commonly used: &lt;strong>GET&lt;/strong> and &lt;strong>POST&lt;/strong>.&lt;/p>
&lt;ul>
&lt;li>
&lt;p>&lt;strong>GET&lt;/strong>: A method in the HTTP protocol used to &lt;em>retrieve information&lt;/em> from a server. It sends a request to obtain a response (e.g., an Excel file or other data we want to download) for the client (web page). GET transmits the data in a &amp;ldquo;visible&amp;rdquo; way through the web browser’s URL. For example, suppose we want to request information from a hypothetical website, &lt;a href="http://www.luis.com">www.luis.com&lt;/a>, and the required data for the request are the file name and month: &lt;code>name = luis&lt;/code> and &lt;code>month = November&lt;/code>. Using GET, the request would look like: &lt;a href="http://www.luis.com/">www.luis.com/&lt;/a>&lt;strong>download?name=luis&amp;amp;month=november&lt;/strong>. Here, the bold part is referred to as the &lt;strong>query&lt;/strong>. By submitting this request to the server (with our data), we would receive a response (e.g., an Excel file). Each website has its own syntax for submitting requests.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>POST&lt;/strong>: Another method in the HTTP protocol that, unlike GET, &lt;em>sends information&lt;/em> to the server for processing and updates the server. For example, when we submit (request) data through a form, the server processes the data and, after a redirect, returns (response) a page with information. To download a file using the POST method, a &lt;strong>query&lt;/strong> is sent in a manner similar to GET. However, instead of immediately receiving a response, the server opens a &lt;em>temporary link&lt;/em> at another URL for the file download.&lt;/p>
&lt;/li>
&lt;/ul>
&lt;p>Next, we will see a practical application of these terms to download relevant information from the COES website.&lt;/p>
&lt;h3 id="coes-indicators-of-the-peruvian-energy-sector">COES: Indicators of the Peruvian Energy Sector&lt;/h3>
&lt;p>To access this section, we go to the &lt;strong>Indicators Portal&lt;/strong> on the COES website. By clicking on export, we send a &lt;strong>query&lt;/strong> containing the selected date range in the &lt;strong>request&lt;/strong>, receiving in return a response with an Excel file containing the data. &lt;em>How can we determine if the method is POST or GET?&lt;/em> It’s easy, by using a web analysis tool such as the &lt;strong>Chrome Developer Tools&lt;/strong>.&lt;/p>
&lt;div class="figure" style="text-align: center">
&lt;img src="images/HTMLI.png" alt="Figure 1" width="600px" />
&lt;p class="caption">&lt;span id="fig:unnamed-chunk-1">&lt;/span>Figure 1: Figure 1&lt;/p>
&lt;/div>
&lt;p>Clicking on the tools will display various options, with &lt;strong>Network&lt;/strong> being the most relevant for us right now. By clicking on Network, we can observe the interactions between our client (web page) and the COES server. To clean up the workspace, first click &lt;em>Clear&lt;/em>, which clears the window and helps focus on future interactions. Next, click on the &lt;strong>Export&lt;/strong> button on the COES webpage (after selecting the date range) to download the Excel file. In the &lt;em>Network&lt;/em> area, two interactions appear: having two interactions suggests that the method might be POST (one URL for sending and another for downloading).&lt;/p>
&lt;div class="figure" style="text-align: center">
&lt;img src="images/HTMLII.png" alt="Figure 2" width="700px" />
&lt;p class="caption">&lt;span id="fig:unnamed-chunk-2">&lt;/span>Figure 2: Figure 2&lt;/p>
&lt;/div>
&lt;p>Click on the first interaction (&lt;strong>exportargeneracion&lt;/strong>) to gather more information. Since it’s the first interaction, it should contain the &lt;strong>request&lt;/strong> sent to the server.&lt;/p>
&lt;div class="figure" style="text-align: center">
&lt;img src="images/request.png" alt="Figure 3" width="600px" />
&lt;p class="caption">&lt;span id="fig:unnamed-chunk-3">&lt;/span>Figure 3: Figure 3&lt;/p>
&lt;/div>
&lt;p>We can see that the &lt;strong>Request Method&lt;/strong> is indeed &lt;strong>POST&lt;/strong>. Additionally, the request URL is shown as &lt;em>&amp;ldquo;&lt;a href="https://www.coes.org.pe/Portal/portalinformacion/exportargeneracion%22">https://www.coes.org.pe/Portal/portalinformacion/exportargeneracion&amp;quot;&lt;/a>&lt;/em>. Finally, we see that three data elements are sent in the request: the start date (&lt;strong>fechaInicial&lt;/strong>), the end date (&lt;strong>fechaFinal&lt;/strong>), and an indicator (&lt;strong>indicador&lt;/strong>).&lt;/p>
&lt;p>It’s important to note the date format: &lt;em>day/month/year&lt;/em>, where both the day and the month always have two digits. This format is crucial when sending the request.&lt;/p>
&lt;p>A header acts as metadata (additional descriptive information, though not intrinsic to the request) that accompanies the request. In the image, there are 15 &lt;strong>request headers&lt;/strong>. While it’s not mandatory to use them, they can be helpful, as we will see later.&lt;/p>
&lt;p>Finally, the &lt;strong>Status Code = 200&lt;/strong> indicates that the interaction was successful.&lt;/p>
&lt;p>Thus, we can conclude that the method used to obtain this information was &lt;strong>POST&lt;/strong>, with the requested date range included in the request.&lt;/p>
&lt;blockquote>
&lt;p>However, since it’s a POST method, the request will not immediately provide a response. We need to check the second interaction to find out from which URL to download the data.&lt;/p>
&lt;/blockquote>
&lt;p>To do so, click on the second interaction (&lt;strong>descargargeneracion&lt;/strong>) to access the following information:&lt;/p>
&lt;div class="figure" style="text-align: center">
&lt;img src="images/response.png" alt="Figure 4" width="700px" />
&lt;p class="caption">&lt;span id="fig:unnamed-chunk-4">&lt;/span>Figure 4: Figure 4&lt;/p>
&lt;/div>
&lt;p>Here, we can see that an &amp;ldquo;&lt;em>access gateway&lt;/em>&amp;rdquo; to the data was opened at the URL: &lt;em>&amp;ldquo;&lt;a href="https://www.coes.org.pe/Portal/portalinformacion/descargargeneracion%22">https://www.coes.org.pe/Portal/portalinformacion/descargargeneracion&amp;quot;&lt;/a>&lt;/em>. This interaction uses a &lt;strong>GET&lt;/strong> method, meaning that by entering the URL, the server will automatically provide the data. Since the request data was already entered in the previous interaction, no additional data or &lt;strong>query&lt;/strong> is needed.&lt;/p>
&lt;h4 id="downloading-in-r">&lt;strong>Downloading in R&lt;/strong>&lt;/h4>
&lt;p>After analyzing the steps for downloading the files, we will now automate this process using R code. This will allow us to access the data directly through our code, enabling us to process it afterward.&lt;/p>
&lt;p>First, R requires a special package to handle HTTPS methods, called &lt;strong>httr&lt;/strong>. This package provides access to two essential functions, &lt;strong>GET&lt;/strong> and &lt;strong>POST&lt;/strong>, for downloading data. To install it, simply type &lt;em>install.packages(&amp;ldquo;httr&amp;rdquo;)&lt;/em> once in the RStudio console.&lt;/p>
&lt;p>After installing it, we invoke the library and use the POST method to download the file. Remember that the POST method requires two steps for file downloads: first, a POST request to send the data, and then a GET request to download the file from the temporary link that was opened. To download and read the data using the GET method, I will use the &lt;em>read.xlsx&lt;/em> function from the &lt;strong>openxlsx&lt;/strong> library, which allows downloading from a URL and reading an Excel file if contained within.&lt;/p>
&lt;p>Since the link is temporary, the two functions must be executed sequentially. Below, I will explain these steps:&lt;/p>
&lt;pre>&lt;code class="language-r">library(httr)
library(openxlsx)
fechaInicial = &amp;quot;07/09/2020&amp;quot;
fechaFinal = &amp;quot;07/09/2020&amp;quot;
POST(url = as.character(&amp;quot;https://www.coes.org.pe/Portal/portalinformacion/exportargeneracion&amp;quot;), config(ssl_verifypeer = FALSE), add_headers(&amp;quot;Referer&amp;quot;= &amp;quot;http://www.coes.org.pe/Portal/portalinformacion/generacion&amp;quot;),
body = list( &amp;quot;fechaInicial&amp;quot; = fechaInicial,
&amp;quot;fechaFinal&amp;quot;= fechaFinal,
&amp;quot;indicador&amp;quot;= 0)) ##Función POST envío los datos
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## Response [https://www.coes.org.pe/Portal/portalinformacion/exportargeneracion]
## Date: 2024-11-23 19:28
## Status: 200
## Content-Type: application/json; charset=utf-8
## Size: 1 B
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-r">datos = read.xlsx(&amp;quot;https://www.coes.org.pe/Portal/portalinformacion/descargargeneracion&amp;quot;,sheet = 1,detectDates = TRUE) ##Funcion GET descargo los datos
datos[1:5,] #ejemplo de 5 primeras filas
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## FECHA EMPRESA GRUPO/CENTRAL TIPO.GENERACIÓN
## 1 07/09/2020 AGRO INDUSTRIAL PARAMONGA PARAMONGA TERMOELÉCTRICA
## 2 07/09/2020 AGROAURORA S.A.C. MAPLE TERMOELÉCTRICA
## 3 07/09/2020 AGROINDUSTRIAS SAN JACINTO S.A.A. SAN_JACINTO TERMOELÉCTRICA
## 4 07/09/2020 AGUAS Y ENERGIA PERU PIAS1 HIDROELÉCTRICA
## 5 07/09/2020 ANDEAN POWER S.A.C. CARHUAC HIDROELÉCTRICA
## TOTAL
## 1 362.45
## 2 420.40
## 3 191.80
## 4 107.65
## 5 271.95
&lt;/code>&lt;/pre>
&lt;ul>
&lt;li>&lt;strong>POST&lt;/strong>: The function uses the POST method, sending a &lt;em>request&lt;/em> to the &lt;strong>URL&lt;/strong> &lt;em>&amp;ldquo;&lt;a href="https://www.coes.org.pe/Portal/portalinformacion/exportargeneracion%22">https://www.coes.org.pe/Portal/portalinformacion/exportargeneracion&amp;quot;&lt;/a>&lt;/em>, requesting the database we need between the dates &lt;strong>fechaInicial&lt;/strong> (&amp;ldquo;07/09/2020&amp;rdquo;) and &lt;strong>fechaFinal&lt;/strong> (&amp;ldquo;07/09/2020&amp;rdquo;). The &lt;em>query&lt;/em> can be added in the &lt;strong>body&lt;/strong> section as a list since there are multiple parameters. Finally, the indicator (&amp;ldquo;0&amp;rdquo;) seems to be a formality without any functionality. Note that we include the header &lt;em>&amp;ldquo;Referer&amp;rdquo;&lt;/em>.&lt;/li>
&lt;/ul>
&lt;blockquote>
&lt;p>If the response in the console displays &lt;strong>Status: 200&lt;/strong>, the request was successful. If this number does not appear, it means there was an error, and you should check the &lt;strong>Chrome Developer Tools&lt;/strong> to ensure the parameters have not changed (parameters often change a couple of times per year).&lt;/p>
&lt;/blockquote>
&lt;p>The following are additional parameters, which are not mandatory but can help avoid errors:&lt;/p>
&lt;p>A header acts as metadata (additional descriptive information, though not intrinsic to the request) included in the request. In this case, the header &lt;em>Referer&lt;/em> refers to the page from which we redirected to the specified URL. If we were using a web browser, we would make the request from &amp;ldquo;&lt;em>&lt;a href="http://www.coes.org.pe/Portal/portalinformacion/generacion">http://www.coes.org.pe/Portal/portalinformacion/generacion&lt;/a>&lt;/em>&amp;rdquo; (&lt;strong>Indicators Portal - Generation&lt;/strong>). While it is not necessary to include this, it informs the server that we accessed the data through a legitimate &lt;em>entry point&lt;/em> and are not hackers attempting to overload their website or access unauthorized pages. Some websites have stricter security measures, while others are more lenient.&lt;/p>
&lt;p>Finally, &lt;strong>SSL Verifier&lt;/strong> refers to whether the website has anti-scam protection (e.g., preventing credit card numbers from being stolen). It is not mandatory to tell the function to ignore this, but we explicitly set it to &lt;strong>FALSE&lt;/strong> just in case.&lt;/p>
&lt;ul>
&lt;li>&lt;strong>read.xlsx&lt;/strong>: The first parameter specifies the URL containing our Excel file. Since we performed the &lt;strong>POST&lt;/strong> function earlier, the URL &lt;em>&amp;ldquo;&lt;a href="https://www.coes.org.pe/Portal/portalinformacion/descargargeneracion%22">https://www.coes.org.pe/Portal/portalinformacion/descargargeneracion&amp;quot;&lt;/a>&lt;/em> opened a temporary link where the requested Excel file is located. &lt;strong>Sheet = 1&lt;/strong> indicates which sheet of the Excel file to read. Finally, &lt;strong>detectDates = TRUE&lt;/strong> ensures that Excel date formats are converted into standard date formats.&lt;/li>
&lt;/ul>
&lt;h4 id="processing-in-r">&lt;strong>Processing in R&lt;/strong>&lt;/h4>
&lt;p>I will use the &lt;strong>Tidyverse&lt;/strong> library, which provides several tools for data manipulation.&lt;/p>
&lt;pre>&lt;code class="language-r">library(tidyverse)
&lt;/code>&lt;/pre>
&lt;p>To get an overview of the data:&lt;/p>
&lt;pre>&lt;code class="language-r">glimpse(datos)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## Rows: 111
## Columns: 5
## $ FECHA &amp;lt;chr&amp;gt; &amp;quot;07/09/2020&amp;quot;, &amp;quot;07/09/2020&amp;quot;, &amp;quot;07/09/2020&amp;quot;, &amp;quot;07/09/2020&amp;quot;…
## $ EMPRESA &amp;lt;chr&amp;gt; &amp;quot;AGRO INDUSTRIAL PARAMONGA&amp;quot;, &amp;quot;AGROAURORA S.A.C.&amp;quot;, &amp;quot;AGR…
## $ `GRUPO/CENTRAL` &amp;lt;chr&amp;gt; &amp;quot;PARAMONGA&amp;quot;, &amp;quot;MAPLE&amp;quot;, &amp;quot;SAN_JACINTO&amp;quot;, &amp;quot;PIAS1&amp;quot;, &amp;quot;CARHUAC…
## $ TIPO.GENERACIÓN &amp;lt;chr&amp;gt; &amp;quot;TERMOELÉCTRICA&amp;quot;, &amp;quot;TERMOELÉCTRICA&amp;quot;, &amp;quot;TERMOELÉCTRICA&amp;quot;, …
## $ TOTAL &amp;lt;dbl&amp;gt; 362.45, 420.40, 191.80, 107.65, 271.95, 6.15, 242.40, …
&lt;/code>&lt;/pre>
&lt;p>The downloaded data contains five columns: &lt;strong>Fecha&lt;/strong> (Date), &lt;strong>Empresa&lt;/strong> (Company), &lt;strong>Grupo&lt;/strong> (Group), &lt;strong>Tipo de Generación&lt;/strong> (Type of Generation), and &lt;strong>Total&lt;/strong> (MWh).&lt;/p>
&lt;p>Typically, we only need to retain the &lt;strong>Fecha&lt;/strong> and &lt;strong>Total&lt;/strong> columns. However, the additional information can be useful for analysts (e.g., identifying generation from agricultural companies to infer sector activity or comparing gas, solar, and other types of generation).&lt;/p>
&lt;p>Additionally, we might have downloaded data for a date range greater than one day. To aggregate total generation by day, we group the data by &lt;strong>FECHA&lt;/strong>. Finally, we sum the values by day and &lt;strong>convert MWh to GWh by dividing by 1,000&lt;/strong>.&lt;/p>
&lt;pre>&lt;code class="language-r">datos %&amp;gt;% # Access the data
select(FECHA, TOTAL) %&amp;gt;% # Select Date and Total (MWh)
group_by(FECHA) %&amp;gt;% # Group by day
summarise(GWh = sum(TOTAL, na.rm = FALSE) / 1000) %&amp;gt;% # Sum and convert to GWh
ungroup() # Ungroup (optional)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## # A tibble: 1 × 2
## FECHA GWh
## &amp;lt;chr&amp;gt; &amp;lt;dbl&amp;gt;
## 1 07/09/2020 141.
&lt;/code>&lt;/pre>
&lt;p>This gives us daily data in GWh. The next step would be &lt;strong>adding the data to a historical database&lt;/strong>. We won&amp;rsquo;t delve into that here but will instead move on to the next topic: &lt;strong>IEOD&lt;/strong>.&lt;/p>
&lt;h3 id="coes-ieod">COES: IEOD&lt;/h3>
&lt;p>Similar to the &lt;em>Indicators of the Peruvian Energy Sector&lt;/em>, we first need to access the IEOD platform and check whether the download function uses &lt;strong>POST&lt;/strong> or &lt;strong>GET&lt;/strong>.&lt;/p>
&lt;div class="figure" style="text-align: center">
&lt;img src="images/IEOD_GET.png" alt="Figure 1" width="500px" />
&lt;p class="caption">&lt;span id="fig:unnamed-chunk-9">&lt;/span>Figure 5: Figure 1&lt;/p>
&lt;/div>
&lt;p>On the IEOD platform, select a date and the desired Excel file (e.g., &amp;ldquo;&lt;strong>Anexo1_Resumen_0709.xlsx&lt;/strong>&amp;quot;). By &lt;strong>right-clicking on the link&lt;/strong>, you can copy the URL address.&lt;/p>
&lt;p>In this case, the copied address is: &lt;em>&amp;ldquo;&lt;a href="https://www.coes.org.pe/portal/browser/">https://www.coes.org.pe/portal/browser/&lt;/a>&lt;strong>download?url=Post%20Operaci%C3%B3n%2FReportes%2FIEOD%2F2020%2F09%20Setiembre%2F07%2FAnexo1_Resumen_0709.xlsx&lt;/strong>&amp;quot;&lt;/em>. From the bold portion, it is clear that this is a &lt;strong>GET&lt;/strong> method (the data included in the &lt;strong>request&lt;/strong> is visible in the URL, which is not the case with POST). However, what parts of the request change, and what do the strange characters like &lt;strong>%2F&lt;/strong>, &lt;strong>%20&lt;/strong>, or &lt;strong>%C3%B3&lt;/strong> mean?&lt;/p>
&lt;p>By reviewing the &lt;strong>Network&lt;/strong> section of the &lt;strong>Chrome Developer Tools&lt;/strong>, we can see that the &lt;strong>query&lt;/strong> starts after &lt;em>download?url=&lt;/em>.&lt;/p>
&lt;div class="figure" style="text-align: center">
&lt;img src="images/query1.png" alt="Figure 2" width="500px" />
&lt;p class="caption">&lt;span id="fig:unnamed-chunk-10">&lt;/span>Figure 6: Figure 2&lt;/p>
&lt;/div>
&lt;p>Based on the information above, we can infer that the &lt;strong>GET&lt;/strong> portion carrying the data, i.e., the &lt;strong>query&lt;/strong>, is:&lt;br>
*&amp;ldquo;Post Operación/Reportes/IEOD/&lt;strong>2020&lt;/strong>/&lt;strong>09 Setiembre&lt;/strong>/&lt;strong>07&lt;/strong>/Anexo1_Resumen_**0709**.xlsx&amp;rdquo;*. Here’s what each bold element represents:&lt;/p>
&lt;ul>
&lt;li>&lt;strong>Year&lt;/strong> (e.g., &lt;strong>2020&lt;/strong>)&lt;/li>
&lt;li>&lt;strong>Month in numbers and letters&lt;/strong> (e.g., &lt;strong>09 Setiembre&lt;/strong>)&lt;/li>
&lt;li>&lt;strong>Day number&lt;/strong> (e.g., &lt;strong>07&lt;/strong>)&lt;/li>
&lt;li>&lt;strong>Day and month number combined&lt;/strong> (e.g., &lt;strong>0709&lt;/strong>)&lt;/li>
&lt;/ul>
&lt;p>If you click on &lt;em>view URL encoded&lt;/em>, you will see that the encoded portion of the URL (&lt;em>Post%20Operaci%C3%B3n%2FReportes%2FIEOD%2F2020%2F09%20Setiembre%2F07%2FAnexo1_Resumen_0709.xlsx&lt;/em>) translates as follows:&lt;/p>
&lt;ul>
&lt;li>&lt;strong>%20&lt;/strong> = space&lt;/li>
&lt;li>&lt;strong>%C3%B3&lt;/strong> = &amp;ldquo;ó&amp;rdquo; (accented letter)&lt;/li>
&lt;li>&lt;strong>%2F&lt;/strong> = &amp;ldquo;/&amp;rdquo; (slash)&lt;/li>
&lt;/ul>
&lt;p>In conclusion, the IEOD data is downloaded using the &lt;strong>GET&lt;/strong> method, with the date details included in the &lt;strong>request&lt;/strong> and embedded in the URL.&lt;/p>
&lt;h4 id="downloading-in-r-1">&lt;strong>Downloading in R&lt;/strong>&lt;/h4>
&lt;p>With the knowledge gained earlier, we are ready to automate the download process. First, I will create the download URL by selecting the desired date and then converting it into the &lt;strong>GET&lt;/strong> syntax identified earlier.&lt;/p>
&lt;p>To work with dates, I will use the &lt;strong>Lubridate&lt;/strong> library. To avoid potential issues with the spelling of the month &amp;ldquo;September&amp;rdquo; (Setiembre?), I will use a different date in October instead.&lt;/p>
&lt;pre>&lt;code class="language-r">library(lubridate)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-r">library(lubridate)
fecha = as.Date(&amp;quot;2023/10/07&amp;quot;)
Sys.setlocale(&amp;quot;LC_TIME&amp;quot;, &amp;quot;es_ES&amp;quot;)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## [1] &amp;quot;es_ES&amp;quot;
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-r">format &amp;lt;- &amp;quot;%a@%A@%b@%B@%p@&amp;quot;
library(lubridate)
path = paste(&amp;quot;https://www.coes.org.pe/portal/browser/download?url=Post%20Operaci%C3%B3n%2FReportes%2FIEOD%2F&amp;quot;,
year(fecha), #El año
&amp;quot;%2F&amp;quot;, # dash (/)
sprintf(&amp;quot;%02d&amp;quot;,month(fecha)), #número del mes, en 2 dígitos
&amp;quot;_&amp;quot;, #espacio
str_to_title(month(fecha,label=TRUE,abbr = FALSE)), #mes en letras
#How to put the output of month() in spanish?
&amp;quot;%2F&amp;quot;, # dash (/)
sprintf(&amp;quot;%02d&amp;quot;,day(fecha)), #número del día en 2 dígitos
&amp;quot;%2FAnexo1_Resumen_&amp;quot;,
sprintf(&amp;quot;%02d&amp;quot;,day(fecha)), #numero del dia
sprintf(&amp;quot;%02d&amp;quot;,month(fecha)),#numero del mes
&amp;quot;.xlsx&amp;quot;,
sep=&amp;quot;&amp;quot;) #concateno las partes en uno solo
path
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## [1] &amp;quot;https://www.coes.org.pe/portal/browser/download?url=Post%20Operaci%C3%B3n%2FReportes%2FIEOD%2F2023%2F10_Octubre%2F07%2FAnexo1_Resumen_0710.xlsx&amp;quot;
&lt;/code>&lt;/pre>
&lt;p>&lt;a href="https://www.coes.org.pe/portal/browser/download?url=Post%20Operaci%C3%B3n%2FReportes%2FIEOD%2F2023%2F10_Octubre%2F19%2FAnexo1_Resumen_1910.xlsx">https://www.coes.org.pe/portal/browser/download?url=Post%20Operaci%C3%B3n%2FReportes%2FIEOD%2F2023%2F10_Octubre%2F19%2FAnexo1_Resumen_1910.xlsx&lt;/a>
Next, I will verify that the link works and successfully downloads electricity demand by geographic zone as well as demand for large free users (mining and manufacturing).&lt;/p>
&lt;h4 id="downloading-geographic-zone-data">&lt;strong>Downloading Geographic Zone Data&lt;/strong>&lt;/h4>
&lt;p>&lt;a href="https://www.coes.org.pe/portal/browser/download?url=Post%20Operaci%C3%B3n%2FReportes%2FIEOD%2F2024%2F11_Noviembre%2F17%2FAnexoA_1711.xlsx">https://www.coes.org.pe/portal/browser/download?url=Post%20Operaci%C3%B3n%2FReportes%2FIEOD%2F2024%2F11_Noviembre%2F17%2FAnexoA_1711.xlsx&lt;/a>&lt;/p>
&lt;pre>&lt;code class="language-r">library(openxlsx)
zonas = read.xlsx(path, sheet = &amp;quot;DEMANDA_AREAS&amp;quot;, rows = c(12, 64), cols = c(5:7)) / 1000
zonas
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## NORTE CENTRO SUR
## 1 24.25947 94.15946 41.00531
&lt;/code>&lt;/pre>
&lt;p>As shown above, I downloaded the Excel file located at the &lt;strong>path&lt;/strong> URL. From that Excel file, I selected the &lt;strong>DEMANDA_AREAS&lt;/strong> sheet, which contains electricity demand in Peru, divided into three zones (North, Center, and South). From this sheet, I chose the columns (&lt;strong>cols&lt;/strong>) containing demand by zone (columns 5 to 7). Additionally, I selected rows (&lt;strong>rows&lt;/strong>) 12 (containing the column names) and 64 (containing the total daily consumption). Finally, I divided the values by 1,000 to convert the data from MWh to GWh.&lt;/p>
&lt;h4 id="downloading-large-free-users-data-mining-and-manufacturing">&lt;strong>Downloading Large Free Users Data (Mining and Manufacturing)&lt;/strong>&lt;/h4>
&lt;pre>&lt;code class="language-r">usuarios_libres = read.xlsx(path, sheet = &amp;quot;DEMANDA_UL&amp;quot;, rows = c(20, 69))
duplicated_cols &amp;lt;- names(usuarios_libres)[duplicated(names(usuarios_libres))]
print(usuarios_libres)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## X1 CEMENTOS.PACASMAYO CREDITEX INDUSTRIAL.PIURA MINERA.HORIZONTE-LLACUABAMBA
## 1 MWh 1019.079 0 0 0
## YANACOCHA BARRICK.-.PIERINA BARRICK-.ALTO.CHICAMA MISKIMAYO-BAYOBAR
## 1 681.969 0 0 279.545
## GOLD.FIELD MARSA SIDER.PERU TRUPAL AGROPECUARIA.AURORA
## 1 629.1684 301.3809 979.8908 241.25 312.375
## PETROPERU.CL-6769.SE.GE1 PETROPERU.CL-6768.SE.GE1 ACEROS.AREQUIPA
## 1 587.759 0 1997.334
## JOCKEY.PLAZA ALICORP MINERA.ALPAYANA COMPAÑÍA.MINERA.CHUNGAR
## 1 0 229.4557 384.1315 337.6162
## COMPAÑÍA.MINERA.CONDESTABLE CREDITEX.-.INDEPENDENCIA CREDITEX.-.INGENIEROS
## 1 366.12 0 0
## EL.BROCAL ADMINISTRADORA.CERRO KIMBERLY.CLARK.PERU LECHE.GLORIA MARCOBRE
## 1 817.9798 93.22284 0 0 1153.913
## MEPSA MINERA.ANTAMINA MINERA.BUENAVENTURA.(UCHUCHACUA+HUANCAVELICA) CHINALCO
## 1 0 3036.311 122.29 3607.068
## MINERA.CORONA LOS.QUENUALES MINERA.SHOUXIN MINERA.VOLCAN MINSUR
## 1 131.204 0 324.9498 1141.029 67.78
## NEXA.RESOURCES.CAJAMARQUILLA NEXA.RESOURCES.-.DESIERTO NEXA.RESOURCES.-.PASCO
## 1 3910.832 773.12 328.9331
## OPP.FILM OXIDOS.PASCO PANASA SOFTYS.PERU QUIMPAC.-.PARAMONGA
## 1 76.87446 114.1832 104.4 278.3232 434.8822
## QUIMPAC.-.OQUENDO REFINERIA.LA.PAMPILLA SHOUGANG.HIERRO.PERU
## 1 1050.251 480.05 0
## TEJIDOS.SAN.JACINTO TRUPAL.-.ZARATE UNACEM-ANDINO UNACEM-LIMA MARCOBRE
## 1 109.318 209.0815 666.175 731.5305 1153.913
## ANGLO.AMERICAN.QUELLAVECO CAL.&amp;amp;.CEMENTO.SUR ANTAPACCAY HUDBAY.PERU
## 1 1254.671 74.97723 2740.34 0
## INDUSTRIAS.CACHIMAYO ARES-COTARUSE ARES-CALLALLI MINERA.BUENAVENTURA.-.ARES
## 1 442.9391 672.1465 18.83618 160.93
## MINERA.BUENAVENTURA.-.TAMBOMAYO CERRO.VERDE.(HIDROMETALÚRGICA)
## 1 176.635 610.3554
## CERRO.VERDE.-.SULFUROS CERRO.VERDE.(AMPLIACIÓN) LAS_BAMBAS
## 1 3371.444 6939.944 3678.651
## MINSUR.-.SAN.RAFAEL MINSUR.-.PUCAMARCA SPCC CEMENTOS.YURA
## 1 674.5289 0 6634.635 800.1874
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-r"># Make column names unique
names(usuarios_libres) &amp;lt;- make.names(names(usuarios_libres), unique = TRUE)
# Proceed with select() or other operations
usuarios_libres &amp;lt;- usuarios_libres %&amp;gt;% select(-X1)
sample(usuarios_libres, size = 4) # Display 4 sample companies
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## SHOUGANG.HIERRO.PERU ALICORP MINERA.BUENAVENTURA...ARES HUDBAY.PERU
## 1 0 229.4557 160.93 0
&lt;/code>&lt;/pre>
&lt;p>As shown above, I downloaded the Excel file located at the &lt;strong>path&lt;/strong> URL. From that Excel file, I selected the &lt;strong>DEMANDA_UL&lt;/strong> sheet, which contains the demand data for large free users. From this sheet, I chose rows (&lt;strong>rows&lt;/strong>) 20 (which contains company names) and 69 (which contains the total daily consumption).&lt;/p>
&lt;h5 id="data-cleaning">Data Cleaning&lt;/h5>
&lt;p>Cleaning the name of the variables:&lt;/p>
&lt;pre>&lt;code class="language-r">nombres = names(usuarios_libres) #nombre de las variables
nombres = gsub(&amp;quot;\\.&amp;quot;,&amp;quot; &amp;quot;,nombres) #cambio puntos por espacios
nombres[which(nombres==&amp;quot;CERRO VERDE HIDROMETALÚRGICA&amp;quot;)] = &amp;quot;REFINERIA CERRO VERDE&amp;quot;
nombres[which(nombres==&amp;quot;VOTORANTIM METAIS CAJAMARQUILLA&amp;quot;)] = &amp;quot;REFINERIA CAJAMARQUILLA&amp;quot;
nombres[which(nombres==&amp;quot;ANTAMINA+09 OCTUBRE &amp;quot;)] = &amp;quot;ANTAMINA&amp;quot;
nombres[which(nombres==&amp;quot;UNACEM-LIMA&amp;quot;)] = &amp;quot;CEMENTOS LIMA&amp;quot;
nombres[which(nombres==&amp;quot;UNACEM-ANDINO&amp;quot;)] = &amp;quot;CEMENTOS ANDINO&amp;quot;
nombres[which(nombres==&amp;quot;INCASAC&amp;quot;)] = &amp;quot;CACHIMAYO&amp;quot;
nombres[which(nombres==&amp;quot;SPCC&amp;quot;)] = &amp;quot;SOUTHERN PERU&amp;quot;
names(usuarios_libres) = nombres
nombres
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## [1] &amp;quot;CEMENTOS PACASMAYO&amp;quot;
## [2] &amp;quot;CREDITEX&amp;quot;
## [3] &amp;quot;INDUSTRIAL PIURA&amp;quot;
## [4] &amp;quot;MINERA HORIZONTE LLACUABAMBA&amp;quot;
## [5] &amp;quot;YANACOCHA&amp;quot;
## [6] &amp;quot;BARRICK PIERINA&amp;quot;
## [7] &amp;quot;BARRICK ALTO CHICAMA&amp;quot;
## [8] &amp;quot;MISKIMAYO BAYOBAR&amp;quot;
## [9] &amp;quot;GOLD FIELD&amp;quot;
## [10] &amp;quot;MARSA&amp;quot;
## [11] &amp;quot;SIDER PERU&amp;quot;
## [12] &amp;quot;TRUPAL&amp;quot;
## [13] &amp;quot;AGROPECUARIA AURORA&amp;quot;
## [14] &amp;quot;PETROPERU CL 6769 SE GE1&amp;quot;
## [15] &amp;quot;PETROPERU CL 6768 SE GE1&amp;quot;
## [16] &amp;quot;ACEROS AREQUIPA&amp;quot;
## [17] &amp;quot;JOCKEY PLAZA&amp;quot;
## [18] &amp;quot;ALICORP&amp;quot;
## [19] &amp;quot;MINERA ALPAYANA&amp;quot;
## [20] &amp;quot;COMPAÑÍA MINERA CHUNGAR&amp;quot;
## [21] &amp;quot;COMPAÑÍA MINERA CONDESTABLE&amp;quot;
## [22] &amp;quot;CREDITEX INDEPENDENCIA&amp;quot;
## [23] &amp;quot;CREDITEX INGENIEROS&amp;quot;
## [24] &amp;quot;EL BROCAL&amp;quot;
## [25] &amp;quot;ADMINISTRADORA CERRO&amp;quot;
## [26] &amp;quot;KIMBERLY CLARK PERU&amp;quot;
## [27] &amp;quot;LECHE GLORIA&amp;quot;
## [28] &amp;quot;MARCOBRE&amp;quot;
## [29] &amp;quot;MEPSA&amp;quot;
## [30] &amp;quot;MINERA ANTAMINA&amp;quot;
## [31] &amp;quot;MINERA BUENAVENTURA UCHUCHACUA HUANCAVELICA &amp;quot;
## [32] &amp;quot;CHINALCO&amp;quot;
## [33] &amp;quot;MINERA CORONA&amp;quot;
## [34] &amp;quot;LOS QUENUALES&amp;quot;
## [35] &amp;quot;MINERA SHOUXIN&amp;quot;
## [36] &amp;quot;MINERA VOLCAN&amp;quot;
## [37] &amp;quot;MINSUR&amp;quot;
## [38] &amp;quot;NEXA RESOURCES CAJAMARQUILLA&amp;quot;
## [39] &amp;quot;NEXA RESOURCES DESIERTO&amp;quot;
## [40] &amp;quot;NEXA RESOURCES PASCO&amp;quot;
## [41] &amp;quot;OPP FILM&amp;quot;
## [42] &amp;quot;OXIDOS PASCO&amp;quot;
## [43] &amp;quot;PANASA&amp;quot;
## [44] &amp;quot;SOFTYS PERU&amp;quot;
## [45] &amp;quot;QUIMPAC PARAMONGA&amp;quot;
## [46] &amp;quot;QUIMPAC OQUENDO&amp;quot;
## [47] &amp;quot;REFINERIA LA PAMPILLA&amp;quot;
## [48] &amp;quot;SHOUGANG HIERRO PERU&amp;quot;
## [49] &amp;quot;TEJIDOS SAN JACINTO&amp;quot;
## [50] &amp;quot;TRUPAL ZARATE&amp;quot;
## [51] &amp;quot;UNACEM ANDINO&amp;quot;
## [52] &amp;quot;UNACEM LIMA&amp;quot;
## [53] &amp;quot;MARCOBRE 1&amp;quot;
## [54] &amp;quot;ANGLO AMERICAN QUELLAVECO&amp;quot;
## [55] &amp;quot;CAL CEMENTO SUR&amp;quot;
## [56] &amp;quot;ANTAPACCAY&amp;quot;
## [57] &amp;quot;HUDBAY PERU&amp;quot;
## [58] &amp;quot;INDUSTRIAS CACHIMAYO&amp;quot;
## [59] &amp;quot;ARES COTARUSE&amp;quot;
## [60] &amp;quot;ARES CALLALLI&amp;quot;
## [61] &amp;quot;MINERA BUENAVENTURA ARES&amp;quot;
## [62] &amp;quot;MINERA BUENAVENTURA TAMBOMAYO&amp;quot;
## [63] &amp;quot;CERRO VERDE HIDROMETALÚRGICA &amp;quot;
## [64] &amp;quot;CERRO VERDE SULFUROS&amp;quot;
## [65] &amp;quot;CERRO VERDE AMPLIACIÓN &amp;quot;
## [66] &amp;quot;LAS_BAMBAS&amp;quot;
## [67] &amp;quot;MINSUR SAN RAFAEL&amp;quot;
## [68] &amp;quot;MINSUR PUCAMARCA&amp;quot;
## [69] &amp;quot;SOUTHERN PERU&amp;quot;
## [70] &amp;quot;CEMENTOS YURA&amp;quot;
&lt;/code>&lt;/pre>
&lt;p>The &lt;em>which&lt;/em> function returns an index, which is the column number that satisfies the test (e.g., names == &amp;ldquo;X1&amp;rdquo;).&lt;/p>
&lt;p>Some companies may have more than one measurement point. For instance, Cerro Verde has three: its &lt;strong>old mine&lt;/strong> (Sulfuros), its &lt;strong>mine expansion&lt;/strong> (Ampliación), and its &lt;strong>hydrometallurgy center&lt;/strong> (Refinería). In this case, we sum the consumption of its old mine and the expansion, consolidating it into two measurement points (refinery and mine).&lt;/p>
&lt;pre>&lt;code class="language-r">usuarios_libres = usuarios_libres %&amp;gt;%
mutate(&amp;quot;CERRO VERDE&amp;quot; = `CERRO VERDE SULFUROS` + `CERRO VERDE AMPLIACIÓN `,
.after = `CERRO VERDE AMPLIACIÓN `) %&amp;gt;% # Sum two columns
select(-`CERRO VERDE SULFUROS`, -`CERRO VERDE AMPLIACIÓN `) # Remove old columns
&lt;/code>&lt;/pre>
&lt;p>With the data from the major electricity-demanding companies (large free users), I can categorize them based on their economic activities. The main sectors where electricity consumption is closely tied to production are &lt;strong>mining&lt;/strong> and &lt;strong>manufacturing&lt;/strong>.&lt;/p>
&lt;p>I already know which columns correspond to mining companies, so I will select only those.&lt;/p>
&lt;pre>&lt;code class="language-r">minerias = usuarios_libres %&amp;gt;%
select(1,2,4,5,6,9,11,12,17,20,24,25,27,28,30,31,32,33,34,35,38,40,41,42,43) # Select mining companies
names(minerias)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## [1] &amp;quot;CEMENTOS PACASMAYO&amp;quot;
## [2] &amp;quot;CREDITEX&amp;quot;
## [3] &amp;quot;MINERA HORIZONTE LLACUABAMBA&amp;quot;
## [4] &amp;quot;YANACOCHA&amp;quot;
## [5] &amp;quot;BARRICK PIERINA&amp;quot;
## [6] &amp;quot;GOLD FIELD&amp;quot;
## [7] &amp;quot;SIDER PERU&amp;quot;
## [8] &amp;quot;TRUPAL&amp;quot;
## [9] &amp;quot;JOCKEY PLAZA&amp;quot;
## [10] &amp;quot;COMPAÑÍA MINERA CHUNGAR&amp;quot;
## [11] &amp;quot;EL BROCAL&amp;quot;
## [12] &amp;quot;ADMINISTRADORA CERRO&amp;quot;
## [13] &amp;quot;LECHE GLORIA&amp;quot;
## [14] &amp;quot;MARCOBRE&amp;quot;
## [15] &amp;quot;MINERA ANTAMINA&amp;quot;
## [16] &amp;quot;MINERA BUENAVENTURA UCHUCHACUA HUANCAVELICA &amp;quot;
## [17] &amp;quot;CHINALCO&amp;quot;
## [18] &amp;quot;MINERA CORONA&amp;quot;
## [19] &amp;quot;LOS QUENUALES&amp;quot;
## [20] &amp;quot;MINERA SHOUXIN&amp;quot;
## [21] &amp;quot;NEXA RESOURCES CAJAMARQUILLA&amp;quot;
## [22] &amp;quot;NEXA RESOURCES PASCO&amp;quot;
## [23] &amp;quot;OPP FILM&amp;quot;
## [24] &amp;quot;OXIDOS PASCO&amp;quot;
## [25] &amp;quot;PANASA&amp;quot;
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-r">minerias %&amp;gt;%
transmute(Minas_GWh = rowSums(.) / 1000) # Sum mining company data
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## Minas_GWh
## 1 17.71114
&lt;/code>&lt;/pre>
&lt;p>We can see that the mining companies consumed 2023-10-07 a total of 17.7 GWh.&lt;/p>
&lt;p>Companies related to commerce/services, like Jockey Plaza Mall, do not have a strong relationship between production and electricity consumption, so they are excluded.&lt;/p>
&lt;pre>&lt;code class="language-r">manufactureras = usuarios_libres %&amp;gt;%
select(-names(minerias)) # Select manufacturers
names(manufactureras)
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## [1] &amp;quot;INDUSTRIAL PIURA&amp;quot; &amp;quot;BARRICK ALTO CHICAMA&amp;quot;
## [3] &amp;quot;MISKIMAYO BAYOBAR&amp;quot; &amp;quot;MARSA&amp;quot;
## [5] &amp;quot;AGROPECUARIA AURORA&amp;quot; &amp;quot;PETROPERU CL 6769 SE GE1&amp;quot;
## [7] &amp;quot;PETROPERU CL 6768 SE GE1&amp;quot; &amp;quot;ACEROS AREQUIPA&amp;quot;
## [9] &amp;quot;ALICORP&amp;quot; &amp;quot;MINERA ALPAYANA&amp;quot;
## [11] &amp;quot;COMPAÑÍA MINERA CONDESTABLE&amp;quot; &amp;quot;CREDITEX INDEPENDENCIA&amp;quot;
## [13] &amp;quot;CREDITEX INGENIEROS&amp;quot; &amp;quot;KIMBERLY CLARK PERU&amp;quot;
## [15] &amp;quot;MEPSA&amp;quot; &amp;quot;MINERA VOLCAN&amp;quot;
## [17] &amp;quot;MINSUR&amp;quot; &amp;quot;NEXA RESOURCES DESIERTO&amp;quot;
## [19] &amp;quot;SOFTYS PERU&amp;quot; &amp;quot;QUIMPAC PARAMONGA&amp;quot;
## [21] &amp;quot;QUIMPAC OQUENDO&amp;quot; &amp;quot;REFINERIA LA PAMPILLA&amp;quot;
## [23] &amp;quot;SHOUGANG HIERRO PERU&amp;quot; &amp;quot;TEJIDOS SAN JACINTO&amp;quot;
## [25] &amp;quot;TRUPAL ZARATE&amp;quot; &amp;quot;UNACEM ANDINO&amp;quot;
## [27] &amp;quot;UNACEM LIMA&amp;quot; &amp;quot;MARCOBRE 1&amp;quot;
## [29] &amp;quot;ANGLO AMERICAN QUELLAVECO&amp;quot; &amp;quot;CAL CEMENTO SUR&amp;quot;
## [31] &amp;quot;ANTAPACCAY&amp;quot; &amp;quot;HUDBAY PERU&amp;quot;
## [33] &amp;quot;INDUSTRIAS CACHIMAYO&amp;quot; &amp;quot;ARES COTARUSE&amp;quot;
## [35] &amp;quot;ARES CALLALLI&amp;quot; &amp;quot;MINERA BUENAVENTURA ARES&amp;quot;
## [37] &amp;quot;MINERA BUENAVENTURA TAMBOMAYO&amp;quot; &amp;quot;CERRO VERDE HIDROMETALÚRGICA &amp;quot;
## [39] &amp;quot;CERRO VERDE&amp;quot; &amp;quot;LAS_BAMBAS&amp;quot;
## [41] &amp;quot;MINSUR SAN RAFAEL&amp;quot; &amp;quot;MINSUR PUCAMARCA&amp;quot;
## [43] &amp;quot;SOUTHERN PERU&amp;quot; &amp;quot;CEMENTOS YURA&amp;quot;
&lt;/code>&lt;/pre>
&lt;pre>&lt;code class="language-r">manufactureras %&amp;gt;%
transmute(Manufact_GWh = rowSums(.) / 1000) # Calculate consumption
&lt;/code>&lt;/pre>
&lt;pre>&lt;code>## Manufact_GWh
## 1 39.80477
&lt;/code>&lt;/pre>
&lt;p>We can see that the manufacturing companies consumed 2023-10-07 a total of 39.8 GWh.&lt;/p></description></item></channel></rss>