<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Koustav on Medium]]></title>
        <description><![CDATA[Stories by Koustav on Medium]]></description>
        <link>https://medium.com/@koustavin?source=rss-de554458f133------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5Y7afv_hJtWWLxuKxihiTA.jpeg</url>
            <title>Stories by Koustav on Medium</title>
            <link>https://medium.com/@koustavin?source=rss-de554458f133------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:07:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@koustavin/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[IMDB SQL Data Analysis : Part III — Customized Ranking for Movies and Filmmakers]]></title>
            <link>https://blog.devops.dev/imdb-sql-data-analysis-part-iii-customized-ranking-for-movies-and-filmmakers-1805931b4b6d?source=rss-de554458f133------2</link>
            <guid isPermaLink="false">https://medium.com/p/1805931b4b6d</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[portfolio-project]]></category>
            <category><![CDATA[imdb]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Koustav]]></dc:creator>
            <pubDate>Wed, 12 Apr 2023 19:09:41 GMT</pubDate>
            <atom:updated>2023-04-17T14:51:39.788Z</atom:updated>
            <content:encoded><![CDATA[<h3>IMDB SQL Data Analysis : Part III — Customized Ranking for Movies and Filmmakers</h3><p>This is the Final part of my IMDB Data Analysis on SQL, and hopefully time to get to real results after spending a lot of effort in preparation.</p><p><strong>Recap :</strong> The First part was all about setting up the database from IMDB flat files, building relations, and extracting implicit features — all on MySQL. You can read about it here —</p><p><a href="https://medium.com/@koustavin/imdb-sql-data-analysis-database-design-492751ab16c4">IMDB SQL Data Analysis : PART I — Building and Designing The Database on MySQL</a></p><p>The Second part described the project objectives and clarified some core assumptions that we will need to find our answers. For that we did some comparative exploration of our database and IMDB Webpage. On our way, we also found limitations in our data that will prevent us from fulfilling at least some of our objectives. In terms of Movie Trilogies, it was truly the dark and gritty 2nd movie —</p><p><a href="https://medium.com/@koustavin/imdb-sql-data-analysis-part-ii-the-objectives-assumptions-and-data-exploration-b8fae4329f93">IMDB SQL Data Analysis : Part II — The Objectives &amp; Assumptions, and Data Exploration</a></p><p>And now here comes the final installment, where hopefully the protagonist gets to the answers, which he/she was seeking all along, before the curtain draws and we all get closure. Let’s find out.</p><p>The objectives (that we can hopefully fulfill) once more —</p><ol><li>Determine Ratings for Movie Directors and Writers. Also, find out Top 5 Directors and Writers in each Genre</li><li>Top 50 Episodes of TV Series (based on Ratings)</li><li>Top 5 Highest Rated Movies from last 5 Years, and compare them with Most Rated (based on Number of Votes) Movies</li><li>Top 5 Movies from Each Decade, starting with the Eighties</li></ol><p><strong>Scripts and Other Files :</strong> All files related to this project are available at <a href="https://github.com/koustavin/IMDB-SQLAnalysis">GitHub</a>. Be warned though, a lot of queries and files are unrelated to the final version of this work, so looking at the scripts by themselves might feel confusing. The files are not clean, but the main learnings and findings have been summarized in these articles. The final version of the queries used for answering the questions above are stored in Final_Queries.sql, and their output in <a href="https://github.com/koustavin/IMDB-SQLAnalysis/blob/main/Final_Resultset.xlsx">Final_Resultset.xlsx</a>.</p><p>Let’s get on with the analysis now.</p><p><strong>Directors/Writers’ Ratings :</strong> We had decided on a few criteria for our Ratings system after exploring how IMDB does it in the previous section — we would only consider titles with at least 25000 votes, and we will look at titleType = movie (for the current objective). The ratings for these titles would be attributed to their director/writer, and then we’ll take an arithmetic mean to arrive at overall Ratings.</p><p><strong>Movies with Multiple Directors/Writers :</strong> We should take note of an important consideration here — we have more than 26 thousand movie titles having more than one directors. I haven’t checked, but movies with multiple writers should be much more — since most of the movies have different writers credited for Story, Dialogue etc., and even directors are often credited as writers for Screenplay. We had comma separated directors, and writers in title_crew table for these records, we split that table (and learnt <a href="https://medium.com/@koustavin/imdb-sql-data-analysis-database-design-492751ab16c4">something</a> in the process) to identify individual members. <em>We would be using these multi-entry tables in our queries. As such, each director (of a multi-director movie) will be credited with same Ratings as that of the movie.</em></p><p>As an example, consider the movie Avengers: Endgame — Russo brothers (Joe and Anthony) directed the movie together, and it has a Rating of 8.4. Now, both the directors would be getting this rating — so, in a way we are doubling the total rating here initially. But this will be balanced out when we take the average in the final step. At first, I wanted to assign the rating of 4.2 to each director — but that actually penalizes the directors in the final calculation, since while we are calculating the average for this movie, it counts as one full movie in the denominator, but in the nominator they are only getting half the score of the movie.</p><p>We could have simply ignored all the titles with multiple directors/writers altogether and sidestep all this. But, the titles we do not include may end up giving us ‘improper’ Ratings, since there would be some amazing titles we would be ignoring. Here are some of the Top rated movies with multiple directors —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ozbSZoyhq2l-uoyJ484A_Q.jpeg" /></figure><p>With this logic cleared, let’s proceed towards the query for Director Rating (and we’ll use the same logic for Writers’ Ratings), and the (top) result set —</p><pre>SELECT<br>DENSE_RANK() OVER dir_rank AS Ranking,<br>nb.nconst AS Director_id,<br>nb.primaryName AS Name,<br>round(avg(tr.averageRating), 2) AS Rating,<br>count(tb.tconst) AS Movie_Count<br>FROM imdb.title_basics AS tb<br>JOIN imdb.title_crew_directors AS tcd  ON tb.tconst = tcd.tconst<br>JOIN imdb.title_ratings AS tr ON tb.tconst = tr.tconst <br>JOIN imdb.name_basics AS nb ON tcd.directors = nb.nconst<br>WHERE tb.titleType = &#39;movie&#39;<br>AND tr.numVotes &gt;= 25000<br>GROUP BY nb.nconst, nb.primaryName<br>WINDOW dir_rank AS (ORDER BY avg(tr.averageRating) DESC, count(tb.tconst) DESC);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lzfwa1LREN8e94oJwxqryQ.jpeg" /></figure><p><strong>Movie Count : </strong>Upon analyzing the result set of 2600 directors (and the same would apply for writers), I realized that the final list of top-ranked directors needs to be more carefully curated. To that end, I propose that only those directors who have directed at least 3 movies that have garnered a minimum of 25000 votes should be included in the final list. Although this will exclude some well-regarded names, it’s crucial to consider the body of work of each director and not just individual films. Every movie may be a stand-alone work of art, but when it comes to rating and ranking directors, their entire careers must be taken into account. As a result, the final list will be significantly pared down, but I believe this is necessary for a more wholesome ranking (if this were a professional analysis project, stakeholder approval would be required for such a proposal). We also need to find out Top 5 Directors in each Genre — we’ll apply the same logic there, i.e., at least 3 movies with minimum 25000 votes in each Genre.</p><p>Let’s check out the final queries and results then.</p><p><strong>Ratings and Ranking For Directors &amp; Writers : </strong>We have already discussed the method of computing this, just to summarize :</p><ol><li>We’re only looking at movies with at least 25000 votes</li><li>Directors/Writers in our list need to have minimum 3 such movies in their bags</li><li>The Ratings of the Movies will be credited to their Directors/Writers, the Final Rating would be a mean (average) of all such ratings</li><li>In case of a movie having multiple writers/directors — each of them will be credited the full rating of the movie</li><li>Rank will be based upon writer/director’s Final Rating — highest to lowest, in case of a tie — writer/director with higher movie count (satisfying condition 1 &amp; 2) will be assigned better Rank</li></ol><p>Query for Director’s Rating :</p><pre>SELECT<br>DENSE_RANK() OVER dir_rank AS Ranking,<br>nb.nconst AS Director_id,<br>nb.primaryName AS Name,<br>round(avg(tr.averageRating), 2) AS Rating,<br>count(tb.tconst) AS Movie_Count<br>FROM imdb.title_basics AS tb<br>JOIN imdb.title_crew_directors AS tcd  ON tb.tconst = tcd.tconst<br>JOIN imdb.title_ratings AS tr ON tb.tconst = tr.tconst <br>JOIN imdb.name_basics AS nb ON tcd.directors = nb.nconst<br>WHERE tb.titleType = &#39;movie&#39;<br>AND tr.numVotes &gt;= 25000<br>GROUP BY nb.nconst, nb.primaryName<br>HAVING count(tb.tconst) &gt;= 3<br>WINDOW dir_rank AS (ORDER BY avg(tr.averageRating) DESC, count(tb.tconst) DESC);</pre><p>And a quick look at the top of the results :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QoMlynF_mytnD3dGgougoQ.jpeg" /></figure><p>I’m happy with this list. Similarly, for Writers :</p><pre>SELECT<br>DENSE_RANK() OVER wri_rank AS Ranking,<br>nb.nconst AS Writer_id,<br>nb.primaryName AS Name,<br>round(avg(tr.averageRating), 2) AS Rating,<br>count(tb.tconst) AS Movie_Count<br>FROM imdb.title_basics AS tb<br>JOIN imdb.title_crew_writers AS tcw  ON tb.tconst = tcw.tconst<br>JOIN imdb.title_ratings AS tr ON tb.tconst = tr.tconst <br>JOIN imdb.name_basics AS nb ON tcw.writers = nb.nconst<br>WHERE tb.titleType = &#39;movie&#39;<br>AND tr.numVotes &gt;= 25000<br>GROUP BY nb.nconst, nb.primaryName<br>HAVING count(tb.tconst) &gt;= 3<br>WINDOW wri_rank AS (ORDER BY avg(tr.averageRating) DESC, count(tb.tconst) DESC);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mz3a-cQsh9MV5yOmK28N5Q.jpeg" /></figure><p>The complete list is available at <a href="https://github.com/koustavin/IMDB-SQLAnalysis">GitHub</a>, filename — <a href="https://github.com/koustavin/IMDB-SQLAnalysis/blob/main/Final_Resultset.xlsx">Final_Resultset.xlsx</a>.</p><p><strong>Top 5 Directors/Writers in Each Genre : </strong>We’ll follow the same method as discussed above, just adding Genre into the mix (we’ll use the split table title_basics_genres, which has multiple rows for a multi-genre title). For instance, for a movie belonging to Action and Comedy genres — the writers/directors of the movie will be awarded the movie’s ratings in both the genres. After that, similar to the Ratings approach, we’ll take average of all the director/writer’s final scores in each genre and show the Top 5 among them. Let’s look at the queries and results for Directors and Writers respectively —</p><pre>WITH dir_genre_avgRating AS(<br>SELECT<br>DENSE_RANK() OVER dir_genre_rank AS Genre_Ranking,<br>nb.nconst AS Director_id,<br>nb.primaryName AS Name,<br>tbg.genres AS Genre,<br>round(avg(tr.averageRating), 2) AS Genre_Rating,<br>count(tb.tconst) AS Genre_Movie_Count<br>FROM imdb.title_basics AS tb<br>JOIN imdb.title_crew_directors AS tcd  ON tb.tconst = tcd.tconst<br>JOIN imdb.title_ratings AS tr ON tb.tconst = tr.tconst <br>JOIN imdb.name_basics AS nb ON tcd.directors = nb.nconst<br>JOIN imdb.title_basics_genres AS tbg ON tb.tconst = tbg.tconst<br>WHERE tb.titleType = &#39;movie&#39;<br>AND tr.numVotes &gt;= 25000<br>GROUP BY nb.nconst, nb.primaryName, tbg.genres <br>HAVING count(tb.tconst) &gt;= 3<br>WINDOW dir_genre_rank AS (PARTITION BY tbg.genres<br>                ORDER BY avg(tr.averageRating) DESC, count(tb.tconst) DESC))<br>SELECT *<br>FROM dir_genre_avgRating<br>WHERE Genre_Ranking &lt;= 5<br>ORDER BY Genre, Genre_Ranking;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6UYdeOOxPSjwZyLjjma5fg.jpeg" /></figure><pre>WITH wri_genre_avgRating AS(<br>SELECT<br>DENSE_RANK() OVER wri_genre_rank AS Genre_Ranking,<br>nb.nconst AS Writer_id,<br>nb.primaryName AS Name,<br>tbg.genres AS Genre,<br>round(avg(tr.averageRating), 2) AS Genre_Rating,<br>count(tb.tconst) AS Genre_Movie_Count<br>FROM imdb.title_basics AS tb<br>JOIN imdb.title_crew_writers AS tcw ON tb.tconst = tcw.tconst<br>JOIN imdb.title_ratings AS tr ON tb.tconst = tr.tconst <br>JOIN imdb.name_basics AS nb ON tcw.writers = nb.nconst<br>JOIN imdb.title_basics_genres AS tbg ON tb.tconst = tbg.tconst<br>WHERE tb.titleType = &#39;movie&#39;<br>AND tr.numVotes &gt;= 25000<br>GROUP BY nb.nconst, nb.primaryName, tbg.genres <br>HAVING count(tb.tconst) &gt;= 3<br>WINDOW wri_genre_rank AS (PARTITION BY tbg.genres ORDER BY avg(tr.averageRating) DESC, count(tb.tconst) DESC))<br>SELECT *<br>FROM wri_genre_avgRating<br>WHERE Genre_Ranking &lt;= 5<br>ORDER BY Genre, Genre_Ranking;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pTq3Yna3lVu0RYhA7yPnNg.jpeg" /></figure><p><strong>Top 50 TV Episodes of All Time : </strong>Let’s restate our assumptions for this part that we discussed in the previous section — episodes of tvSeries or tvMiniSeries with type tvEpisode and minimum 5000 votes will be ranked based on diminishing Ratings and votes respectively. Let’s put this in SQL :</p><pre>WITH season_episode_count AS (<br>SELECT te.parentTconst AS ShowId,<br>max(te.seasonNumber) AS TotalSeasons,<br>count(te.episodeNumber) AS TotalEpisodes<br>FROM imdb.title_episode AS te<br>GROUP BY 1),<br>parent_show AS (<br>SELECT tb2.primaryTitle AS ParentShowTitle,<br>tr2.averageRating AS ParentRating,<br>tb2.tconst AS ParentShowId<br>FROM imdb.title_basics AS tb2<br>JOIN imdb.title_ratings AS tr2 ON tb2.tconst = tr2.tconst<br>        AND tb2.titleType IN (&#39;tvSeries&#39;, &#39;tvMiniSeries&#39;))<br>SELECT<br>DENSE_RANK() OVER epi_rank AS `Rank`,<br>tb.primaryTitle AS EpiTitle,<br>replace(tb.startYear, &#39;,&#39;, &#39;&#39;)  AS ReleasedOn,<br>round(tr.averageRating, 2) AS EpiRating,<br>tr.numVotes AS EpiVotes,<br>ParentShowTitle AS ShowTitle,<br>concat(&#39;S&#39;, lpad(te2.seasonNumber, 2, &#39;0&#39;), &#39;.E&#39;, lpad(te2.episodeNumber, 2, &#39;0&#39;)) AS EpiSerial,<br>TotalSeasons AS TotalSeasons,<br>TotalEpisodes AS TotalEpisodes,<br>round(ParentRating, 2) AS ShowRating<br>FROM imdb.title_basics AS tb<br>JOIN imdb.title_ratings AS tr ON tb.tconst = tr.tconst<br>        AND tb.titleType = &#39;tvEpisode&#39;<br>        AND tr.numVotes &gt;= 5000<br>JOIN imdb.title_episode as te2 ON te2.tconst = tb.tconst<br>JOIN parent_show ON te2.parentTconst = parent_show.ParentShowId<br>JOIN season_episode_count ON parent_show.ParentShowId = season_episode_count.ShowId<br>WINDOW epi_rank AS (ORDER BY tr.averageRating DESC, tr.numVotes DESC)<br>LIMIT 50;</pre><p>I’m using two CTEs — season_episode_count to get the total number of seasons and episodes belonging to each series, and parent_show to fetch Rating of the overall series. The main query actually looks at individual episodes and their ranking, it connects with the CTEs via each episode’s parent show id (in title_episode table). The EpSerial column indicates the specific season and episode number of the parent show that the current episode belongs to. This is how the result looks like —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ofZWRiWWVBFfb3mpxfuPKQ.jpeg" /></figure><p><strong>Compare 5 Highest Rated and 5 Most Voted Movies From Last 5 Years :</strong> Moving on to the next task, I decided to club the comparison into one column, i.e., entry in that column itself should tell us whether that movie is Top Rated, or Most Voted, or both. Other assumptions are —</p><ol><li>I have considered 2018 to 2022 as ‘last 5 years’, since I have only 2 months’ worth data for 2023.</li><li>Titles considered here have type movie and at least 25000 votes.</li></ol><p>Let’s take a look at the query :</p><pre>WITH movie_ranking AS(<br>SELECT<br>DENSE_RANK() OVER (PARTITION BY tb.startYear ORDER BY tr.averageRating DESC)<br>    AS HighestRatedRanking,<br>DENSE_RANK() OVER (PARTITION BY tb.startYear ORDER BY tr.numVotes DESC)<br>    AS MostVotedRanking,<br>replace(tb.startYear, &#39;,&#39;, &#39;&#39;) AS ReleasedOn,<br>tb.primaryTitle AS Title,<br>tr.averageRating AS Rating,<br>tr.numVotes AS NumberOfVotes<br>FROM imdb.title_basics AS tb<br>JOIN imdb.title_ratings AS tr ON tb.tconst = tr.tconst<br>AND tb.startYear BETWEEN 2018 AND 2022<br>AND tb.titleType = &#39;movie&#39;<br>AND tr.numVotes &gt;= 25000)<br>SELECT<br>CASE WHEN (HighestRatedRanking &lt;= 5 AND MostVotedRanking &gt; 5)<br>     THEN concat(&#39;Highest Rated : &#39;, HighestRatedRanking, &#39; of &#39;, ReleasedOn)<br>   WHEN (HighestRatedRanking &gt; 5 AND MostVotedRanking &lt;= 5)<br>     THEN concat(&#39;Most Voted : &#39;, MostVotedRanking, &#39; of &#39;, ReleasedOn)<br>   WHEN (HighestRatedRanking &lt;= 5 AND MostVotedRanking &lt;= 5)<br>     THEN concat(&#39;Highest Rated : &#39;, HighestRatedRanking, &#39; &amp; Most Voted : &#39;, MostVotedRanking, &#39; of &#39;, ReleasedOn)<br>END AS WhyOnTop,<br>ReleasedOn AS `Year`,<br>Title,<br>round(Rating, 2) AS Rating,<br>NumberOfVotes<br>FROM movie_ranking<br>WHERE HighestRatedRanking &lt;= 5<br>OR MostVotedRanking &lt;= 5<br>ORDER BY ReleasedOn, WhyOnTop;</pre><p>Most of the filtering (assumptions mentioned above) and ranking is being done inside the CTE movie_ranking. The final query just chooses the 5 top ranking titles. ‘WhyOnTop’ is the column that shows the comparison — I have used Case statement based on the rank values to determine the reason for the that particular title to be on the list. Here is (part of) the result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xwX_KPT7zjEbpAt4ujwshA.jpeg" /></figure><p>One important general disclaimer here, in most of these queries I have used DENSE_RANK — since I didn’t mind getting some extra names on the list as long as they fit the bill, and also the ask wasn’t specific about how many movies should be in the result. When I think ‘Top 5’, I want to know that each rank has at least one name — DENSE_RANK helps with that. If we had more strict requirements (like ‘5 Top Movies’ instead of ‘Top 5 Movies’) I would probably have used RANK and/or LIMIT, depending upon the case.</p><p><strong>Top 5 Movies from Each Decade :</strong> I approached this problem as a binning problem — we need to bin the titles as per the decade of their release, and then find the top titles in each bin. Some assumptions I had made —</p><ol><li>I have considered 1980-1989 as 80’s, 1990-1999 as 90’s and so on. There are other approaches, hence just wanted to clarify beforehand.</li><li>Titles considered here have type movie and at least 25000 votes.</li></ol><p>Let’s look at the query first :</p><pre>WITH movie_decade AS(<br>SELECT<br>CASE WHEN tb.startYear BETWEEN 1980 AND 1989 THEN &#39;1980&#39;&#39;s&#39;<br>   WHEN tb.startYear BETWEEN 1990 AND 1999 THEN &#39;1990&#39;&#39;s&#39;<br>   WHEN tb.startYear BETWEEN 2000 AND 2009 THEN &#39;2000&#39;&#39;s&#39;<br>   WHEN tb.startYear BETWEEN 2010 AND 2019 THEN &#39;2010&#39;&#39;s&#39;<br>   WHEN tb.startYear BETWEEN 2020 AND 2023 THEN &#39;2020&#39;&#39;s&#39;<br>END AS Decade,<br>DENSE_RANK() OVER (PARTITION BY (<br>  CASE<br>   WHEN tb.startYear BETWEEN 1980 AND 1989 THEN &#39;1980&#39;&#39;s&#39;<br>   WHEN tb.startYear BETWEEN 1990 AND 1999 THEN &#39;1990&#39;&#39;s&#39;<br>   WHEN tb.startYear BETWEEN 2000 AND 2009 THEN &#39;2000&#39;&#39;s&#39;<br>   WHEN tb.startYear BETWEEN 2010 AND 2019 THEN &#39;2010&#39;&#39;s&#39;<br>   WHEN tb.startYear BETWEEN 2020 AND 2023 THEN &#39;2020&#39;&#39;s&#39;<br>  END)<br> ORDER BY averageRating DESC) AS `Rank`,<br>count(primaryTitle) OVER (PARTITION BY (<br>  CASE<br>   WHEN tb.startYear BETWEEN 1980 AND 1989 THEN &#39;1980&#39;&#39;s&#39;<br>   WHEN tb.startYear BETWEEN 1990 AND 1999 THEN &#39;1990&#39;&#39;s&#39;<br>   WHEN tb.startYear BETWEEN 2000 AND 2009 THEN &#39;2000&#39;&#39;s&#39;<br>   WHEN tb.startYear BETWEEN 2010 AND 2019 THEN &#39;2010&#39;&#39;s&#39;<br>   WHEN tb.startYear BETWEEN 2020 AND 2023 THEN &#39;2020&#39;&#39;s&#39;<br>  END)) AS TotElgblMoviesOfDecade,<br>tb.primaryTitle,<br>tb.startYear,<br>tb.genres,<br>tr.averageRating,<br>tr.numVotes <br>FROM imdb.title_basics AS tb<br>JOIN imdb.title_ratings AS tr<br>ON tb.tconst = tr.tconst<br>AND tb.startYear &gt;= 1980<br>AND tb.titleType = &#39;movie&#39;<br>AND tr.numVotes &gt;= 25000)<br>SELECT<br>Decade,<br>`Rank`,<br>primaryTitle AS Title,<br>replace(startYear, &#39;,&#39;, &#39;&#39;) AS `Year`,<br>round(averageRating, 2) AS Rating,<br>numVotes AS NumberOfVotes,<br>genres AS Genre,<br>TotElgblMoviesOfDecade<br>FROM movie_decade<br>WHERE `Rank` &lt;= 5;</pre><p>The core element of this query is the binning which I implemented with a case statement. the ‘Decade’ bin has been used thrice — first for the decade (SELECT column) itself, second for the ranking over each decade, and third to count the total eligible (as per our assumptions) movies in that decade. The results :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*leuyoi_5DbdWwKWdTDmiiA.jpeg" /></figure><p>Looking at the result set briefly, we can see that total eligible movies have increased decade over decade, except for 2020’s — of course, it’s not even half over yet. But we do have to take into account that the pandemic hit this decade’s movie business pretty hard. So far, almost all the Top movies in this decade are from India though — YAY to that.</p><p><strong>Parting Thoughts :</strong> And on that high note, we draw the curtains over this ‘little’ project of mine. What I have realized is that these days I mostly watch ‘Most Voted’ titles, but miss out on ‘Top Rated’ titles with less public discourse — I need to correct that. Anyway, as mentioned earlier, all the files are available at <a href="https://github.com/koustavin/IMDB-SQLAnalysis">GitHub</a>, and the results are in — <a href="https://github.com/koustavin/IMDB-SQLAnalysis/blob/main/Final_Resultset.xlsx">Final_Resultset.xlsx</a>. Hope you had fun, see you soon.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1805931b4b6d" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/imdb-sql-data-analysis-part-iii-customized-ranking-for-movies-and-filmmakers-1805931b4b6d">IMDB SQL Data Analysis : Part III — Customized Ranking for Movies and Filmmakers</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IMDB SQL Data Analysis : Part II — The Objectives & Assumptions, and Data Exploration]]></title>
            <link>https://medium.com/@koustavin/imdb-sql-data-analysis-part-ii-the-objectives-assumptions-and-data-exploration-b8fae4329f93?source=rss-de554458f133------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8fae4329f93</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[imdb]]></category>
            <category><![CDATA[data-exploration]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[Koustav]]></dc:creator>
            <pubDate>Sun, 09 Apr 2023 13:45:58 GMT</pubDate>
            <atom:updated>2024-07-31T20:10:56.642Z</atom:updated>
            <content:encoded><![CDATA[<h3>IMDB SQL Data Analysis : Part II — The Objectives &amp; Assumptions, and Data Exploration</h3><p>Movies and TV Series have always been my favorite pastime. My first Data analysis project for GDAC was based on the Movie Industry dataset in Kaggle — <a href="https://www.kaggle.com/code/koustavin/how-to-invest-in-popular-profitable-movies">How To Invest in Popular/Profitable Movies</a>. There I had tried to ‘decode’ the formula for profitable movies using Excel and R — from movie runtime, popular writers/directors to ideal time of the year to release a movie — what made the movies more popular/profitable. My first SQL project is sort of an homage to that — IMDB has ratings for Movies, is it possible to derive ratings for directors/writers in a similar way?</p><p><strong>Project Objectives :</strong> What I wanted out of this project (spoiler alert, didn’t quite get everything done — more on that later) :</p><ol><li>Determine Ratings for Movie Directors and Writers. Also, find out Top 5 Directors and Writers in each Genre</li><li>Top 50 Episodes of TV Series (based on Ratings)</li><li>Top 5 Highest Rated Movies from last 5 Years, and compare them with Most Rated (based on Number of Votes) Movies</li><li>Top 5 Movies from each Decade, starting with the Eighties</li><li><em>IMDB Top 250 of Indian Contents</em></li></ol><p>I could not achieve the 5th goal, since I couldn’t find any information in the dataset that would reliably allow me to separate Indian content from the rest. I will come back to this later in the article.</p><p><strong>Why IMDB Dataset :</strong> The reason I chose <a href="https://www.imdb.com/interfaces/">IMDB</a> is simple — it is the most widely relied upon and openly available Movies dataset. It would have been more insightful had it also included financial information and origin country/region of production information. Saw somewhere that these information are available through IMDB Pro, but didn’t get any reliable confirmation whether IMDB Pro provides this information through their API (as dataset). Their <a href="https://aws.amazon.com/marketplace/seller-profile?id=0af153a3-339f-48c2-8b42-3b9fa26d3367">AWS offerings</a> promise this data, but are very costly after the trial. I have restricted myself to the free dataset available.</p><p><strong>Setting Up The Database —</strong> I had initially planned to just load the data on the tables and get querying. As you can probably tell from the tone, things didn’t go as planned. I ended up spending days on setting up the database, but it was quite a rewarding journey. Since that part became quite valuable in terms of effort spent and learning — I decided to move it in a separate article. If you like to get your hands dirty with technical nitty-gritty (SQL only, I promise), I will heavily encourage you to visit that article here —</p><p><a href="https://medium.com/@koustavin/imdb-sql-data-analysis-database-design-492751ab16c4">IMDB SQL Data Analysis : PART I — Building and Designing The Database on MySQL</a></p><p>The current article mainly covers the Exploration of the dataset and IMDB website, to help set up ground work for the main Analysis to come (in the next part) :</p><p><a href="https://blog.devops.dev/imdb-sql-data-analysis-part-iii-customized-ranking-for-movies-and-filmmakers-1805931b4b6d">IMDB SQL Data Analysis : Part III — Customized Ranking for Movies and Filmmakers</a></p><p><strong>Making Sense of The Data —</strong></p><p>The Database Setup part ran way too long, much longer than what I intended. But anyways, since now that we have the data in intended format with reasonable query speed (for a Database running on a laptop) — we can finally proceed with the actual analysis.</p><p><strong>Exploration of IMDB Ranking : </strong>I will first try to assess how IMDB does its Top Ranking — is it just through the value of the Rating, or are there other criteria involved? Let’s take a look at the list of <a href="https://www.imdb.com/chart/top">IMDB Top 250 Movies</a>, and let’s see if we can recreate that in SQL.</p><blockquote>During my college days, one of my close friends introduced me to this list. And our mission (we did choose to accept it) was to watch all the movies on it. Although I can’t recall whether we managed to watch all of them, we did view a significant number and it was a memorable experience. In recent years, I have re-watched a few of those films and realized that my perspective on them has evolved with time — as is often the case. Nonetheless, let’s refocus on the current topic.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c9bpdzcJSOVmFC1_5PLhMw.jpeg" /></figure><p>The criteria used here is probably not going to be the just the rating number itself, but assuming it is — let’s see what the SQL query below returns.</p><pre>SELECT tb.primaryTitle, tr.averageRating, tr.numVotes <br>FROM imdb.title_basics AS tb<br>JOIN imdb.title_ratings AS tr  USING (tconst)<br>WHERE tb.titleType = &#39;movie&#39;<br>ORDER BY tr.averageRating DESC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*hD7pv0lI8ySvyb0TOtJRdQ.jpeg" /></figure><p>The results of the SQL we used does not match at all with what IMDB has. And sure enough, titles having perfect score of 10 based on just 8 votes seem heavily biased — not to undermine anyone’s efforts, but it could just be the friends and family of the crew voting here. To ensure that the Top chart includes widely accepted movies, high number of votes is a necessity — but how high should we set the bar? Or better yet, how high does IMDB set the bar? Hovering mouse pointer over a rating on the website, or inspecting it in console reveals the vote count behind that rating. In top 10 titles — vote count varies from around 7,71,000 to 2.7 million. The HTML code of the page doesn’t reveal any criteria either — as expected. Let’s look at one of the Genres (Action) listed in the right hand side panel under the title — ‘Top Rated Movies by Genre’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FmfzK5VQ9BtSuhujVn0yFg.jpeg" /></figure><p>Ahh ha, now we are getting somewhere. At least some of the criteria can be found in the address bar and page title — genres = action, title_type = feature, num_votes ≥ 25000, sorted by descending user_rating. But wait, what’s title type feature?</p><pre>SELECT DISTINCT tb.titleType  <br>FROM imdb.title_basics AS tb;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/163/1*c1pv8NEWws0gDYoEBjdoKQ.jpeg" /></figure><p>We don’t have a title type in our dataset called ‘feature’. As we do know these titles to be movies, we are going to assume that they mean the same thing in this context. OK, let’s convert these conditions into SQL and see what result we get from the dataset. We’ll compare Top movies in Action genre between IMDB web and dataset. These are the movies in IMDB webpage —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*4fZ4Dv4TVYZDQnUYN-0Mog.jpeg" /></figure><p>The criteria we dug out from the web page converted to SQL, with some extra flourish to match the Ranking Table above (we don’t have Gross income in our dataset), looks like this —</p><pre>SELECT ROW_NUMBER() OVER rating_window AS Ranking,<br>tb.originalTitle AS Title,<br>tb.startYear AS Release_Year,<br>tr.averageRating AS Rating,<br>tr.numVotes AS NumVotes<br>FROM imdb.title_basics AS tb<br>JOIN imdb.title_ratings AS tr USING (tconst)<br>JOIN imdb.title_basics_genres AS tbg USING (tconst)<br>WHERE tb.titleType = &#39;movie&#39;<br>AND tbg.genres = &#39;Action&#39;<br>AND tr.numVotes &gt;= 25000<br>WINDOW rating_window AS (ORDER BY tr.averageRating DESC);</pre><p>And the output of that (showing the Top 35 results), with VLOOKUP of the Web Ranking (of Top 25 titles) —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l5nu0oQDmJRTK2mQl0u7gw.jpeg" /></figure><p>This matches somewhat, but not completely — looks like the filter criteria are spot on, but ordering is different. We are sorting by Rating, and that works as expected. But among the movies having the same rating, looks like IMDB applies some custom sorting of its own. This model is not made explicit — I suspect, it might be some combination of Number of Votes, Release Year (<em>how recent the movie is — John Wick 4 has just released, and it is on Top among the movies with 8.5 rating with low vote count; we don’t have this movie in our month-old dataset at all</em>) and/or Gross income. Unless folks at IMDB themselves decide to chime in, it’s unlikely that we can figure out the exact logic of their sorting. Also, I can see that there is a different criteria for the Top 250 Movies page and Genre specific Top Movies page — while the Genre specific page has a minimum vote count of 25000, the Top 250 page doesn’t have any movie having below 80000 votes and I can see movies with high rating but votes between 25000 and 80000 being excluded. For sake of simplicity, <strong>for Movies we’ll use the minimum 25000 votes criteria and sort by Rating and Number of Votes respectively and in Descending order.</strong></p><p>Now that we have the Ranking system somewhat figured out, let’s try to see how we can identify Indian movies from the Dataset — which we’ll need for our 5th objective.</p><p><strong>Exploration of Indian Movies :</strong> As I had mentioned earlier, I ultimately could not complete the 5th objective (on Indian Movies and TV Series). I could not find a consistent feature in the dataset that could undoubtedly point toward a title being produced in India. First of all, let me explain why I initially assumed that I would be able to find that information from the dataset. IMDB <a href="https://www.imdb.com/interfaces/">Documentation</a> for the Dataset contains this about title_akas table (or the flat file title.akas.tsv.gz) —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*v8UVPYg_ayfrjoqN9CPApw.jpeg" /></figure><p>If we look at the data in this table, there is record for almost every (please don’t take my word on the completeness of the data — I have no way to verify this, although I feel like I have seen quite a few obscure titles’ even more obscure edition here, be it a dubbing in a different language or 3D re-release) version of a title. I had assumed that the region and or language of the original title (isOriginalTitle = 1) would point me towards the actual country or language of that title. I have checked multiple other titles, but for now let’s take a look at the records for RRR (to celebrate its victory at the global stage) in this table —</p><pre>WITH movie AS (<br>SELECT tb.tconst AS TitleId<br>FROM imdb.title_basics AS tb<br>WHERE tb.primaryTitle = &#39;RRR&#39;<br>AND tb.titleType = &#39;movie&#39;)<br>SELECT ta.*<br>FROM imdb.title_akas AS ta<br>JOIN movie ON movie.TitleId = ta.titleId;</pre><p>RRR has overall 43 records in this table, let’s look at some of them —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e-f541YZybsGovRuvM6cfg.jpeg" /></figure><p>RRR is not a so-called Bollywood movie — the original production was in Telugu, and then it was dubbed in many other languages. However, the Telugu version is not explicitly mentioned in this list. If we filter this result set further for region (IN, for India presumably, or NULL), this is what it looks like —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P1_sZ0l9SiMJ6YY73M1LVw.jpeg" /></figure><p>We can assume that one of these NULL records is actually for the Telugu version, presumably the ‘original’ record — but it contains no region or language information for us to be able to confirm that. I don’t know if this information is missing by mistake or willfully withheld (to push users towards IMDB Pro, or their AWS offering — which to be honest, is completely fair on their part). I checked briefly, and only 22 ‘original’ records in title_akas table contain region and/or language information — out of 9.6 million titles in total. To confirm, the other possible table, title_basics, does not contain any region, country or language specific information (I had some hope for originalTitle column, but didn’t find anything useful there).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*TGkJObUHJQA2ZOVm8JR_fw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FuwzDllCxl2IzVFerOLl6Q.jpeg" /></figure><p>So, to summarize — we have no way of separating ‘Indian’ Movies or TV Series from the rest in a comprehensive and reproducible manner. And hence we need to drop Objective 5 from our list — we can probably accomplish it with some other dataset, but not with this one.</p><p><strong>TV Series Exploration : </strong>Similar to the Top Movies page, IMDB has an excellent <a href="https://www.imdb.com/chart/toptv/?ref_=nv_tvv_250">Top 250 TV</a> page. Exploring it like we did for the movies, and considering that we’ll be looking at individual episodes, this is the criteria I decided upon — episodes with minimum 5000 votes will be ranked, episodes will have titletype tvEpisode, parent shows will have titletype either tvSeries or tvMiniSeries, and we’ll sort by highest to lowest Rating and vote count in that order.</p><p>Now that we are done exploring the thorny side of the data, We need to get back to our main objectives. And we will, but in the next part — since this one has gotten quite huge, and we still have a lot more to cover in terms of intricacies of the data and quite a few nifty SQL tricks. See you soon.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8fae4329f93" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IMDB SQL Data Analysis : PART I — Building and Designing The Database on MySQL]]></title>
            <link>https://medium.com/@koustavin/imdb-sql-data-analysis-database-design-492751ab16c4?source=rss-de554458f133------2</link>
            <guid isPermaLink="false">https://medium.com/p/492751ab16c4</guid>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[imdb]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[imdb-dataset]]></category>
            <dc:creator><![CDATA[Koustav]]></dc:creator>
            <pubDate>Fri, 07 Apr 2023 21:20:15 GMT</pubDate>
            <atom:updated>2023-04-09T15:26:44.388Z</atom:updated>
            <content:encoded><![CDATA[<h3>IMDB SQL Data Analysis : PART I — Building and Designing The Database on MySQL</h3><p>This is about my journey into the world of Relational Database Design. I was going to use IMDB Dataset for one of my SQL projects, and didn’t want to turn this into a whole ETL (Explore, Transform, and Load) workflow. I just wanted to get the dataset in tables so that I could run some quick SQL queries and get my answers. But things didn’t go as planned, and unwillingly I had to delve into building a full-fledged relational database, along with some Data Cleaning and Feature Engineering. Before this, I was proud of my 11+ years of experience in SQL — some of which also involved creating an Index or Foreign Key here, looking into PL/SQL Procedures &amp; Functions and running them there. But in the process of setting up this database, I learned quite a few new things myself.</p><p>This is part of my IMDB Data Analysis Project using SQL, this article covers the Database part. Next part is about Data Exploration, solidifying assumptions etc., it’s now available at the link below. The 3rd and final part which covers the actual analysis will be up very soon.</p><p><a href="https://medium.com/@koustavin/imdb-sql-data-analysis-part-ii-the-objectives-assumptions-and-data-exploration-b8fae4329f93">IMDB SQL Data Analysis : Part II — The Objectives &amp; Assumptions, and Data Exploration</a></p><p>At first, this Database Setup part was supposed to be a small footnote in my main Data Analysis article, since this was not supposed to be about Database Design at all. However, several developments had taken place since then, compelling me to alter my strategy. In addition, I was keen on thoroughly recording my learning journey — so, here we go.</p><p><strong>Initial Plan :</strong> I didn’t want to spend a lot of time on this task, since I had already wasted weeks procrastinating on what SQL project I should do, what dataset should I use etc. So before starting with the project, I set some boundaries for myself -</p><ol><li>I will limit my analysis to IMDB Dataset (the free version, there are some paid alternatives) itself. I am allowed to verify information from other sources to confirm my understanding, but the data itself (in the database) will just be from the dataset.</li><li>I won’t spend efforts in building a pipeline or designing an ETL process — since this is going to be a one time task. I just want to showcase my SQL Querying skills — and that’s what I will limit my efforts to.</li><li><em>Sort of an extension of the previous guideline, I won’t spend much time designing the database — no Primary Key, Foreign Key etc., and no ER Diagram. Just load the files in separate tables and proceed to querying.</em></li><li>I will limit myself to SQL as much as possible, so no other programming language or visualization tool shall be used.</li></ol><p><strong>Setting Up The Database —</strong></p><p><strong>Loading The Files :</strong> The data was sourced from <a href="https://www.imdb.com/interfaces/">IMDB</a>. I already had a MySQL instance installed on my laptop as part of a SQL course that I had attended. I created a new schema (imdb) on that DB and decided to load the data there. I vaguely recalled using something called ‘loader’ for loading multiple flat files into oracle database from years back. I wanted to find something similar for MySQL — I found MySQL Shell command importTable. After testing it out a bit, when I felt comfortable using it — I started this load cycle for each table :</p><p>(a) Create table, where the file would be loaded, in MySQL Workbench (that’s what I was using at the beginning, switched to DBeaver midway through the project — mainly because I had started hating the UI of the former).</p><pre>CREATE TABLE title_crew(<br>tconst VARCHAR(15),<br>directors VARCHAR(150),<br>writers VARCHAR(150));</pre><p>(b) Run importTable utility on MySQL Shell after connecting to the database. The utility can handle both tsv (tab separated value) file and tsv.gz (gzipped tsv file, this is the format IMDB dataset files came in) — in fact it can handle many other types as well. Although I didn’t use it, importTable supports parallel loading as well — I was worried whether I will be able to catch errors properly with parallel loading, plus I was worried that it might strain my 2 year old laptop.</p><pre>\use imdb<br>util.importTable(&quot;/Downloads/imdb20230223/title.ratings.tsv.gz&quot;, {&quot;table&quot; : &quot;title_ratings&quot;, skipRows: 1, showProgress: true});<br>util.importTable(&quot;/Downloads/imdb20230223/title.crew.tsv/data.tsv&quot;, {&quot;table&quot; : &quot;title_crew&quot;, skipRows: 1, showProgress: true})</pre><p>( c) Check the output for errors/warnings. Sometimes the column size might be too small for particular records — in that case, importTable generates a warning, inserts truncated data (as per the size allowed) in said column, and then proceeds with the rest. In this case, I would then drop the existing table (with records that did get inserted) and redefine it with larger column size. This process could be simpler if maximum allowed size is used for every column — but that’s just bad and irresponsible design. After table has been recreated, repeat steps b and c.</p><pre>DROP TABLE title_crew;</pre><pre>CREATE TABLE title_crew(<br>tconst VARCHAR(15),<br>directors VARCHAR(6000),<br>writers VARCHAR(10000));</pre><p>After the loading process was done, this is how the tables and columns looked —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*iNjWjOubO7kp82cU5HGMZA.jpeg" /></figure><p><strong>Setting Up The Constraints :</strong> I didn’t want any Primary, Foreign keys and wanted to query the data directly. But even a simple query with very simple WHERE conditions was taking very long time to run with this setup — simply because of the size of the overall database. Hence, I had to give up on the 3rd guideline I had set for myself — I had to create Primary Keys, Foreign Keys and Index where needed.</p><p>Exploring the data for that purpose, I found 2 issues —</p><p>(i) In some cases, for the tables I wanted to connect through Foreign Key — the primary table would be missing data that would be referenced by the secondary table. So, in order to be able to create a relationship, I would have to delete those records that are missing in the primary table. If there were very few records missing like this, it may have been possible (albeit very painfully) to manually find out details of the missing data and try to create those missing records on the primary table — but number of missing records removed that possibility altogether. I hadn’t expected this kind of issue from IMDB dataset, but well… This is one of the queries that were used to identify records missing in the primary table (for this query, title_basics is the primary table, and title_ratings is the secondary table — on which we are trying to create the Foreign Key) —</p><pre>SELECT tr.tconst<br>FROM imdb.title_ratings tr<br>LEFT JOIN imdb.title_basics tb<br>ON tr.tconst = tb.tconst<br>WHERE tb.tconst is NULL;</pre><p>(ii) Some of the table columns contained comma separated values, which were separately present in other tables. So, if we needed to join those two tables, Foreign Key was out of question. We could still join those two tables (in a query) by treating the comma separated value as a string and then use string operations (LIKE, substr_index etc.) to join those two tables — but then again a string operation like that on a database this size would be very costly. Better option was to split those comma separated values in different records — we’ll come back to this later.</p><p>I decided to address issue (i) first, so that I can go ahead with creating Primary Key and Foreign Keys first — that will make querying the data faster. I went on to delete missing data from secondary tables — title_episode, title_ratings, title_principals, title_akas. Then created Primary and Foreign Keys. The Foreign Keys were sometimes taking too long to create — since it being a reference between two columns, both of the columns (in both the tables) needed to be indexed. By this time, I had not created any index explicitly — just the ones that were getting created implicitly while creating Primary Keys. So, if the column from the secondary table (where Foreign Key is being created, since by definition the column it is referring should already be Primary Key of the primary table) is not the (single column) Primary Key of the secondary table — MySQL will need to create an index first and then create the Foreign Key reference. For example, title_principals table had a primary key consisting of three columns — tconst, nconst, ordering. I wanted nconst (which is the alphanumeric id of actors/directors etc.) of title_principals table(secondary table in this case) refer to nconst of name_basics table (containing details of all actors, crew members etc., primary table in this case, and nconst was its Primary Key). Since, nconst was not the sole Primary Key of title_principals table, which is also the largest table in the DB based on size — it took 10 hours and 24 mins for the command to run. I realized it too late, but for the remaining tables after that, I created an Index explicitly before creating the Foreign Key. Sample code —</p><pre>ALTER TABLE imdb.title_akas ADD PRIMARY KEY(titleId, ordering);<br><br>ALTER TABLE title_akas  ADD FOREIGN KEY (titleId) REFERENCES title_basics(tconst);<br><br>CREATE INDEX te_parent<br>ON title_episode (parentTconst);</pre><p>At this point, Entity Relationship Diagram (yes, I went there) for the Database looked like this —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hto8KR1HdTmW0rX_uxNaGw.jpeg" /></figure><p><strong>Splitting The Columns Containing Comma Separated Values :</strong> I still needed to deal with issue (ii) mentioned above — the columns with comma separated values. This part has been the biggest learning for me from this project. I knew that had I loaded the files using Python and followed an ETL process, I could have dealt with this in the code itself before inserting it into the DB. But I didn’t want to use Python, and at that time I didn’t think that the comma separated values in their current form would be a problem. I still wanted to solve this through SQL. After searching for some time, I stumbled upon this wonderful solution on S<a href="https://stackoverflow.com/a/17942691">tackOverflow</a>. I tested it out on my database, and it seemed to work fine. I had multiple columns like this, sometimes on the same table. So, I had to do multiple iterations of this process — I will take an example of title_crew table and try to explain the steps. title_crew table contained lists of directors and writers (both in comma separated format in case of multiple directors or writers) in respective columns against each tconst (basically titleid, Primary Key of this table) value. We had to separate the tconst-directors and tconst-writers relationship — because if we had 3 directors and 5 writers associated with a single title, we can’t show that together when the values are split. I proceeded with these steps —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*tEekX6yiKeBKJTIdzi4TuQ.jpeg" /></figure><p>(I) First of all, I needed to know how many comma separated values at maximum are we looking at — since that will be required in following steps. I used this query to get the length of the whole string, minus the length of the string without the commas from it — to get the number of commas. The value-count would be one more than the comma-count — we got the maximum values from this. Now, don’t call me a coward, but I did spot check the count outside SQL to confirm that the query is behaving as intended. Query used —</p><pre>SELECT tc.directors, (CHAR_LENGTH(tc.directors) - CHAR_LENGTH(REPLACE(tc.directors, &#39;,&#39;, &#39;&#39;))) AS comma_count<br>FROM imdb.title_crew AS tc <br>ORDER BY (CHAR_LENGTH(tc.directors) - CHAR_LENGTH(REPLACE(tc.directors, &#39;,&#39;, &#39;&#39;))) DESC<br>LIMIT 10; -- maximum 491 comma separated values (for 490 commas) for directors in a single row</pre><pre>SELECT tc.writers, (CHAR_LENGTH(tc.writers) - CHAR_LENGTH(REPLACE(tc.writers, &#39;,&#39;, &#39;&#39;))) AS comma_count<br>FROM imdb.title_crew tc<br>ORDER BY (CHAR_LENGTH(tc.writers) - CHAR_LENGTH(REPLACE(tc.writers, &#39;,&#39;, &#39;&#39;))) DESC<br>LIMIT 10; -- maximum 991 comma separated values for writers in a single row</pre><p>(II) Now that we know the highest number of comma separated values (say n) in each column — we need one number (from 1 to n) each to extract every value, from every record. So, we need a table containing each of those numbers (1 to n) in each row. I decided to go for a separate table for each column that required splitting (and not reuse same number table). You can ignore the SELECT part of the INSERT (into these number tables) — ROW_NUMBER was taken from a random table to fetch 1 to n numbers.</p><pre>CREATE TABLE imdb.num_tc_dir(<br>n INT); -- numbers table for title_crew.directors<br><br>CREATE TABLE imdb.num_tc_wri(<br>n INT); -- numbers table for title_crew.writers<br><br>INSERT INTO imdb.num_tc_dir<br>SELECT ROW_NUMBER() OVER()<br>FROM imdb.name_basics<br>LIMIT 491;<br><br>INSERT INTO imdb.num_tc_wri<br>SELECT ROW_NUMBER() OVER()<br>FROM imdb.name_basics<br>LIMIT 991;</pre><p>(III) As I had stated earlier, I would need two separate tables to hold the split data — one for writers, and one for directors. These tables would connect to the original data via tconst (title id) from the original record.</p><pre>CREATE TABLE imdb.title_crew_directors(<br>tconst VARCHAR(15),<br>directors VARCHAR(15));<br><br>CREATE TABLE imdb.title_crew_writers(<br>tconst VARCHAR(15),<br>writers VARCHAR(15));</pre><p>(IV) Finally we are ready to split the data. Let me show the query first, and then I will try to explain —</p><pre>INSERT INTO imdb.title_crew_directors(tconst, directors)<br> SELECT<br>  tc.tconst,<br>  SUBSTRING_INDEX(SUBSTRING_INDEX(tc.directors, &#39;,&#39;, numbers.n), &#39;,&#39;, -1) AS directors<br>FROM<br>  imdb.num_tc_dir  AS numbers INNER JOIN imdb.title_crew AS tc<br>  ON (CHAR_LENGTH(tc.directors) - CHAR_LENGTH(REPLACE(tc.directors, &#39;,&#39;, &#39;&#39;))) &gt;= (numbers.n - 1);<br> <br> INSERT INTO imdb.title_crew_writers(tconst, writers)<br> SELECT<br>  tc.tconst,<br>  SUBSTRING_INDEX(SUBSTRING_INDEX(tc.writers, &#39;,&#39;, numbers.n), &#39;,&#39;, -1) AS writers<br>FROM<br>  imdb.num_tc_wri  AS numbers INNER JOIN imdb.title_crew AS tc<br>  ON (CHAR_LENGTH(tc.writers) - CHAR_LENGTH(REPLACE(tc.writers, &#39;,&#39;, &#39;&#39;))) &gt;= (numbers.n - 1);</pre><p>Consider a string like ‘A,B,C’ — it contains 3 values separated by 2 commas. The JOIN ON clause matches strings where comma-count is greater than or equals to number (from number table) minus 1, so this particular string (with 2 commas) will match with numbers 1, 2 and 3. Now let’s consider the SELECT term with <a href="https://www.w3schools.com/sql/func_mysql_substring_index.asp">SUBSTRING_INDEX</a> (<em>the SUBSTRING_INDEX() function returns a substring of a string before a specified number of delimiter occurs</em>). The inner SUBSTRING_INDEX returns — ‘A,B,C’ when matched with the number 3 (substring before 3 commas appear — which is never), ‘A,B’ when matched with 2 (substring before the 2nd comma appears), and ‘A’ when matched with 1. The outer part (with -1 as the number) returns the last part after the last occurrence of comma. So, the final output would be — ‘C’ when matched with the number 3, ‘B’ when matched with 2, and ‘A’ when matched with 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*ZalkfhwUHC1Ox2cxlALzvg.jpeg" /></figure><p>This process split the comma separated values in individual rows and that is how the data was inserted into the new tables. Total 5 new tables were now holding the split data — name_basics_knownForTitles for name_basics.knownForTitles, name_basics_primaryProfession for name_basics.primaryProfession, title_crew_directors for title_crew.directors, title_crew_writers for title_crew.writers, title_basics_genres for title_basics.genres.</p><p><strong>Others :</strong> I had also created relevant indexes and Foreign Keys initially and during the Analysis as needed. For instance, this simple GROUP BY query was taking around 3 minutes to run —</p><pre>SELECT te.parentTconst, max(te.seasonNumber) AS NumberOfSeasons, count(te.episodeNumber) AS NumberOfEpisodes<br>FROM imdb.title_episode AS te<br>GROUP BY 1</pre><p>After I created separate indexes for each column, the time reduced to 1 min 25 secs — but that was still a lot. Finally, this index helped bring down the time to 828 ms —</p><pre>CREATE INDEX te_combi4group<br>ON imdb.title_episode (parentTconst, seasonNumber, episodeNumber);</pre><p><strong>Parting Thoughts :</strong> This concludes the Database Designing part. Finally, this is how the Entity Relationship Diagram looks like —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wDhQ6kRldxh708A8nBy1jw.png" /></figure><p>I had some other Data Extraction ideas — for instance, we can probably get more crew details(like Cinematographer etc.) from title_principals by processing each row and separating data based on the content text. But that was not needed for my objectives, and I was too tired at this point. I went back to my analysis task after this, 1st part of which is (again) available here —</p><p><a href="https://medium.com/@koustavin/imdb-sql-data-analysis-part-ii-the-objectives-assumptions-and-data-exploration-b8fae4329f93">IMDB SQL Data Analysis : Part II — The Objectives &amp; Assumptions, and Data Exploration</a></p><p>All files related to the project, including the SQL scripts used in Database Designing and Analysis part, are available in my <a href="https://github.com/koustavin/IMDB-SQLAnalysis">GitHub</a> repository . Be warned though, they are not very well organized, since the main learnings and findings are documented in these articles. See you soon in the Analysis article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=492751ab16c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Do Stock Markets Go Down on Fridays?]]></title>
            <link>https://medium.com/@koustavin/do-stock-markets-go-down-on-fridays-29735443aaff?source=rss-de554458f133------2</link>
            <guid isPermaLink="false">https://medium.com/p/29735443aaff</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tableau]]></category>
            <category><![CDATA[portfolio-project]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Koustav]]></dc:creator>
            <pubDate>Sat, 18 Mar 2023 23:56:05 GMT</pubDate>
            <atom:updated>2023-03-23T20:33:29.320Z</atom:updated>
            <content:encoded><![CDATA[<h4>For my first proper Data Analysis project, I decided to test out a long held belief of mine. My interest in Financial markets started 12–13 years back, when I was working at the National Stock Exchange (as a consultant). Seeing the tickers move on the board everyday gives you a feeling of being at the center of things. I thought I saw a general trend where stock prices generally settled a bit lower on Fridays before the Close and rose back to normal levels again after Monday Open. I had rationalized this internally thinking people would generally square off their positions going into the weekend. This made sense to me, but I have never seen any proof to substantiate this. Even if it’s a small drop, it could be significant if it’s a consistent trend — so why was no one talking about this? Let’s test it out.</h4><p>For this project, I decided to use a <a href="https://www.investopedia.com/terms/m/marketindex.asp">Market Index</a> as a representative of overall stock market — since using individual stock prices would have been too chaotic. Before this, I had used pandas_datareader to get historical stock market prices for a course specific mini-project months back, and I had loved how easy it was to use and how it didn’t require any authentication. Unfortunately though, my earlier data source Yahoo Finance didn’t seem to be working now(January/February 2023). For an earlier version of this project I used Stooq instead, which has data for various Global indices. It had only one Indian index though — Sensex, so that’s what I did my initial analysis on. However, I really wanted to use Nifty 50 for my final analysis. So, after some digging, I found a work around to get Yahoo Finance working again in datareader. For this analysis, we looked at Nifty 50 prices from January 2010 to January 2023.</p><pre>from pandas_datareader import data<br>import yfinance as yf<br>yf.pdr_override()<br>NSEI = data.get_data_yahoo(&#39;^NSEI&#39;, start = &#39;2009-12-31&#39;, end = &#39;2023-01-31&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*neDk-IoxHwEZOChIuClcjQ.jpeg" /></figure><p>Before getting into the weekdays analysis, I wanted to explore the data (and Indian Stock Market in general). The first feature I extracted was Intraday Price Fluctuation as a percentage difference between day’s High and Low prices. For stocks, this is usually a good indicator of volatility — but I had never looked at this data for an Index. These are the dates having more than 5% fluctuation -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*vu4MEfSRBKQD_6RSt-1NaQ.jpeg" /></figure><p>11 of these 17 dates are from March 2020 — probably one of the most volatile months. Two out of one of the most volatile days(more than 18% fluctuation) is also from this month — 13th March 2020, when Covid panic was just starting. The other date is 5th October 2012 — the infamous NSE Flash Crash. Funny story — I was working in the NSE BKC offices at that time, remember the hectic work day and worried looks. Here is the distribution for Price Fluctuation -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*IoxG4ok5PIIYGVJbE2ir9A.png" /></figure><p>Nifty 50 (and overall the Indian Stock Market) had a somewhat good run over our data range — from Close Price of 5232 on 4th January 2010 to Close Price of 17662 on 31st January 2023, at roughly 9.8% CAGR.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*w4KXOe5s2kpJqlfY2lJ8Bw.png" /></figure><p>I wanted to know what were the best and worst years been so far. So, decided to take a yearly resample of the Close price and take diff on that. From the results, it looks like the best and worst years have been 2021 and 2020 respectively.</p><pre>NSEI_YrlyCloseMean = NSEI.Close.resample(&#39;Y&#39;).mean()<br>NSEI_YrlyCloseMean_df = pd.DataFrame(NSEI_YrlyCloseMean)<br>NSEI_YrlyCloseMean_df[&#39;Diff&#39;] = NSEI_YrlyCloseMean_df.Close.diff()<br>NSEI_YrlyCloseMean_df[&#39;DiffPct&#39;] = NSEI_YrlyCloseMean_df.Close.pct_change() * 100</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*uLtu97plwRYdSTmB7yBJaA.jpeg" /></figure><p>Next, I derived Close Price Difference (in absolute value and percentage) between successive trading days, which led to calculation of our Market Move marker — it’s ‘Up’ if Close Price Difference is larger than 0, ‘Down’ otherwise. Also, determined the Day of The Week value, since our analysis will need that. One thing to note here, there were 3 trading days (out of more than 3200 days) where Close Price remained flat (Close Price Difference = 0) — we have counted them in ‘Down’ days, because if it’s not going up…</p><pre>NSEI[&#39;CloseDiff&#39;] = NSEI.Close.diff()<br>NSEI[&#39;CloseDiffPct&#39;] = NSEI.Close.pct_change() * 100<br>NSEI[&#39;MarketMove&#39;] = NSEI.CloseDiff.apply(lambda x : &#39;Up&#39; if x &gt; 0 else &#39;Down&#39;)<br>NSEI[&#39;DayOfWeek&#39;] = NSEI.index.day_name()</pre><p>Here is a quick look at the distribution of Close Price Difference Percent, it’s almost a Normal Distribution with Mean around 0 (actual mean 0.04) — indicating that the price is growing but not a miraculous rate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*I4aFMTVLPG7hhCFZOsiWkA.png" /></figure><p>Also, here is a box plot of Close Price Difference Percent vs Day of The Week. Keeping the outliers (that also ‘widened’ some of the boxes) aside, all of them have a mean around 0 — this corroborates the distribution plot above and doesn’t show any indication of Price moving any differently (on ‘average’) on any specific weekday.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*TCVCX8fvlmHE_IDtKv3ENw.png" /></figure><p>Now let’s look at the ‘Money’ question — whether we have more ‘Down’ days (than the number of ‘Up’ days) on Friday.</p><pre>NSE_grp_DayMove_cnt = NSEI.groupby([&#39;DayOfWeek&#39;, &#39;MarketMove&#39;])[&#39;Close&#39;].count()<br>NSE_grpbyDay_Movecnt = NSEI[[&#39;DayOfWeek&#39;, &#39;MarketMove&#39;]].groupby([&#39;DayOfWeek&#39;]).value_counts(normalize = True) * 100</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PdyUDRX4BVyEw328i_HrPg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*RuogBFm_6MqX2BTyNmLKlQ.png" /></figure><p>Well, if anything — this disproves my assumption. For all days of the week, there are more days when the Index price has gone up, than the number of days when it has gone down. I can’t say this is surprising, given the overall index has gone up so much over the last 12–13 years. But over our data range(1st January, 2010 to 31st January, 2023) — there is no evidence that Index price regularly falls on Fridays. Last thing we should confirm is whether this has been the ‘general trend’ throughout the years. Let’s look at the number of Up/Down Fridays for all years individually -</p><pre>NSE_grp_DayMoveYr_cnt = NSEI.groupby([NSEI.index.year, &#39;DayOfWeek&#39;, &#39;MarketMove&#39;])[&#39;Close&#39;].count()<br>NSE_grp_DayMoveYr_cnt[:, &#39;Friday&#39;, &#39;Up&#39;].plot(color = &#39;blue&#39;, label = &#39;Up&#39;)<br>NSE_grp_DayMoveYr_cnt[:, &#39;Friday&#39;, &#39;Down&#39;].plot(color = &#39;orange&#39;, label = &#39;Down&#39;)<br>plt.xlabel(&#39;Year&#39;)<br>plt.ylabel(&#39;Number of Days&#39;)<br>plt.title(&#39;Index Price Movement on Fridays, Throughout The Years&#39;)<br>plt.legend()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*PT30rEZzgvebG0mxQAxtNQ.png" /></figure><p>Hold on, this paints little bit of a different picture. Number of ‘Down’ days on Fridays were not smaller than number of ‘Up’ days in 2010(24 vs 23), 2011(33 vs 18), 2012(same here, 25 on both counts), 2013(25 vs 23) and 2021(28 vs 20) — the more drastic years being 2011 and 2021. I had started working at NSE in December of 2010. So, whatever I thought I had noticed would have been in 2011 — this at least proves that I wasn’t dreaming. Also, from what we saw earlier — 2011 was one of the worst years in terms of Index performance, and 2021 was the absolute best.</p><p>I had tried to look around a bit further in my analysis around these 2 years after that, but didn’t get any definitive answer. You can take a look at the notebook on my <a href="https://github.com/koustavin/SNXWeekDay">github</a>. I don’t think I have the proper data or expertise to decode why in some years on Fridays Stock Market was more likely to fall than rise, and in some years we saw the reverse. For now, I am going to consider these odd years as random, and look at the whole data range to come to a conclusion. Can I say that Stock Markets are more likely to fall on Fridays? Absolutely no, you should not make your investment decisions based on that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*OnPn3wS5lrgcsBXJEZ_efg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*8TJ033zbne1no0yTwe_Fxw.png" /></figure><p>The only conclusion we can draw with statistical significance over this 13+ years long dataset is this — (I) Given that it’s a Friday, there is slightly higher chance of Index Price going Up (51%), rather than Down (49%). (II) Given that Index Price has gone down, and each day of the week is equally probable [our dataset is slightly skewed — we have slightly less number of Fridays. But we can consider each day equiprobable when we are just looking at the probability of each day markets going up/down separately] — there is a slightly higher chance that Price would go down on a Friday than any other days. To clarify further, consider we are comparing between exactly 1000 Mondays, Tuesdays, Wednesdays, Thursdays and Fridays. The diagram below shows <em>(in a slightly exaggerated way, since we are not showing the whole chart to emphasize the difference)</em> that number of Down Days will be highest for Fridays —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NfMKc8e7znzZ_38M7RveGg.jpeg" /></figure><p>Here is a Tableau Dashboard of my analysis, if you are interested — <a href="https://public.tableau.com/app/profile/koustav.bhattacharya/viz/Nifty50PriceAnalysis/Consolidated_1">Nifty 50 Price Analysis</a>, you can look at the data at a desired granularity level (monthly or yearly) and for various time periods. Once again, the notebook is available on <a href="https://github.com/koustavin/SNXWeekDay">github</a>.</p><p>There are a few articles on the web around this topic, like this — <a href="https://www.fool.co.uk/2021/06/30/why-do-stocks-go-down-on-friday/">Why do stocks go down on Friday? | The Motley Fool UK</a>. Apparently, there is also a phenomenon called the Weekend Effect, where returns are supposed to be lower on Mondays — <a href="https://www.investopedia.com/terms/w/weekendeffect.asp">Weekend Effect: What It Is &amp; Why It Happens (investopedia.com)</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29735443aaff" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>