{
  "version": "https://jsonfeed.org/version/1",
  "title": "Quants on CafeIO",
  "icon": "https://micro.blog/akarsh/avatar.jpg",
  "home_page_url": "https://akarsh.micro.blog/",
  "feed_url": "https://akarsh.micro.blog/feed.json",
  "items": [
      {
        "id": "http://akarsh.micro.blog/2023/04/04/unlocking-the-secrets.html",
        "title": "Unlocking The Secrets of Algo Trading: Learn How to Use Python for Getting Data and Strategies…!!",
        "content_html": "<blockquote>\n<p>With Python&rsquo;s limitless libraries and tools, we can build a robust foundation to predict market trends, analyse financial data, and create advanced financial models.</p>\n</blockquote>\n<p>Hey there! In this post, I&rsquo;m going to talk about setting things up for algo trading. <a href=\"https://www.youtube.com/watch?v=uvby-fWe8Ts\">In my previous video</a>, I covered many aspects of algo trading, including technology, tools, markets, and data. I will build on top of that in this blog post. I would like to point out that this post is accompanied by a video which I shared before.</p>\n<blockquote>\n<p>You can watch the supplementary video and <a href=\"https://www.youtube.com/watch?v=vBBM_2fu15U\">Follow Along the Video</a>.</p>\n</blockquote>\n<h2 id=\"hardware--software-setup\">Hardware &amp; Software Setup</h2>\n<p>You don&rsquo;t need a fancy computer for this, anything online or a simple computer will work.</p>\n<ul>\n<li>8 GB of RAM with an i5 Processor. Something lower might work too.</li>\n<li>Apple Silicon (m1/m2) is great too if you can install the required dependencies. There are few libraries which do not work on it.</li>\n<li>Anaconda Environment with Python 3.7. Though higher version of python can be taken, however I have found this to be the common denominator which most libraries support.</li>\n<li>List of Libraries to Install\n<ul>\n<li>Pandas</li>\n<li>Numpy</li>\n<li>Matplotlib, Seaborn, Plotly</li>\n<li>yfinance</li>\n<li>Cufflinks</li>\n</ul>\n</li>\n<li><strong>Bonus</strong> : Just use Google Colab and install yfinance, Cufflinks in there and get started</li>\n</ul>\n<h2 id=\"heres-what-we-will-focus-on\">Here’s what we will focus on</h2>\n<p>We will be setting up a python environment, getting market data using Yahoo Finance, and doing some basic statistical analysis. We will then create a simple strategy and compare returns.</p>\n<ol>\n<li>Get market data from Yahoo Finance.</li>\n<li>Play with the data, get data from NSE, and do stats on it.</li>\n<li>Calculate moving averages and do plotting.</li>\n<li>Try to do something known as Bollinger bands, which is a technical indicator.</li>\n<li>Make a simple moving average-based strategy.</li>\n</ol>\n<h2 id=\"more-details\">More Details</h2>\n<p>After installing the libraries, we will use Yahoo Finance to get market data. We will define a variable ticker and set start and end dates. Then, we will download the data and create a data frame. We will also reduce the number of days to make it easier to plot.</p>\n<p>Next, we will plot the high, lows, and search for patterns. We will also calculate some basic formulas like simple moving average, exponential moving averages, and Bollinger bands. Bollinger bands is a plus-minus two standard deviations up and down from a simple moving average.</p>\n<p>Finally, we will make a simple moving average-based strategy. The strategy will be to sell if a condition is met and hold if it is not.</p>\n<blockquote>\n<p>The Complete Code is shared below</p>\n</blockquote>\n<ol>\n<li>Install necessary libraries.</li>\n<li>Define variable ticker and set start and end dates.</li>\n<li>Download data and create a data frame.</li>\n<li>Reduce the number of days to make it easier to plot.</li>\n<li>Plot high lows and search for patterns.</li>\n<li>Calculate basic formulas like simple moving average, exponential moving averages, and Bollinger bands.</li>\n</ol>\n<h2 id=\"working-with-a-strategy\">Working with a Strategy</h2>\n<p>In the world of algorithmic trading, having a well-defined strategy is crucial for success. A trading strategy is simply a set of rules that traders follow to generate signals that indicate when to buy, sell, or do nothing.</p>\n<p>One popular trading strategy is using the <strong>simple moving average (SMA)</strong>. The SMA is a technical indicator that helps traders identify trends in the market. It calculates the average price of a security over a specific time period, such as 12 days, by adding up the closing prices of each day and dividing it by the number of days in the period.</p>\n<p>When using the SMA, traders typically buy a stock when its closing price is higher than its simple moving average and sell it when the closing price is lower. This approach can help traders identify potential uptrends or downtrends in the market and make informed decisions on when to enter or exit a trade.</p>\n<p>However, it&rsquo;s important to note that no trading strategy is foolproof. <em>Market conditions can change rapidly, and unforeseen events can impact a stock&rsquo;s performance.</em> Therefore, it&rsquo;s essential to continually monitor the market and adjust trading strategies as needed.</p>\n<p>In addition to the SMA, there are many other technical indicators and trading strategies that traders can use to make informed decisions in the market. Some popular ones include the <strong>relative strength index (RSI)</strong>, the <strong>moving average convergence divergence (MACD)</strong>, and <strong>the Bollinger Bands</strong>.</p>\n<p>When studying financial engineering and data science, it&rsquo;s essential to clean up data to ensure that the calculations are accurate. This often involves dropping unnecessary columns and removing any errors or outliers that may skew the results.</p>\n<p>In summary, having a well-defined trading strategy is essential for success in algorithmic trading. The SMA is just one of many technical indicators and trading strategies that traders can use to make informed decisions in the market. However, it&rsquo;s important to continually monitor the market and adjust strategies as needed to stay ahead of the game.</p>\n<h2 id=\"complete-code\">Complete Code</h2>\n<pre><code>#pip install yfinance plotly cufflinks\n\n# Core Imports\nimport pandas as pd\nimport numpy as np\nimport datetime\nimport yfinance as yf\nimport matplotlib.pyplot as plt\n\n#Ticker is the stock that we want to get\nTicker = &quot;^NSEI&quot;\n\n\n# Get Sample data based on a Ticker\nend1 = datetime.date.today()\nstart1 = end1 - pd.Timedelta(days=5)\n\ndf = yf.download(Ticker, start=start1, end=end1, interval=&quot;5m&quot; )\nprint(df.head())\ndf.info()\n\n# Plotting the Data\n\ndf1a = df.copy()\ndf1a.loc['2023-02-13', ['Open', 'High', 'Low', 'Close']].plot(grid=True, linewidth=1, figsize=(14, 9))\n\n# Just the Closing Price\ndf1a['Close'].plot(grid=True, linewidth=1, figsize=(14, 9))\n\n# Core Calculation Functions \n# SMA\ndef get_sma(prices, rate):\n  return prices.rolling(rate).mean()\n\n# EMA\ndef get_ema(prices, rate):\n  return prices.ewm(span=ema, adjust=False).mean()\n\n# Bollinger Bands\n\n# Bollinger bands are a technical analysis tool used by traders to identify potential entry and exit points in the market. They are created by plotting a moving average of the price along with two standard deviation lines above and below it. By doing so, Bollinger bands can provide an indication of whether a stock is overbought or oversold. They also help traders identify potential breakouts or reversals in the market. With this knowledge, traders can make more informed decisions when entering or exiting a position in the market.\n\ndef get_bollinger_bands(prices,rate):\n    sma = get_sma(prices, rate)\n    std = prices.rolling(rate).std()\n    bollinger_up = sma + std * 2 # Calculate top band\n    bollinger_down = sma - std * 2 # Calculate bottom band\n    return bollinger_up, bollinger_down\n\n\n# Other Functions\n\ndef download_daily_data(ticker, start, end):\n    &quot;&quot;&quot; \n    The function downloads daily market data to a pandas DataFrame \n    using the 'yfinance' API between the dates specified.\n    &quot;&quot;&quot;\n    data = yf.download(ticker, start, end)\n    \n    return data\n\ndef compute_daily_returns(data):\n    &quot;&quot;&quot; \n    The function computes daily log returns based on the Close prices in the pandas DataFrame\n    and stores it in a column  called 'cc_returns'.\n    &quot;&quot;&quot;\n    data['cc_returns'] = np.log(data['Close'] / data['Close'].shift(1))\n    return data\n\n# Generate Bollinger bands for the above\n\nbollinger_up, bollinger_down = get_bollinger_bands(df1a['Close'],20)\n\n\n# Plot the Results\n\nsymbol = 'NSE'\nclosing_prices = df1a['Close']\n\nplt.title(symbol + ' Bollinger Bands')\nplt.xlabel('Days')\nplt.ylabel('Closing Prices')\nplt.plot(closing_prices, label='Closing Prices')\nplt.plot(bollinger_up, label='Bollinger Up', c='g')\nplt.plot(bollinger_down, label='Bollinger Down', c='r')\nplt.legend()\nplt.show()\n\n\n# Strategy Perform Calculations\n\n# Remove the Un-necessary Columns\ndf1a.drop(columns=['High', 'Low', 'Volume'], inplace=True)\n\n# Create a new colum which captures the percentage cahnge from previous day\ndf1a['cc_returns'] = df1a['Close'].pct_change()\n\n# Define a short 12 day sma \nsma = 12\ndf1a['sma'] = df1a['Close'].rolling(window=sma).mean()\n\nprint(df1a.head())\nprint(df1a.tail())\n\n# If the closging price is higher that sma buy else do nothing\ndf1a['position'] = np.where((df1a['Close'] &gt; df1a['sma']), 1, 0)\ndf1a['position'] = df1a['position'].shift(1)\ndf1a['position'].value_counts()\n\n# Plotting the above strategy returns\n\ndf1a['strategy_returns'] = df1a['cc_returns'] * df1a['position']\n\n\ndf1a['strategy_returns'] = 1 + df1a['strategy_returns']\ndf1a['cc_returns'] = 1 + df1a['cc_returns']\n\nprint(df1a.head())\nprint(df1a.tail())\n\ndf1a[['cc_returns', 'strategy_returns']].cumprod().plot(grid=True, figsize=(9, 5))\n\nprint('Buy and hold returns: ', np.round(df1a['cc_returns'].cumprod()[-1], 2))\nprint('Strategy returns: ', np.round(df1a['strategy_returns'].cumprod()[-1], 2))\nHyperWrite Logo\n</code></pre>\n",
        "date_published": "2023-04-04T09:00:00+05:30",
        "url": "https://akarsh.micro.blog/2023/04/04/unlocking-the-secrets.html",
        "tags": ["algotrading","Python","Quants","Financial Engineering"]
      }
  ]
}
