<?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 Idjaz on Medium]]></title>
        <description><![CDATA[Stories by Idjaz on Medium]]></description>
        <link>https://medium.com/@idjaz?source=rss-8fbe319eca89------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZzK_T0BamLo4-AYMd6aGjw.jpeg</url>
            <title>Stories by Idjaz on Medium</title>
            <link>https://medium.com/@idjaz?source=rss-8fbe319eca89------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 17:45:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@idjaz/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[Crypto Trend Following Strategy: Using Python]]></title>
            <link>https://medium.com/coinmonks/crypto-trend-following-strategy-using-python-5910d7ab4f0d?source=rss-8fbe319eca89------2</link>
            <guid isPermaLink="false">https://medium.com/p/5910d7ab4f0d</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <dc:creator><![CDATA[Idjaz]]></dc:creator>
            <pubDate>Sun, 23 Apr 2023 08:56:53 GMT</pubDate>
            <atom:updated>2023-04-25T08:40:54.254Z</atom:updated>
            <content:encoded><![CDATA[<p>Simple moving averages (SMAs) vs Exponential moving averages (EMAs)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xu_yRcTgCa5fQ5ZXtkQWbA.png" /></figure><p><strong>Abstract &amp; Background</strong></p><p>There are two general approaches for gaining insights of the markets in trading. There is <strong>fundamental analysis</strong> which involves carefully examining the supply and demand factors, or “fundamentals” for a particular token and it is believed to possibly predict changes in market conditions. On the other hand, there is <strong>technical analysis</strong> where the underlying philosophy for this approach is that the market prices well reflect all known factors at all times. So the price is already a solid performance indicator as a result of the supply and demand for that particular token.</p><p><strong>What’s Trend Following?</strong></p><p>Trend following is a type of technical analysis that neither predicts nor forecasts. <strong>It simply responds meticulously to what has recently happened and what is currently happening, rather than anticipating what will happen. </strong>The idea of a trend is intimately connected with that of momentum — <strong>if price moves in one direction in one period, it is likely to continue that direction in the next</strong>. However, there can be reversals within trends, and the key to successful trend following is to discover when a trend starts and ends. Accordingly, traders who use this approach typically use the current market price calculation and <strong>moving averages</strong> to determine the general direction of the market (the “trend”) and generate trade signals.</p><p><strong>Let’s get started!</strong></p><blockquote><strong><em>Simple Moving Average (SMA)</em></strong></blockquote><p>The simple moving average (SMA) is a <strong>smoothing function</strong> that calculates the average of the past observations. The idea behind is simply to smooth out an otherwise volatile series. For example, if we have n days of daily pricing data, the 50-day moving average is calculated by averaging the first 50 days and subsequently averaging 50 days at a time by shifting the range one day at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*mhFgqO4jz3diTtqorldGxg.png" /><figcaption><strong>50 Day SMA Mathematical Function</strong></figcaption></figure><p><strong>Step I: Data Collection &amp; Processing (Python)</strong></p><pre># Libraries I will be using<br><br>import pandas as pd<br>import requests<br>import json<br>import datetime<br>import yfinance as yf<br>import numpy as np</pre><pre># Collecting BTC Price data from YFinance<br><br>import yfinance as yf<br>import pandas as pd<br><br>btc = yf.Ticker(&quot;BTC-USD&quot;)<br>start = &quot;2021-11-10&quot;<br>end = &quot;2023-04-19&quot;<br>interval = &quot;1d&quot;<br><br>df1 = btc.history(start=start, end=end, interval=interval)<br>df1 = df1[[&#39;Close&#39;]]<br>df1 = df1[[&#39;Close&#39;]].rename(columns = {&#39;Close&#39;: &#39;BTC Price&#39;})<br>df1.index = pd.to_datetime(df1.index, utc=True).tz_localize(None)<br>df1 = df1.reset_index()<br>df1.set_index(&quot;Date&quot;, inplace=True)<br>print(df1)</pre><pre># Use the pandas rolling function for calculating the 50-day moving average, <br># and add the result as a new column to the DataFrame.<br># The 50 first moving average values show as NaN. <br># This is because we needed the first 50 price observations to calculate the MA.<br><br>df1[&quot;BTC 50MA (Trend)&quot;] = df1[&quot;BTC Price&quot;].rolling(window=50).mean()<br>df1.dropna(inplace=True)<br>df1</pre><pre># Plotting Everything<br><br>import matplotlib.pyplot as plt<br>from matplotlib.pyplot import figure<br>import matplotlib.dates as mdates<br><br># Setting the color style<br>plt.style.use(&#39;seaborn-dark&#39;)<br>plt.style.use(&quot;tableau-colorblind10&quot;)<br><br>fig, ax = plt.subplots(figsize=(8,4),dpi=200)<br>ax.plot(df1[&#39;BTC Price&#39;], label=&#39;BTC Price&#39;, color = &#39;#1a5276&#39;) #dark blue line<br>ax.plot(df1[&#39;BTC 50SMA (Trend)&#39;], label=&#39;50 Day SMA (Trend)&#39;, color = &#39;#FF7F50&#39;) #orange peach line<br>ax.plot(df1[&#39;BTC 50EMA (Trend)&#39;], label=&#39;50 Day EMA (Trend)&#39;, color = &#39;#800020&#39;) #burgundy line (see next chart)<br><br>plt.title(&#39;BTC Cycles&#39;)<br>plt.grid(True) #adding grid lines<br>plt.legend()<br><br># Formatting the Date axis to show quarterly data<br>quarters = mdates.MonthLocator(bymonth=[1, 4, 7, 10])<br>ax.xaxis.set_major_locator(quarters)<br>ax.xaxis.set_major_formatter(mdates.DateFormatter(&#39;%b-%Y&#39;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mqEmg28MvLMiJXe7p_PCZw.png" /><figcaption><strong>50 Day Simple Moving Average — Generated in Python</strong></figcaption></figure><blockquote><strong><em>Exponential Moving Average (EMA)</em></strong></blockquote><p>Unlike the SMA, the exponential moving average assigns a greater weight to more recent observations and uses an exponentially decaying weighting function. It is also more responsive to changes in price movements. This means that the EMA can be used to identify trends earlier than the SMA, allowing traders to enter and exit trades at more favorable prices. Now, we will not dive into the rather complex mathematical function of the EMA and jump right into looking at some charts.</p><pre># exponential moving average<br>df1[&quot;BTC 50EMA (Trend)&quot;] = df1[&quot;BTC Price&quot;].ewm(span=50).mean()<br>df1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U4fzv07hNI6eGOuxSmFtBA.png" /><figcaption><strong>50 Day SMA vs EMA — Generated in Python</strong></figcaption></figure><p>Generally, we hope to catch the ride when BTC is trending upwards (<strong>BTC price exceeds the moving average, i.e. take a long position</strong>) and when it trends downwards we short sell in order to benefit from the fall (<strong>BTC price drops below the moving average, i.e. take a short position</strong>).</p><pre># Generate long/short signals<br># Using 1 for long and -1 for short - LongShort Strategy<br><br>Signal_SMA_LongShort = []<br>Signal_EMA_LongShort = []<br><br>for i in range(0, df1.shape[0]):<br>    if df1[&quot;BTC Price&quot;].iloc[i] &gt; df1[&quot;BTC 50SMA (Trend)&quot;].iloc[i]:<br>        Signal_SMA_LongShort.append(1)<br>    else:<br>        Signal_SMA_LongShort.append(-1)   <br>        <br>    if df1[&quot;BTC Price&quot;].iloc[i] &gt; df1[&quot;BTC 50EMA (Trend)&quot;].iloc[i]:<br>        Signal_EMA_LongShort.append(1)<br>    else:<br>        Signal_EMA_LongShort.append(-1)<br><br>df1[&#39;Signal_SMA_LongShort&#39;] = Signal_SMA_LongShort<br>df1[&#39;Signal_EMA_LongShort&#39;] = Signal_EMA_LongShort<br><br># Displaying the last few rows of the BTC price data with the SMA and EMA signals<br>print(df1.tail())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*SK8i7QkQtE4dpbHs2ZhOjQ.png" /><figcaption><strong>Long vs Short Trade Signals</strong></figcaption></figure><p><strong>Step III: Strategy Performance (risk-return profile)</strong></p><pre># Calculate the daily returns for each strategy<br>df1[&#39;SMA_returns_LongShort&#39;] = df1[&#39;Signal_SMA_LongShort&#39;] * df1[&#39;BTC Price&#39;].pct_change()<br>df1[&#39;EMA_returns_LongShort&#39;] = df1[&#39;Signal_EMA_LongShort&#39;] * df1[&#39;BTC Price&#39;].pct_change()<br>df1.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0_gtFtl4qOhiyUrnMQwpEw.png" /><figcaption><strong>Daily Return Profile — SMA vs EMA</strong></figcaption></figure><pre># initial capital of $1000<br>initial_capital = 1000<br><br># Calculate the cumulative returns for each strategy<br>df1[&#39;SMA_cumul_LongShort&#39;] = (1 + df1[&#39;SMA_returns_LongShort&#39;]).cumprod() * initial_capital<br>df1[&#39;EMA_cumul_LongShort&#39;] = (1 + df1[&#39;EMA_returns_LongShort&#39;]).cumprod() * initial_capital<br><br># Plot the cumulative returns for each strategy<br>#df1[[&#39;SMA_LongShort&#39;,&#39;EMA_LongShort&#39;]].plot(figsize=(10, 6))<br><br>fig, ax = plt.subplots(figsize=(8,4),dpi=200)<br>ax.plot(df1[&#39;SMA_cumul_LongShort&#39;], label=&#39;SMA_LongShort Strategy&#39;) #orange peach line<br>ax.plot(df1[&#39;EMA_cumul_LongShort&#39;], label=&#39;EMA_LongShort Strategy&#39;) #orange peach line<br><br># Set color style &amp; formatting<br>plt.title(&#39;Cumulative Return Profile&#39;)<br>plt.legend()<br>plt.style.use(&#39;seaborn-dark&#39;)<br>plt.style.use(&quot;tableau-colorblind10&quot;)<br>plt.grid(True) #adding grid lines<br><br># Formatting the Date axis to show quarterly data<br>quarters = mdates.MonthLocator(bymonth=[1, 4, 7, 10])<br>ax.xaxis.set_major_locator(quarters)<br>ax.xaxis.set_major_formatter(mdates.DateFormatter(&#39;%b-%Y&#39;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6wEzzLBI8A_jzeAJ_J8KXQ.png" /></figure><p>Now, it would be somehow unrealistic to simply look at the cumulative return profile and conclude that a long/short EMA is a better performing strategy than a long/short SMA. Accordingly, we will look into some of the risk-adjusted performance metrics that are often used to evaluate the performance of an investment strategy.</p><p>The <strong>sharpe ratio</strong> is a measure of the excess return per unit of risk and a higher Sharpe Ratio generally indicates a better risk-adjusted performance, as the investment is generating higher returns for the same level of risk. Similarly, <strong>maximum drawdown </strong>measures the maximum fall in the value of the investment, as given by the difference between the value of the lowest trough and that of the highest peak before the trough. It provides a measure of the downside risk of an investment and a lower maximum drawdown generally indicates lower downside risk.</p><pre># Calculate the statistical metrics for each strategy using the quantstats library<br># QuantStats is a Python library for quantitative financial analysis. It provides tools for analyzing and comparing portfolio performance, backtesting trading strategies, <br># and evaluating risk. QuantStats is built on top of popular libraries like Pandas, NumPy, and Matplotlib.<br># QuantStats provides several functions for portfolio analysis, including metrics such as portfolio returns, drawdowns, Sharpe ratio, Sortino ratio, and Calmar ratio. <br># It also includes functions for calculating portfolio optimization and diversification metrics, such as correlation and covariance matrices, mean-variance optimization, <br># and diversification ratios.<br># Documentation can be found here: https://pypi.org/project/QuantStats/<br><br>import quantstats as qs<br><br># Calculate the Sharpe ratio (daily) and maximum drawdown (daily) for each strategy<br>sma_sharpe = qs.stats.sharpe(df1[&#39;SMA_returns_LongShort&#39;])<br>ema_sharpe = qs.stats.sharpe(df1[&#39;EMA_returns_LongShort&#39;])<br>sma_max_drawdown = qs.stats.max_drawdown(df1[&#39;SMA_cumul_LongShort&#39;]) * 100  # convert to percentage<br>ema_max_drawdown = qs.stats.max_drawdown(df1[&#39;EMA_cumul_LongShort&#39;]) * 100  # convert to percentage<br><br># Format the results as a table<br>table = pd.DataFrame({<br>    &#39;Sharpe Ratio&#39;: [sma_sharpe, ema_sharpe],<br>    &#39;Max Drawdown&#39;: [&#39;{:.2f}%&#39;.format(sma_max_drawdown), # max drawdown to 2dp<br>                     &#39;{:.2f}%&#39;.format(ema_max_drawdown)]<br>}, index=[&#39;SMA&#39;, &#39;EMA&#39;])<br><br># Print the table<br>print(table)<br><br># Max Drawdown Graph for EMA<br><br>ema_drawdowns = (df1[&#39;EMA_cumul_LongShort&#39;].cummax() - df1[&#39;EMA_cumul_LongShort&#39;]) / df1[&#39;EMA_cumul_LongShort&#39;].cummax()<br><br># Plot the drawdowns of SMA and EMA<br>fig, ax = plt.subplots(figsize=(10, 5))<br>ema_drawdowns.plot(ax=ax, label=&#39;EMA&#39;)<br><br># Invert the y-axis<br>ax.invert_yaxis()<br><br># Add legend, title, and axis labels<br>ax.set_title(&#39;EMA_LongShort Strategy Drawdowns&#39;)<br>ax.set_xlabel(&#39;Date&#39;)<br>ax.set_ylabel(&#39;Drawdown&#39;)<br>plt.style.use(&#39;seaborn-dark&#39;)<br>plt.style.use(&quot;tableau-colorblind10&quot;)<br>plt.grid(True) #adding grid lines</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*u2-ZYzIX31lIUYzd2cUkog.png" /><figcaption><strong>EMA vs SMA — Performance Metrics</strong></figcaption></figure><p>Based on these numbers, the EMA strategy does have a higher sharpe ratio which suggests that it is generating higher risk-adjusted returns than the SMA strategy. However, the EMA strategy also has a higher maximum drawdown than the SMA strategy. This indicates that it has experienced a larger peak-to-trough decline in value and that the EMA strategy carries more downside risk than the SMA strategy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pjnK7ty-ywgEAv9k0MOweA.png" /></figure><p><strong>Concluding Remarks</strong></p><p>Our analysis has shown that trend following using moving averages can be a valuable tool for traders in the crypto market.</p><p>We also found that although EMA LongShort strategy carries a higher risk-adjusted returns, it also had a larger max drawdown than the SMA LongShort strategy during the period we analyzed. Effectively, the EMA is more responsive to recent price changes, which means it can be expected to have larger swings in the short term. This responsiveness can cause EMA to react more quickly to market changes, which can lead to larger drawdowns when the market moves against the position.</p><p>Moreover, it can be insightful to consider the context in which this occurred. During the period we analyzed, the market experienced significant volatility and downturns related to Terra-LUNA and NFTs, as well as bankruptcy filings from Voyager and Celsius.</p><blockquote><strong><em>In the News!</em></strong></blockquote><blockquote><em>In April, </em><a href="https://www.forbes.com/sites/qai/2022/09/20/what-really-happened-to-luna-crypto/?sh=636529a94ff1"><strong><em>Terra’s</em></strong></a><em> algorithmic stablecoin TerraUSD (UST) had a market cap as high as almost US$18.7 billion. That all fell apart within a few days in May.</em></blockquote><blockquote><em>On Jun. 27, the U.S-based crypto lender U.S.-based </em><a href="https://www.cnbc.com/2022/08/15/voyager-customers-beg-new-york-judge-for-money-back-after-bankruptcy.html"><strong><em>Voyager</em></strong></a><em> issued a notice of default to hedge fund </em><a href="https://www.cnbc.com/2022/07/11/how-the-fall-of-three-arrows-or-3ac-dragged-down-crypto-investors.html"><strong><em>Three Arrows Capital (3AC)</em></strong></a><em> for failing to service a loan worth about US$665 million. Singapore-based 3AC was next to fall. On Jun. 29, the firm was ordered liquidated by a British Virgin Islands court. Two days later, 3AC filed for bankruptcy under Chapter 15.</em></blockquote><blockquote><em>On Jul. 5, Voyager and its affiliates filed for bankruptcy under Chapter 11. </em><a href="https://www.theguardian.com/technology/2022/jul/15/celsius-network-crypto-firm-deficit-bankruptcy-funds"><strong><em>Celsius</em></strong></a><strong><em> </em></strong><em>filed for bankruptcy under Chapter 11 on Jul. 13.By mid-summer, a “crypto winter ” had set in, with prices of crypto assets extending declines. Bitcoin dropped around 70% from its all-time high in November 2021 by July.</em></blockquote><p>We have also made several assumptions. There is no slippage or transaction fees. We have also used the daily BTC close prices and can only make a transaction at that time. Similarly, while moving averages can be a powerful tool for trend following, there are ways to optimize their use even further. For example, we could incorporate additional signal strength indicators like the <strong>Relative Strength Index (RSI)</strong> to help confirm or filter trading signals or implementing a <strong>trailing stop loss</strong> that can help protect profits and minimize losses in rapidly changing market conditions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5910d7ab4f0d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/crypto-trend-following-strategy-using-python-5910d7ab4f0d">Crypto Trend Following Strategy: Using Python</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cross Exchange Arbitrage: Using Python]]></title>
            <link>https://medium.com/coinmonks/cross-exchange-arbitrage-using-python-7fb43caef343?source=rss-8fbe319eca89------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fb43caef343</guid>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Idjaz]]></dc:creator>
            <pubDate>Tue, 18 Apr 2023 10:03:30 GMT</pubDate>
            <atom:updated>2023-04-19T12:41:57.704Z</atom:updated>
            <content:encoded><![CDATA[<p>Exploiting Crypto Price Discrepancies through Cross-Exchange Arbitrage</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9oIg0HnHlm7KuxDxrHqkIQ.png" /></figure><p><strong>Abstract &amp; Motivation</strong></p><p>Cross exchange arbitrage is a popular trading strategy in the world of cryptocurrencies, and it involves taking advantage of price discrepancies between different exchanges to make a profit. In this article, we will be demonstrating how this mechanism works by considering two popular cryptocurrency data aggregators, <strong>Coingecko</strong> and <strong>YFinance</strong>. Although these are not real exchanges, they will serve as a demo to showcase how traders can take advantage of price discrepancies to make a profit.</p><p>We will be looking at BTC prices on both platforms over a <strong>1 day timeframe from April 17, 2023, 00:00:00 to April 17, 2023, 23:55:00 (5 min intervals)</strong>, and by monitoring the prices of BTC on both platforms, we will be able to identify any potential differences in price and determine if there is an opportunity for cross exchange arbitrage.</p><pre>#Libraries we will be using<br>import pandas as pd<br>import requests<br>import json<br>import datetime<br>import yfinance as yf</pre><p><strong>Step I: Connecting to Exchange 1 — Coingecko API</strong></p><pre><br># Set the API endpoint and parameters<br>url = &quot;https://api.coingecko.com/api/v3/coins/bitcoin/market_chart/range?vs_currency=usd&amp;from=1681689600&amp;to=1681776000&quot;<br><br>#1681689600 : Mon Apr 17 2023 00:00:00 GMT+0000<br>#1681776000 : Tue Apr 18 2023 00:00:00 GMT+0000<br><br># Send a GET request to the API endpoint<br>response = requests.get(url)<br>data = json.loads(response.text)</pre><pre># Extract the price data from the response<br>prices = data[&#39;prices&#39;]<br><br># Convert the price data to a Pandas dataframe<br>df = pd.DataFrame(prices, columns=[&#39;timestamp&#39;, &#39;price&#39;])<br>df = df[[&#39;timestamp&#39;, &#39;price&#39;]].rename(columns = {&#39;price&#39;: &#39;Coingecko BTC&#39;,&#39;timestamp&#39;:&#39;Timestamp&#39;})<br><br># Convert the timestamp to a datetime object<br>df[&#39;Timestamp&#39;] = pd.to_datetime(df[&#39;Timestamp&#39;], unit=&#39;ms&#39;)<br>print(df)</pre><pre>#Simple manipulation of the Timestamp column to have a linear 5 mins interval.<br><br>start_time = pd.to_datetime(&#39;2023-04-17 00:00:00&#39;)<br>end_time = pd.to_datetime(&#39;2023-04-17 23:55:00&#39;)<br><br>interval = &#39;5min&#39;<br>new_index = pd.date_range(start=start_time, end=end_time, freq=interval)<br><br>df[&#39;Timestamp&#39;] = new_index<br>print(df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*p-dMYS4RkmHXLm1mg6PO8w.png" /><figcaption><strong>Python Output — Coingecko BTC Prices</strong></figcaption></figure><p><strong>Step II: Connecting to Exchange 2 — YFinance API</strong></p><pre>btc = yf.Ticker(&quot;BTC-USD&quot;)<br>start = &quot;2023-04-17&quot;<br>end = &quot;2023-04-18&quot;<br>interval = &quot;5m&quot;<br><br>df1 = btc.history(start=start, end=end, interval=interval)<br>df1 = df1[[&#39;Close&#39;]]<br>df1 = df1[[&#39;Close&#39;]].rename(columns = {&#39;Close&#39;: &#39;YFinance BTC&#39;})<br>df1.index = pd.to_datetime(df1.index, utc=True).tz_localize(None)<br>df1 = df1.reset_index()<br>print(df1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*J6Ha-9bXxEO3_5DjASWLkg.png" /><figcaption><strong>Python Output — YFinance BTC Prices</strong></figcaption></figure><p><strong>Step III: Data Aggregation &amp; Plot</strong></p><pre>df2 = df.join(df1[&#39;YFinance BTC&#39;])<br>print(df2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*UmxnefprsLcWs_QFBeefng.png" /><figcaption><strong>Output — Coingecko BTC vs YFinance BTC</strong></figcaption></figure><pre>import matplotlib.pyplot as plt<br>from matplotlib.pyplot import figure<br><br>fig, ax = plt.subplots(figsize=(8,4),dpi=200)<br>ax.plot(df2[&#39;Timestamp&#39;], df2[&#39;Coingecko BTC&#39;], label=&#39;Coingecko BTC (Exchange I)&#39;)<br>ax.plot(df2[&#39;Timestamp&#39;], df2[&#39;YFinance BTC&#39;], label=&#39;YFinance BTC (Exchange II)&#39;)<br>plt.title(&#39;BTC Price (Coingecko vs YFinance)&#39;)<br>plt.legend()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2h_DgyLm0yPVbiCfB1CjYA.png" /></figure><p>From the above, the graph displays the BTC prices on the two platforms, Coingecko and YFinance, represented by two separate lines that do not always overlap. This indicates a difference in prices between the two platforms, which is referred to as the <strong>spread (see below)</strong>. Effectively, traders can take advantage of this spread by buying when the Coingecko price is higher than the YFinance price, and selling when the YFinance price is higher than the Coingecko price, to make a profit.</p><p><strong>Step IV: Identifying the Spread</strong></p><pre>fig, ax = plt.subplots(figsize=(8,4),dpi=200)<br>plt.plot(df2[&#39;Timestamp&#39;], abs(df2[&#39;Coingecko BTC&#39;] - df2[&#39;YFinance BTC&#39;]), label = &#39;Spread | Coingecko - YFinance&#39;)<br>plt.title(&#39;Spread | Coingecko - YFinance&#39;)<br>plt.legend()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xJDIV4XD5QPZLH0w6khY9g.png" /></figure><p><strong>Perfect Environment</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WzasQFrvlc5mTGK4iySYbg.png" /></figure><p>Now, in a perfect environment with no trading costs, one could make around USD $6,320.03 in just 1 day if you were just constantly buying on 1 exchange and selling on another. But we do not live in ideal world and hence we have factor in trading fees from the exchanges.</p><p><strong>Trading Fees</strong></p><p>In cross exchange arbitrage, the concept of maker and taker fees applies to each exchange that you are trading on. When executing an arbitrage trade, you will need to buy and sell assets on different exchanges, and each exchange may have different maker and taker fees.</p><p>Let’s say you are trying to take advantage of a price difference of BTC between two exchanges, Coinbase and Binance. You want to buy 1 BTC on Coinbase at a lower price and sell it on Binance at a higher price. Here’s how maker and taker fees could apply to this scenario:</p><p><strong>On Coinbase:</strong></p><ul><li>If you place a limit order to buy 1 BTC, you are a maker and will pay the maker fee when your order is filled.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*s2B1DiidLlH9PvLuHq5Baw.png" /><figcaption><strong>Coinbase Fee Structure (See resources for full tier list)</strong></figcaption></figure><p><strong>On Binance:</strong></p><ul><li>If you place a market order to sell 1 BTC at the current market price, you are a taker and will pay the taker fee.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xFfa6gE7RMYPeioU3XZBmg.png" /><figcaption><strong>Binance Fee Structure (See resources for full tier list)</strong></figcaption></figure><p>Accordingly, when executing cross exchange arbitrage, it’s important to take these fees into account and factor them into profit calculations. Depending on the fees, it’s possible that the arbitrage opportunity may not be profitable after accounting for the fees on both exchanges.</p><p><strong>Step V: Factoring Trading Cost</strong></p><pre>#Buying low on 1 exchange and selling high on the other exchange<br>#Let&#39;s combine the necessary columns together applying a 0.2% average trading cost between the maker and taker<br><br>comb_df = pd.concat([df2[&#39;Timestamp&#39;],<br>                    df2[&#39;Coingecko BTC&#39;],<br>                    df2[&#39;YFinance BTC&#39;],<br>                    abs(df2[&#39;Coingecko BTC&#39;]-df2[&#39;YFinance BTC&#39;]),<br>                    0.002 * (df2[&#39;Coingecko BTC&#39;]+df2[&#39;YFinance BTC&#39;])], axis =1)<br>comb_df.columns = [&#39;Timestamp&#39;,&#39;Coingecko BTC&#39;, &#39;YFinance BTC&#39;, &#39;Absolute Difference&#39;, &#39;Trading Cost&#39;]<br>comb_df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*Yu844g0HpbduqKrLPUcDUg.png" /><figcaption><strong>Trading cost to fully execute the trade</strong></figcaption></figure><p><strong>Step V: Signal Generation</strong></p><pre>#Checking out which accounts in the corresponding exchanges need to be bought or sold<br>#Will return 0 if Coingecko BTC Price &gt; YFinance BTC Price (buy on Coingecko and sell on YFinance)<br>#Will return 1 if YFinance BTC Price &gt; Coingecko BTC Price (buy on YFinance and sell on Coingecko)<br><br>v = pd.DataFrame(np.where(comb_df[&#39;Coingecko BTC&#39;]&gt;comb_df[&#39;YFinance BTC&#39;], 0, 1))<br>v.columns = [&#39;BuyCoinSellYFin&#39;]<br>comb_df = pd.concat([comb_df,v],axis = 1)<br>comb_df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x51SvgaTPxhwimgl9FC1-g.png" /><figcaption><strong>Determining on which exchange one should buy/sell</strong></figcaption></figure><p><strong>Step VI: Trade Execution</strong></p><pre>#Execute Trade for Profit<br><br>order69 = pd.DataFrame(np.where(comb_df[&#39;Absolute Difference&#39;]&gt;comb_df[&#39;Trading Cost&#39;], 0, 1))<br>order69.columns = [&#39;Execute&#39;]<br>comb_df = pd.concat([comb_df,order69],axis = 1)<br>comb_df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rxhr2TL-TfDIFa6kVVYTaA.png" /></figure><p>Now, as one can see, <strong>most of the trades are actually not profitable</strong> (most values under the “Execute” column are 1s) since you get wiped out by trading costs. For example in line 0, trading cost ($121.244232) &gt; absolute difference ($4.986982)between the BTC buy and sell prices.</p><pre>#Let&#39;s get a tally on all the orders that would have been executed and be profitable<br>orders_fulfilled = comb_df.loc[comb_df[&#39;Execute&#39;]==0]<br>orders_fulfilled</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Cp8334Trrmcp2ciknBqWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dU40tEIJ_8vaQh3w3k9GuQ.png" /><figcaption><strong>Actual profits on the 2 executed trades</strong></figcaption></figure><p>Looking at the full data set of 288 trades, it can be observed that there are only 2 trades that are profitable (<strong>total profit of $303.69 in 1 day</strong>), with the absolute difference between the buy and sell prices being greater than the trading costs associated with the trade.</p><blockquote>The spread graph above showed two significant spikes in the spread, indicating a large difference in prices between the BTC buy and sell prices. Based on these spikes, it could be expected that there would only be a small number of profitable trades. This is because the large spread indicates that the trading costs would be high, reducing the likelihood of the trades being profitable. Therefore, it is not surprising to see that only two trades out of 288 were profitable, as the high trading costs would have made it difficult to make a profit on most of the trades. The spread graph provides valuable insights into the potential profitability of the trades and can be used to guide investment decisions.</blockquote><p><strong>Resources &amp; Acknowledgements:</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FTNJNCJe9fDY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DTNJNCJe9fDY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FTNJNCJe9fDY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/93aff708a002c825f6ff0b7a45ab2270/href">https://medium.com/media/93aff708a002c825f6ff0b7a45ab2270/href</a></iframe><p><a href="https://www.binance.com/en/fee/schedule">Fee Rate</a></p><p><strong>Coinbase Fee Structure (Maker &amp; Taker):</strong> <a href="https://help.coinbase.com/en/exchange/trading-and-funding/exchange-fees">https://help.coinbase.com/en/exchange/trading-and-funding/exchange-fees</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fb43caef343" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/cross-exchange-arbitrage-using-python-7fb43caef343">Cross Exchange Arbitrage: Using Python</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Twitter Sentiment Analysis: Using Python]]></title>
            <link>https://medium.com/@idjaz/twitter-sentiment-analysis-using-python-1ece9fc31d5a?source=rss-8fbe319eca89------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ece9fc31d5a</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[sentiment-analysis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[twitter]]></category>
            <dc:creator><![CDATA[Idjaz]]></dc:creator>
            <pubDate>Fri, 24 Mar 2023 20:00:19 GMT</pubDate>
            <atom:updated>2023-04-18T16:41:56.901Z</atom:updated>
            <content:encoded><![CDATA[<p>The Collapse of Silicon Valley Bank</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vs8xMsKh8MZ1aSqK4Q_Y_w.png" /></figure><p><strong>What’s sentiment analysis?</strong></p><p>Twitter is a place where people can share short messages with each other. Sometimes people use Twitter to talk about things they like, and sometimes they talk about things they don’t like. Now, imagine if we could read all of those messages and figure out if people are feeling happy or sad when they write them. That’s kind of like what Twitter sentiment analysis is. We use special tools to read all of those messages and figure out if people are feeling good or bad. Pretty cool, huh?</p><p><strong><em>Why Twitter?</em></strong></p><ol><li><strong>Real-time data</strong>: Twitter provides a real-time stream of data, which can be useful for monitoring market sentiment and reacting quickly to changes in sentiment.</li><li><strong>Large user base</strong>: Twitter has a large and diverse user base, which provides a broad range of opinions and perspectives on financial markets.</li></ol><p>Most recently, the collapse of the Silicon Valley Bank caused significant media attention and coverage. To that end, we will take a quick dive into conducting sentiment analysis of tweets related to the incident in order to gauge public opinion on the matter. We will further apply some machine learning models to extract some valuable insights into the attitudes and perspectives of the general public to make sense of the implications of the bank’s collapse and beyond.</p><p><strong>Key Event: The Collapse of the Silicon Valley Bank (SVB)</strong></p><p>Regulators shut down SVB Friday and seized its deposits in the largest U.S. banking failure since the 2008 financial crisis and the second-largest ever. The company’s downward spiral began late Wednesday, when it surprised investors with news that it needed to raise $2.25 billion to shore up its balance sheet. What followed was the rapid collapse of a highly-respected bank that had grown alongside its technology clients.</p><p>SVB’s stock plunged by <strong>60% </strong>in a single day, prompting regulators to step in and shut it down. Although a bailout by the US government has ensured all depositors will get their money back and seems to have quelled fears of a contagion effect, there will undoubtedly be ramifications across the tech and financial industries (<a href="https://www.nytimes.com/2023/03/19/business/economy/fed-silicon-valley-bank.html"><strong><em>see link</em></strong></a>)</p><p><strong>STEP I: GETTING &amp; CLEANING THE DATA</strong></p><pre>#The following code fetches 10000 tweets from Twitter&#39;s API using the snscrape module, <br>#filtering them by language and removing retweets, URLs, mentions, hashtags and newlines from the tweet content. <br>#The tweets are then added to a list of unique tweet contents and stored in a pandas DataFrame for further analysis. <br>#The search query used is for the term &quot;Silicon Valley Bank&quot; and the date range is from March 9th, 2023 to March 13th, 2023.<br><br>import snscrape.modules.twitter as sntwitter<br>import pandas as pd<br>import pytz<br>import re<br>from textblob import TextBlob<br>import matplotlib.pyplot as plt<br>import nltk<br>from wordcloud import WordCloud, STOPWORDS<br>import string<br>from nltk.corpus import stopwords<br>from nltk.tokenize import word_tokenize<br>nltk.download(&#39;vader_lexicon&#39;)<br>from sklearn.model_selection import train_test_split<br>from sklearn.feature_extraction.text import CountVectorizer<br>from sklearn.naive_bayes import MultinomialNB, BernoulliNB<br>from sklearn.metrics import classification_report, confusion_matrix<br>import seaborn as sns<br>from sklearn.linear_model import LogisticRegression<br><br>utc_timezone = pytz.timezone(&#39;UTC&#39;)<br>queries = [&quot;Silicon Valley Bank&quot;]<br>tweets = []<br>tweet_contents = set()<br>limits = 10000<br><br>nltk.download(&#39;stopwords&#39;)<br># Load the English stop words<br>stop_words = set(stopwords.words(&#39;english&#39;)) <br><br>for query in queries:<br>    for tweet in sntwitter.TwitterSearchScraper(query + &#39; lang:en since:2023-03-09 until:2023-03-14&#39;).get_items():<br>        if tweet.lang == &#39;en&#39; and not tweet.rawContent.startswith(&#39;RT&#39;):<br>            # Cleaning tweet content<br>            tweet_content = re.sub(r&#39;http\S+&#39;, &#39;&#39;, tweet.rawContent)<br>            tweet_content = re.sub(r&#39;https\S+&#39;, &#39;&#39;, tweet_content) #remove https/urls links<br>            tweet_content = re.sub(r&#39;@\S+&#39;, &#39;&#39;, tweet_content) #removes @<br>            tweet_content = re.sub(r&#39;\n&#39;, &#39; &#39;, tweet_content) #remove space between 2 sentences<br>            tweet_content = re.sub(r&#39;^RT\S+&#39;, &#39;&#39;, tweet_content) #removes any retweet tags at the beginning of a tweet<br>            tweet_content = re.sub(r&#39;#\S+&#39;, &#39;&#39;, tweet_content) #remove hashtags<br>            tweet_content = re.sub(r&#39;[0-9?!]+&#39;, &#39;&#39;, tweet_content) #remove and punctuation marks<br>            tweet_content = re.sub(r&#39;^\s+&#39;, &#39;&#39;, tweet_content) #remove space at the start of the tweet<br>            tweet_content = re.sub(f&#39;[{string.punctuation}’—-]&#39;, &#39;&#39;, tweet_content) #remove string punctuations<br>            tweet_content = re.sub(r&#39;[^\x00-\x7F]+&#39;, &#39;&#39;, tweet_content) #remove emojis<br>            tweet_content = &#39; &#39;.join([word for word in tweet_content.split() if word.lower() not in stop_words and len(word) &gt; 3]) #remove stopwords &amp; words length less than 3<br><br>            if tweet_content not in tweet_contents:<br>                tweet_contents.add(tweet_content)<br>                tweet_date = tweet.date.astimezone(utc_timezone).replace(tzinfo=None)<br>                tweets.append([tweet_date, tweet_content])<br>        <br>        if len(tweets) == limits:<br>            break<br><br>df = pd.DataFrame([t[1] for t in tweets], columns=[&#39;Tweet&#39;])<br>df.to_excel(&quot;Tweets.xlsx&quot;, index=False)</pre><blockquote><strong>Note</strong>: You can also access tweets via the Tweepy API by applying for a Twitter Developer Account. However, recent community forums show that there is currently a backlog of applications and some people have been waiting for over a month to receive feedback on their application (I applied on the 8th of March and it’s already been 2 weeks since I got any feedback). For now, the ‘snscrape’ module should do the trick!</blockquote><p><strong>STEP II: EXPLORING THE RESULTS</strong></p><pre>#word cloud<br>#A word cloud, is a visual representation of text data that highlights <br>#the most frequently occurring words. The words are typically displayed in a graphical format, <br>#with the size of each word indicating its frequency or importance in the text. <br>#Effectively, the most common words are displayed in larger font sizes, <br>#while less frequent words are displayed in smaller font sizes.<br><br># stopwords do not appear in the wordcloud.<br>stopwords = STOPWORDS.copy()<br>stopwords.update([&#39;Silicon&#39;, &#39;Valley&#39;,&#39;Bank&#39;])<br><br># Join all tweets into a single string<br>text = &#39; &#39;.join(df[&#39;Tweet&#39;].tolist())<br><br># Create a WordCloud object with some basic parameters<br>wordcloud = WordCloud(stopwords = stopwords, width=800, height=800, background_color=&#39;white&#39;, colormap=&#39;inferno&#39;, max_words=90).generate(text)<br><br># Plot the word cloud<br>plt.figure(figsize=(8, 8), facecolor=None)<br>plt.imshow(wordcloud)<br>plt.axis(&#39;off&#39;)<br>plt.tight_layout(pad=0)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*ZE862T0vcKWj9tLonesN8Q.png" /></figure><p>The output above shows that words like “collapse”, “failure”, “bailout”, “losses”, “Federal Reserve” are some of the most frequent words appearing in the retrieved tweets. This is as expected given we are analysing the collapse of SVB.</p><p><strong>STEP III: TRAINING THE MODEL</strong></p><p>The <a href="https://www.kaggle.com/datasets/kazanova/sentiment140"><strong><em>Sentiment140 dataset</em></strong></a> is used to train machine learning models to predict the sentiment of text. By training on this dataset, a model can learn to recognize patterns and features in the language that are associated with positive or negative sentiment. Once the model is trained, it can be used to make predictions on new, unseen text, allowing it to automatically classify the sentiment of new tweets or other types of text.</p><p>Sentiment140 is a popular dataset consisting of 1.6 million tweets labeled as either positive or negative. It was created in 2009 by Stanford University researchers to help train and evaluate sentiment analysis models.</p><pre>#Training a model using the Stanford Sentiment 140 Dataset<br><br># Load the Sentiment140 dataset<br>data = pd.read_csv(&#39;C:\\Users\\Idjaz\\OneDrive\\Desktop\\Python New\\training.1600000.processed.noemoticon.csv&#39;, encoding=&#39;ISO-8859-1&#39;, names=[&#39;target&#39;, &#39;id&#39;, &#39;date&#39;, &#39;flag&#39;, &#39;user&#39;, &#39;text&#39;])<br><br># Clean the data<br>data.drop(columns=[&#39;id&#39;, &#39;date&#39;, &#39;flag&#39;, &#39;user&#39;], inplace=True) #remove unncessary columns in the dataset<br>data[&#39;target&#39;] = np.where(data[&#39;target&#39;] == 0, 0, 1)<br><br># Split the data into training and testing sets<br>X_train, X_test, y_train, y_test = train_test_split(data[&#39;text&#39;], data[&#39;target&#39;], test_size=0.2, random_state=42)<br><br>#We split data into training and test sets to evaluate the performance of a machine learning model. <br>#The training set is used to train the model, while the test set is used to evaluate its performance on unseen data.<br>#Splitting the data into training and test sets helps us to ensure <br>#that our model is not overfitting to the training data, which can occur when <br>#the model becomes too complex and starts to memorize the training data rather than <br>#learning patterns that generalize to new data. By evaluating the model on unseen data,<br>#we can get a better estimate of its performance on new, real-world data.<br>#For example, if we set test_size to 0.2 and have a total of 1.6 million tweets, <br>#it means that 20% of the data (or 320,000 tweets) will be randomly selected and used for testing, <br>#while the remaining 80% of the data (or 1,280,000 tweets) will be used for training the model.<br><br># Tokenize the text using CountVectorizer<br>vectorizer = CountVectorizer(stop_words=&#39;english&#39;)<br>X_train_vec = vectorizer.fit_transform(X_train)<br>X_test_vec = vectorizer.transform(X_test)</pre><p><strong>STEP IV: FUNCTION FOR MODEL EVALUATION</strong></p><p>When performing sentiment analysis on scraped tweets, it’s essential to choose an appropriate classifier that accurately predicts the sentiment of the tweets. To select the best classifier, we usually split our dataset into two parts: a training set and a test set. We use the training set to train our model and then evaluate its performance on the test set. This evaluation helps us to determine which classifier works best on our data. The goal is to select the classifier that performs the best on the test set, as it will likely provide the most accurate predictions when applied to new, unseen data. Therefore, it’s crucial to use a classifier that is not only accurate on the training data but also generalizes well to new data.</p><p>For the purpose of our analysis, we will use and compare 2 popular classifiers namely <strong><em>Logistic Regression </em></strong>and<strong><em> Naive Bayes (Multinomial)</em></strong><em> </em>to see which one yields the best results on the scraped tweets.</p><pre>def model_Evaluate(model):<br># Predict values for Test dataset<br>    y_pred = model.predict(X_test_vec)<br>    # Print the evaluation metrics for the dataset.<br>    print(classification_report(y_test, y_pred))<br>    # Compute and plot the Confusion matrix<br>    cf_matrix = confusion_matrix(y_test, y_pred)<br>    categories = [&#39;Negative&#39;,&#39;Positive&#39;]<br>    group_names = [&#39;True Neg&#39;,&#39;False Pos&#39;, &#39;False Neg&#39;,&#39;True Pos&#39;]<br>    group_percentages = [&#39;{0:.2%}&#39;.format(value) for value in cf_matrix.flatten() / np.sum(cf_matrix)]<br>    labels = [f&#39;{v1}\n{v2}&#39; for v1, v2 in zip(group_names,group_percentages)]<br>    labels = np.asarray(labels).reshape(2,2)<br>    sns.heatmap(cf_matrix, annot = labels, cmap = &#39;Blues&#39;,fmt = &#39;&#39;,<br>    xticklabels = categories, yticklabels = categories)<br>    plt.xlabel(&quot;Predicted values&quot;, fontdict = {&#39;size&#39;:14}, labelpad = 10)<br>    plt.ylabel(&quot;Actual values&quot; , fontdict = {&#39;size&#39;:14}, labelpad = 10)<br>    plt.title (&quot;Confusion Matrix&quot;, fontdict = {&#39;size&#39;:18}, pad = 20)</pre><p><strong>STEP VI: TESTING THE DESIRED MODEL</strong></p><pre># Using Naive Bayes (Multinomial) Classifier<br><br>MNBmodel = MultinomialNB()<br>MNBmodel.fit(X_train_vec, y_train)<br>model_Evaluate(MNBmodel)<br>y_pred1 = MNBmodel.predict(X_test_vec)<br><br># Test the classifier on your scraped tweets<br>scraped_tweets_vec = vectorizer.transform(df[&#39;Tweet&#39;])<br>preds = MNBmodel.predict(scraped_tweets_vec)<br><br># Add the predictions to the DataFrame<br>df[&#39;Prediction&#39;] = preds<br><br># Count the number of positive and negative tweets<br>pos_count = np.count_nonzero(preds == 1)<br>neg_count = np.count_nonzero(preds == 0)<br><br># Plot the results in a horizontal bar chart<br>fig, ax = plt.subplots()<br>ax.barh([&#39;Negative&#39;, &#39;Positive&#39;], [neg_count, pos_count])<br>ax.set_xlabel(&#39;Count&#39;)<br>ax.set_title(&#39;Sentiment of Scraped Tweets&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*43LjFJkJrz2qCZqGz9VN7A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*yiSGNX8srghX8lal7xwgJg.png" /></figure><pre># Using Logistic Regression Classifier<br><br>LRmodel = LogisticRegression(C = 2, max_iter = 1000, n_jobs=-1)<br>LRmodel.fit(X_train_vec, y_train)<br>model_Evaluate(LRmodel)<br>y_pred3 = LRmodel.predict(X_test_vec)<br><br># Test the classifier on your scraped tweets<br>scraped_tweets_vec = vectorizer.transform(df[&#39;Tweet&#39;])<br>preds = LRmodel.predict(scraped_tweets_vec)<br><br># Add the predictions to the DataFrame<br>df[&#39;Prediction&#39;] = preds<br><br># Count the number of positive and negative tweets<br>pos_count = np.count_nonzero(preds == 1)<br>neg_count = np.count_nonzero(preds == 0)<br><br># Plot the results in a horizontal bar chart<br>fig, ax = plt.subplots()<br>ax.barh([&#39;Negative&#39;, &#39;Positive&#39;], [neg_count, pos_count])<br>ax.set_xlabel(&#39;Count&#39;)<br>ax.set_title(&#39;Sentiment of Scraped Tweets&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*tXrpcAxeJypUkZsN4ZekVg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*sFp95lgSs5Zn6q3lbpkx9g.png" /></figure><p><strong>STEP VII: CONCLUSION &amp; THOUGHTS</strong></p><p>Based on the evaluation of two classifiers on a set of scraped tweets, the Multinomial classifier seems to be performing better than the Logistic Regression classifier. Specifically, when tested on the scraped tweets, the Multinomial classifier predicted 7823 negative tweets (2173 positive tweets), while the Logistic Regression classifier predicted 6038 negative tweets (3962 positive tweets). This indicates that the Multinomial classifier may be a better choice for sentiment analysis of Twitter data. Given the nature of the event, we realistically expected to see more negative tweets than positive ones.</p><p><strong>Resources:</strong></p><ul><li><a href="https://openai.com/blog/chatgpt">Introducing ChatGPT</a></li><li><a href="https://www.justintodata.com/twitter-sentiment-analysis-python/">How to apply useful Twitter Sentiment Analysis with Python - Just into Data</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ece9fc31d5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Portfolio Optimization: Using Python]]></title>
            <link>https://medium.com/@idjaz/portfolio-optimization-using-python-870bd1d7a9d1?source=rss-8fbe319eca89------2</link>
            <guid isPermaLink="false">https://medium.com/p/870bd1d7a9d1</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[portfolio-management]]></category>
            <category><![CDATA[hedge-funds]]></category>
            <category><![CDATA[asset-management]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Idjaz]]></dc:creator>
            <pubDate>Sun, 05 Mar 2023 19:51:50 GMT</pubDate>
            <atom:updated>2023-04-18T16:41:41.879Z</atom:updated>
            <content:encoded><![CDATA[<h4>Modern Portfolio Theory &amp; Efficient Frontier</h4><p><strong>Background &amp; Thoughts</strong></p><p>What began with me wanting to put into practice some of the modern portfolio theory from CM2 led me to eventually write 250 lines of code to optimize some of my portfolio.</p><p>I currently have 3 of the mutual funds of the Mauritius Commercial Bank (MCB) in my personal portfolio which include the MCB Domestic Equites Fund (MCBDEF), the MCB Overseas Fund (MCBOF), and the MCB Yield Fund (MCBYF). My initial allocation dates back to 12 April 2022 which was purely on a discretionary basis (guilty of thinking I can just do so by interpreting factsheets). By 05 March 2023, my portfolio was down 3.743% (probably not a lot given recent market conditions but I must say it was kept fairly stable through dividend payments).</p><p>For full transparency, the initial allocation across the funds was 25% (MCBDEF), 40% (MCBOF), and 35% (MCBYF) which was me trying to “diversify” across both local and overseas holdings. Nevertheless, over the past few weeks, as I sit down exploring portfolio optimization techniques and building algorithms around historical data, I started writing down a few lines which could help me identify the optimal portfolio based on a certain set of constraints.</p><p>I have included some of the resources I have used as input (<em>courtesy of ChatGPT). </em>I have also commented out the full Python code which usually helps me find the logic behind a syntax and sometimes just a way to write down my thoughts. I now<em> </em>look forward to implementing this new risk-adjusted portfolio allocation and hopefully, it lives up to the claims of “long-term capital appreciation”.</p><p><strong>Modern Portfolio Theory</strong></p><p>Modern portfolio theory (MPT) is a mathematical framework for assembling a portfolio of assets such that risk-averse investors can construct portfolios to maximize expected return. This is based on a given level of market risk, emphasizing that higher risk is an inherent part of higher reward.</p><p>MPT uses weighted returns of equities to calculate a portfolio-wide return. Then it uses statistical measures such as variance (standard deviation) and correlation to determine ‘risk’ of a portfolio. It is important to note that for a portfolio comprised of ’n’ assets you can’t simply sum the standard deviation of each asset to calculate the total risk, but must also account for the correlation between assets.</p><p>Using MPT, one can calculate what is called the ‘efficient frontier,’ which is the set of ‘optimal’ portfolios that offer the highest expected return for a defined level of risk. In this post, we will run thousands of portfolio simulations to highlight where the efficient frontier is, given a set of stocks.</p><p>The application of mean-variance portfolio theory is based on some important assumptions: <em>all expected returns, variances and covariances of pairs of assets are known, investors make their decisions purely on the basis of expected return and variance, investors are non-satiated (prefers more to less), investors are risk-averse, and there are no taxes or transaction costs.</em></p><p><strong>Code</strong></p><pre>import pandas as pd<br>import os.path<br>import glob<br>import matplotlib.pyplot as plt<br>import numpy as np<br>import datetime<br>import matplotlib.dates as mdates<br><br># STEP I - GETTING THE DATA<br><br># Define the folder path, Excel file names, and performance column names<br>folder_path = &quot;C:\\Users\\Idjaz\\OneDrive\\Desktop\\Python\\MCB&quot;<br>file_names = [&#39;MCBGF.xlsx&#39;, &#39;MCBOF.xlsx&#39;, &#39;MCBYF.xlsx&#39;, &#39;MCBDEF.xlsx&#39;]<br>performance_names = [&#39;MCBGF&#39;, &#39;MCBOF&#39;, &#39;MCBYF&#39;, &#39;MCBDEF&#39;]<br><br># Read the first Excel file into a pandas DataFrame with the date column as the index (header = 5 since data only starts on the 5th row)<br>df = pd.read_excel(os.path.join(folder_path, file_names[0]), index_col=&#39;Ruling Date&#39;, header = 5)[[&#39;Performance Nav Dividend&#39;]]<br><br># Rename the performance column based on the corresponding name in the list<br>df = df.rename(columns={&#39;Performance Nav Dividend&#39;: performance_names[0]})<br><br># Loop through the remaining Excel files (it takes the MCBGF dataframe as reference and loop through to take MCBOF and MCBYF as next)<br>for i in range(1, len(file_names)):<br>    # Read the Excel file into a pandas DataFrame with the date column as the index<br>    temp_df = pd.read_excel(os.path.join(folder_path, file_names[i]), index_col=&#39;Ruling Date&#39;, header = 5, usecols=[&#39;Ruling Date&#39;, &#39;Performance Nav Dividend&#39;])<br>    <br>    # Rename the performance column based on the corresponding name in the list<br>    temp_df = temp_df.rename(columns={&#39;Performance Nav Dividend&#39;: performance_names[i]})<br>    # Append the performance column to the main DataFrame<br>    df = pd.concat([df, temp_df], axis=1)<br><br># Save the combined DataFrame to a new Excel file<br>#df = df.dropna(thresh=3) # for all dates that doesnt have 3 performance data points, it drops it to ensure consistency of data<br>df = df.drop(df.tail(9).index)<br>df.to_excel(os.path.join(folder_path,f&quot;Data.xlsx&quot;))<br><br># STEP II - VISUALIZING THE DAILY PRICE DATA<br>df.index = pd.to_datetime(df.index)<br><br>fig = plt.figure(figsize=(14,7))<br>ax = fig.add_subplot(111)<br># figsize: This is a tuple of two values that specifies the width and height of the figure in inches. <br># In this case, (14, 7) means that the width of the figure will be 14 inches and the height will be 7 inches.<br><br>for i in df.columns.values:<br>    plt.plot(df.index, df[i],lw=2, alpha=0.8,label=i)<br>    # plt.plot(df.index, df[i], lw=2, alpha=0.8,label=i)<br>    # df.index: This is the x-axis data for the line plot. It is a pandas series representing the index of the DataFrame df. Here it is the Ruling Date.<br>    # lw=2: This argument sets the line width to 2. lw stands for &quot;line width&quot;<br>    # alpha=0.8: This argument sets the transparency of the line to 0.8. alpha stands for &quot;alpha channel&quot; which controls transparency<br>    # label=i: This argument sets the label of the line to i. i is the name of the column in df that is being plotted. This label will be used to create a legend for the line plot.<br><br># since the axis is daily data for 10 years which makes it difficult to read the tickers, we are going to customize to show only every 2 years price data<br>ax.xaxis.set_major_locator(mdates.YearLocator(base=2))<br>ax.xaxis.set_major_formatter(mdates.DateFormatter(&#39;%Y&#39;))<br><br>plt.title(&quot;Daily Price Data&quot;)<br>plt.legend(loc=&#39;upper left&#39;, fontsize=12) # determine position and fontsize of legend which here is upper left<br>plt.ylabel(&#39;Index NAV (MUR)&#39;) # y-axis label</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yY2PveilpCEwrKcZeRxqpA.png" /></figure><pre># STEP III - VISUALIZING THE DAILY % RETURN DATA<br><br>#Plotting this using daily % change in return can help illustrate the stocks&#39; volatility.<br><br>returns = df.pct_change() #calculate the daily % return for each fund<br><br>fig = plt.figure(figsize=(14,7))<br>ax = fig.add_subplot(111)<br><br>for i in returns.columns.values:<br>    plt.plot(returns.index, returns[i], lw=2, alpha=0.8,label=i)<br><br>ax.xaxis.set_major_locator(mdates.YearLocator(base=2))<br>ax.xaxis.set_major_formatter(mdates.DateFormatter(&#39;%Y&#39;))<br><br>plt.title(&quot;Daily % Return Data&quot;)<br>plt.legend(loc=&#39;upper left&#39;, fontsize=12)<br>plt.ylabel(&#39;daily returns (%)&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HoIHplEtM5nukEAnqsLm1Q.png" /></figure><pre># STEP IV - DEFINING FORMULAS FOR SIMULATIONS<br><br>returns = df.pct_change() # computes the % daily returns based off the daily index price<br>mean_returns = returns.mean() # The mean() method in pandas DataFrame computes the mean of a set of variables.<br>cov_matrix = returns.cov() # The cov() method in pandas DataFrame computes the covariance matrix of a set of variables.<br>num_portfolios = 20000 # Number of portfolios to simulate<br>risk_free_rate = 0.0479 <br><br># Risk free rate (used for Sharpe ratio below) <br># anchored on treasury bond rates - The value for the risk-free rate is based off the weighted average yield of Mauritius 10YR Bond Auction as of 11 Oct 2022 (4.79%)<br><br># STEP V - DEFINING FUNCTIONS TO SIMULATE RANDOM PORTFOLIOS<br><br># Define function to calculate returns, volatility<br># The NYSE and NASDAQ average about 252 trading days a year (excludes holidays, weekends)<br><br>def portfolio_annualized_performance(weights, mean_returns, cov_matrix):<br><br>    # Return of portfolio<br>    returns = np.sum(mean_returns*weights) *252<br>    # mean_returns is a numpy array containing the mean expected returns for each asset in the portfolio, <br>    # while weights is a numpy array containing the portfolio weights for each asset. <br>    # The product of mean_returns and weights computes the expected return for each asset in the portfolio, <br>    # and then np.sum computes the sum of these expected returns to give the overall expected portfolio return.<br>    # Multiplying by 252 at the end converts the expected daily return to an expected annualized return, assuming 252 trading days in a year.<br><br>    # Standard deviation of portfolio<br>    std = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights))) * np.sqrt(252)<br>    # In the context of portfolio optimization, covariance refers to the way in which the returns of different assets in the portfolio tend to move together. <br>    # A positive covariance indicates that the returns of the assets tend to move in the same direction, while a negative covariance indicates that the returns tend to move in opposite directions.<br>    # The covariance of two assets is influenced not only by their own individual volatility (i.e., standard deviation), but also by the degree to which they are related <br>    # to each other. If two assets have a high positive covariance, their combined volatility in a portfolio will be higher than if they had a low or negative covariance.<br>    # The inner product np.dot(cov_matrix, weights) computes the weighted covariance matrix of the portfolio returns. <br>    # In other words, it takes into account not only the covariance between the returns of the assets, but also the degree to which each asset contributes to the overall portfolio return.<br>    # The outer product np.dot(weights.T, np.dot(cov_matrix, weights)) computes the variance of the portfolio returns.<br>    # The square root of the portfolio variance gives the expected volatility of the portfolio, <br>    # which is then annualized by multiplying by the square root of the number of trading days in a year (assuming 252 trading days in a year).<br>    <br>    return std, returns<br><br># STEP VI - GENERATING RANDOM PORTFOLIOS<br><br>def generate_random_portfolios(num_portfolios, mean_returns, cov_matrix, risk_free_rate):<br><br>    results = np.zeros((3,num_portfolios))<br>    # Initialize array of shape 3 x N to store our results<br>    # where N is the number of portfolios we&#39;re going to simulate<br>    # 3 rows: portfolio_std_dev, portfolio_return, and sharpe ratio<br>    # The array &quot;results&quot; has three rows and &quot;num_portfolios&quot; columns, all initialized to zero. <br>    # We will then use this array to store results or calculations for each portfolio in our analysis.<br><br>    weight_array = [] # Empty array to store the weights of each fund<br><br>    for i in range(num_portfolios):<br>        weights = np.random.random(4) # initializes a NumPy array called &quot;weights&quot; with four random weights (1 for each fund). Each time the code is ran, the numbers will be different because they are randomly generated.<br>        weights /= np.sum(weights) # Convert the randomized weights to percentages (summing to 100)<br>        weight_array.append(weights) # Add the generated random weights to the empty portfolio weight array/matrix above<br><br>        portfolio_std_dev, portfolio_return = portfolio_annualized_performance(weights, mean_returns, cov_matrix)<br>        # based off the random weights generated, it calls the portfolio annualized performance function and passes the weights to calculate the returns and std<br>        # it then returns the mean_returns (returns.mean()) and cov_matrix (returns.cov())<br><br>        results[0,i] = portfolio_std_dev<br>        results[1,i] = portfolio_return<br>        results[2,i] = (portfolio_return - risk_free_rate) / portfolio_std_dev # Sharpe ratio formula<br>        # In the above, the portfolio matrix is a 3 x N NumPy array where each column represents a different portfolio. <br>        # We then use the np.std function to calculate the standard deviation of each portfolio, resulting in a 1-dimensional NumPy array portfolio_std_devs with length N. <br>        # We then loop through each portfolio and store its standard deviation in the first row of the results array using the code results[0, i] = portfolio_std_devs[i]. <br>        # Once this loop is finished, the results array will contain the standard deviation of each of the N portfolios.<br><br>    return results, weight_array<br><br># STEP VII - RUNNING THE SIMULATIONS AND VISUALIZING THE DATA - OPTIMAL ALLOCATION<br><br>def display_simulated_portfolios(mean_returns, cov_matrix, num_portfolios, risk_free_rate):<br><br>    # pull results, weights from random portfolios<br>    results, weights = generate_random_portfolios(num_portfolios,mean_returns, cov_matrix, risk_free_rate)<br><br>    max_sharpe_idx = np.argmax(results[2])<br>    # pulls the max portfolio sharpe ratio (3rd element in results array from the generate_random_portfolios function)<br><br>    stdev_portfolio, returns_portfolio = results[0,max_sharpe_idx], results[1,max_sharpe_idx]<br>    # pulls the associated standard deviation, annualized return with respect to the the max Sharpe ratio<br><br>    max_sharpe_allocation = pd.DataFrame(weights[max_sharpe_idx],index=df.columns,columns=[&#39;allocation&#39;])<br>    max_sharpe_allocation.allocation = [round(i*100,2)for i in max_sharpe_allocation.allocation]<br>    max_sharpe_allocation = max_sharpe_allocation.T<br>    # pulls the allocation associated with max Sharpe ratio and put it in a panda dataframe<br>    # rounds each element of the allocation attribute of the max_sharpe_allocation object to two decimal places and multiplies it by 100.<br>    # The DataFrame had 1 row and as many columns as there were assets in the portfolio. The row represented the allocation percentages of each asset in the portfolio.<br>    # By transposing the DataFrame with the .T method, the rows and columns are swapped. <br>    # This means that max_sharpe_allocation now has one column and as many rows as there are assets in the portfolio. <br>    # Each row represents the allocation percentage of a single asset in the portfolio.<br><br>    print(&quot;-&quot;*100) # prints 100 times &quot;-&quot;<br>    print(&quot;Portfolio at maximum Sharpe Ratio\n&quot;) # leave a line after the print &quot;\n&quot;<br>    print(&quot;--Returns, volatility--\n&quot;)<br>    print(&quot;Annualized Return:&quot;, round(returns_portfolio,2)) # returns the return of the portfolio rounded to 2dp<br>    print(&quot;Annualized Volatility:&quot;, round(stdev_portfolio,2)) # returns the stdev of the portfolio rounded to 2dp<br><br>    print(&quot;\n&quot;)<br>    print(&quot;--Allocation at max Sharpe ratio--\n&quot;)<br>    print(max_sharpe_allocation)<br>    print(&quot;-&quot;*100)<br><br>    plt.figure(figsize=(14, 7))<br>    # figsize: This is a tuple of two values that specifies the width and height of the figure in inches. <br>    # In this case, (14, 7) means that the width of the figure will be 14 inches and the height will be 7 inches.<br>    <br>    plt.scatter(results[0,:],results[1,:],c=results[2,:], cmap=&#39;winter&#39;, marker=&#39;o&#39;, s=10, alpha=0.3)<br>    # The plt.scatter function is used to create a scatter plot of three arrays of data. <br>    # The first array (results[0,:]) specifies the values for the x-axis, the second array (results[1,:]) specifies the values for the y-axis, <br>    # and the third array (results[2,:]) specifies the values to use for coloring the markers.<br>    # The size of each marker/circle is set to 10 (s=10), and the transparency of each marker is set to 0.3 (alpha=0.3).<br>    # The c argument of the plt.scatter function specifies the array to use for coloring the markers. In this case, the results[2,:] array is being used. <br>    # The cmap argument specifies the colormap to use for mapping the values in results[2,:] to colors (sharp ratio values)<br>    # In this case, the &#39;winter&#39; colormap is being used, which maps lower values to blues and higher values to greens, yellows, and reds.<br>    # colourmaps directory can be found here: https://matplotlib.org/stable/tutorials/colors/colormaps.html<br>    # marker directory can be found here: https://matplotlib.org/stable/api/markers_api.html<br>    <br>    plt.colorbar()<br>    # In the context of the code you provided, plt.colorbar() is used to add a colorbar to the scatter plot created by plt.scatter(). <br>    # The colorbar will show the mapping between the values in the results[2,:] array and the colors used to plot the markers.<br>    <br>    plt.scatter(stdev_portfolio, returns_portfolio, marker=&#39;x&#39;,color=&#39;r&#39;,s=150, label=&#39;Max Sharpe ratio&#39;)<br>    # The color argument specifies the color of the marker. In this case, &#39;r&#39; is used to specify the color red.<br>    # The marker argument of the plt.scatter function specifies the marker to use for each data point in the scatter plot. In this case, red crosses (&#39;x&#39;) are being used.<br>    # The plt.scatter function is used to create a scatter plot of two arrays of data. <br>    # The first array (stdev_portfolio) specifies the values for the x-axis, while the second array (returns_portfolio) specifies the values for the y-axis.<br><br>    plt.title(&#39;Simulated portfolios illustrating efficient frontier&#39;) # graph title<br>    plt.xlabel(&#39;annualized volatility&#39;) # x-axis label<br>    plt.ylabel(&#39;annualized returns&#39;) # y-axis label<br>    plt.legend(labelspacing=1.2) # The labelspacing argument of the plt.legend function specifies the spacing between the labels in the legend<br><br>display_simulated_portfolios(mean_returns, cov_matrix, num_portfolios, risk_free_rate)</pre><p><strong>New Risk-Adjusted Portfolio Allocation</strong></p><pre>----------------------------------------------------------------------------------------------------<br>Portfolio at maximum Sharpe Ratio<br><br>--Returns, volatility--<br><br>Annualized Return: 0.07<br>Annualized Volatility: 0.03<br><br>--Allocation at max Sharpe ratio--<br><br>            MCBGF  MCBOF  MCBYF  MCBDEF<br>allocation  19.01   0.19  75.88    4.92<br>----------------------------------------------------------------------------------------------------</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tQlbMPbeN7xas-8knWS3kw.png" /></figure><p><strong>Resources:</strong></p><ul><li><a href="https://www.mcbcapitalmarkets.mu/en/funds-listing">Funds Listing</a></li><li><a href="https://www.mcb.mu/en/personal/marketupdates/mauritian-bond-markets">Mauritian Bond Markets</a></li><li><a href="https://openai.com/blog/chatgpt">Introducing ChatGPT</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=870bd1d7a9d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>