<rss version="2.0">
  <channel>
    <title>Python on CafeIO</title>
    <link>https://akarsh.micro.blog/categories/python/</link>
    <description></description>
    
    <language>en</language>
    
    <lastBuildDate>Sun, 09 Apr 2023 09:00:00 +0530</lastBuildDate>
    
    <item>
      <title>Deep Dive into Architecture Patterns, Part 2</title>
      <link>https://akarsh.micro.blog/2023/04/09/deep-dive-into.html</link>
      <pubDate>Sun, 09 Apr 2023 09:00:00 +0530</pubDate>
      
      <guid>http://akarsh.micro.blog/2023/04/09/deep-dive-into.html</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;Deep Dive into Architecture Patterns. This Post is focused on understanding different technology stacks and their usage.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;This might very well be tangential to the idea of patterns, but I feel it is significant to be aware of the different technology stacks and from the core idea of patterns.&lt;/p&gt;
&lt;p&gt;A technology stack refers to a set of technologies that are used together to create a software application or system. Different technology stacks are typically named after the key technologies that they include, such as the operating system, programming language, web server, and database.&lt;/p&gt;
&lt;h2 id=&#34;tech-stack-management&#34;&gt;Tech Stack Management&lt;/h2&gt;
&lt;h3 id=&#34;some-popular-technology-stacks&#34;&gt;Some Popular Technology Stacks&lt;/h3&gt;
&lt;p&gt;Here’s a high-level view on some popular technology choices that we are currently presented with.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;LAMP Stack :&lt;/strong&gt; &lt;em&gt;Linux&lt;/em&gt;: LAMP stack is based on the Linux operating system, which is an open-source operating system that is widely used for servers and desktops. &lt;em&gt;Apache&lt;/em&gt;: Apache is a free, open-source web server software that is used to deliver web content over the internet. &lt;em&gt;MySQL&lt;/em&gt;: MySQL is a popular open-source relational database management system (RDBMS) that is used to store and retrieve data. &lt;em&gt;PHP&lt;/em&gt;: PHP is a popular open-source server-side scripting language that is used to create dynamic web pages and web applications.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;MEAN Stack :&lt;/strong&gt; &lt;em&gt;MongoDB&lt;/em&gt;: MongoDB is a NoSQL document-oriented database that is used to store data in a flexible, JSON-like format. &lt;em&gt;Express.js&lt;/em&gt;: Express.js is a lightweight web application framework that is used to build web applications and APIs in Node.js. &lt;em&gt;AngularJS&lt;/em&gt;: AngularJS is a JavaScript-based front-end web application framework that is used to build dynamic and responsive user interfaces. &lt;em&gt;Node.js&lt;/em&gt;: Node.js is a server-side JavaScript runtime environment that is used to run JavaScript on the server-side.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;MERN Stack :&lt;/strong&gt; &lt;em&gt;MongoDB&lt;/em&gt;: Same as MEAN stack, MongoDB is used as the database in MERN stack.&lt;em&gt;Express.js:&lt;/em&gt; Same as MEAN stack, Express.js is used as the server-side framework.&lt;em&gt;React.js&lt;/em&gt;: React.js is a popular front-end JavaScript library that is used to build user interfaces.&lt;em&gt;Node.js&lt;/em&gt;: Same as MEAN stack, Node.js is used as the server-side runtime environment.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;MERN with Next.js Stack :&lt;/strong&gt; &lt;em&gt;MongoDB&lt;/em&gt;: Same as MERN stack, MongoDB is used as the database in this stack.&lt;em&gt;Express.js&lt;/em&gt;: Same as MERN stack, Express.js is used as the server-side framework.&lt;em&gt;React.js&lt;/em&gt;: Same as MERN stack, React.js is used as the front-end JavaScript library. &lt;em&gt;Node.js&lt;/em&gt;: Same as the MERN stack, Node.js is used as the server-side runtime environment.&lt;em&gt;Next.js:&lt;/em&gt; Next.js is a popular React-based framework that is used to build server-side rendered web applications.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;.NET Stack :&lt;/strong&gt; &lt;em&gt;.NET Framework or .NET Core:&lt;/em&gt; .NET Framework is a free, open-source development platform for building Windows-based desktop and web applications. .NET Core is a newer version of the framework that is designed to be cross-platform.&lt;em&gt;C#:&lt;/em&gt; C# is a modern, object-oriented programming language that is used to develop applications on the .NET platform. &lt;em&gt;Visual Studio IDE:&lt;/em&gt; Visual Studio is an integrated development environment (IDE) that is used to develop, test, and deploy .NET applications.&lt;em&gt;SQL Server:&lt;/em&gt; SQL Server is a popular relational database management system (RDBMS) developed by Microsoft.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Python Flask Stack :&lt;/strong&gt; Python: &lt;em&gt;Python&lt;/em&gt; is a high-level programming language that is used for web development, data analysis, and artificial intelligence. &lt;em&gt;Flask&lt;/em&gt;: Flask is a lightweight web application framework that is used to build web applications and APIs in Python. &lt;em&gt;PostgreSQL&lt;/em&gt;: PostgreSQL is a popular open-source relational database management system (RDBMS) that is used to store and retrieve data.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Django Stack :&lt;/strong&gt; &lt;em&gt;Django&lt;/em&gt;: Django is a high-level Python web framework that is used to build web applications and APIs quickly and efficiently. &lt;em&gt;PostgreSQL&lt;/em&gt;: PostgreSQL is a popular open-source relational database management system (RDBMS) that is used to store and retrieve data. &lt;em&gt;Nginx&lt;/em&gt;: Nginx is a high-performance web server that is used to deliver web content over the internet.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Java Stack :&lt;/strong&gt; &lt;em&gt;Java&lt;/em&gt;: Java is a widely used programming language that is used to develop a wide range of applications, from desktop and mobile apps to web and enterprise applications.&lt;em&gt;Spring Framework&lt;/em&gt;: Spring is a popular open-source framework that is used to build web applications and enterprise-level software systems. &lt;em&gt;Hibernate&lt;/em&gt;: Hibernate is an object-relational mapping (ORM) framework that is used to manage database operations in Java-based applications. &lt;em&gt;Apache Tomcat&lt;/em&gt;: Apache Tomcat is a popular open-source web server and servlet container that is used to deploy and run Java-based web applications.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Serverless Stack :&lt;/strong&gt; &lt;em&gt;AWS Lambda or Azure Functions&lt;/em&gt;: Serverless stack is a technology stack that doesn&amp;rsquo;t require any server management or infrastructure. AWS Lambda and Azure Functions are popular serverless computing services offered by Amazon Web Services and Microsoft Azure, respectively._ Amazon S3 or Azure Blob Storage_: Amazon S3 and Azure Blob Storage are popular object storage services that can be used to store and retrieve data in a serverless environment._ Amazon API Gateway or Azure API Management:_ Amazon API Gateway and Azure API Management are popular API gateway services that can be used to manage and secure APIs in a serverless environment.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id=&#34;factors-to-keep-in-mind-before-selecting-tech-stack&#34;&gt;Factors to keep in mind before selecting Tech Stack&lt;/h3&gt;
&lt;p&gt;When selecting a technology stack, there are several factors that need to be considered. Here are some key factors that should be kept in mind:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;em&gt;&lt;strong&gt;Project requirements&lt;/strong&gt;&lt;/em&gt;: Consider the requirements of the project, including the type of application, the features it needs to support, and the expected usage. The technology stack should be able to support these requirements and provide the necessary functionality.&lt;/li&gt;
&lt;li&gt;&lt;em&gt;&lt;strong&gt;Scalability&lt;/strong&gt;&lt;/em&gt;: Consider the scalability requirements of the project, including the expected growth of the application over time. The technology stack should be able to scale to meet the demands of the application without sacrificing performance.&lt;/li&gt;
&lt;li&gt;&lt;em&gt;&lt;strong&gt;Cost&lt;/strong&gt;&lt;/em&gt;: Consider the budget for the project and the cost of the technology stack. Some technology stacks may require more expensive hardware or licensing fees, while others may be more cost-effective.&lt;/li&gt;
&lt;li&gt;&lt;em&gt;&lt;strong&gt;Development resources&lt;/strong&gt;&lt;/em&gt;: Consider the skillset and experience of the development team. The technology stack should align with the team&amp;rsquo;s expertise to ensure efficient development and maintenance.&lt;/li&gt;
&lt;li&gt;&lt;em&gt;&lt;strong&gt;Community support&lt;/strong&gt;&lt;/em&gt;: Consider the level of community support for the technology stack. A strong community can provide valuable resources, tools, and support for developers, as well as ensure the longevity and sustainability of the technology.&lt;/li&gt;
&lt;li&gt;&lt;em&gt;&lt;strong&gt;Integration&lt;/strong&gt;&lt;/em&gt;: Consider the integration requirements of the project. The technology stack should be able to integrate with other systems and tools as needed.&lt;/li&gt;
&lt;li&gt;&lt;em&gt;&lt;strong&gt;Security&lt;/strong&gt;&lt;/em&gt;: Consider the security requirements of the project, including data privacy, regulatory compliance, and potential vulnerabilities. The technology stack should provide robust security features and be regularly updated to address new security threats.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Overall, it is important to carefully evaluate the specific requirements and constraints of the project to select the most appropriate technology stack.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Some popular technology stacks mentioned are LAMP, MEAN, MERN, MERN with Next.js, .NET, Python Flask, Django, Java, and Serverless stack. Factors to consider when choosing a technology stack include project requirements, scalability, cost, and development resources.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2 id=&#34;deployment-patterns&#34;&gt;Deployment Patterns&lt;/h2&gt;
&lt;h3 id=&#34;deployment-approaches&#34;&gt;Deployment Approaches&lt;/h3&gt;
&lt;p&gt;The deployment options available for a technology stack depend on the specific components of the stack and the requirements of the project. However, here are some common deployment options that are available for most technology stacks:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;On-premises deployment:&lt;/strong&gt; This is a traditional deployment method where the application is deployed on hardware that is located on-site or within the organization&amp;rsquo;s premises. This deployment method requires the organization to manage the hardware, software, and security of the application.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Virtual machines (VM) deployment:&lt;/strong&gt; In this deployment method, the application is deployed on a virtual machine that is hosted on a public cloud or private infrastructure. This method provides greater flexibility than on-premises deployment and allows the organization to scale resources up or down as needed.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Container deployment:&lt;/strong&gt; Container deployment involves deploying the application in a container, such as Docker, which encapsulates the application and its dependencies. This method provides greater portability, as the container can be deployed on any infrastructure that supports the container runtime.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Serverless deployment:&lt;/strong&gt; In a serverless deployment, the application is deployed as a set of functions that run in a serverless computing environment, such as AWS Lambda or Azure Functions. This deployment method eliminates the need to manage the underlying infrastructure and provides greater scalability.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Platform as a Service (PaaS) deployment:&lt;/strong&gt; PaaS deployment involves deploying the application on a cloud-based platform, such as Google App Engine, Heroku, or Microsoft Azure App Service. The platform manages the underlying infrastructure and provides developers with a pre-configured environment for deploying and running their applications.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Infrastructure as a Service (IaaS) deployment:&lt;/strong&gt; IaaS deployment involves deploying the application on a cloud-based infrastructure, such as Amazon Web Services (AWS) or Microsoft Azure. This deployment method provides organizations with greater control over the underlying infrastructure and allows them to customize the environment to meet their specific requirements.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id=&#34;factors-influencing-deployment-strategies&#34;&gt;Factors Influencing Deployment Strategies&lt;/h3&gt;
&lt;p&gt;When selecting a deployment method for a technology stack, there are several factors that should be considered. Here are some key choices that should be made:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;em&gt;&lt;strong&gt;Scalability&lt;/strong&gt;&lt;/em&gt;: Consider the expected traffic and usage of the application. If the application is expected to experience high levels of traffic or usage, a scalable deployment method such as serverless or container deployment may be more appropriate.&lt;/li&gt;
&lt;li&gt;&lt;em&gt;&lt;strong&gt;Cost&lt;/strong&gt;&lt;/em&gt;: Consider the budget for the project and the cost of the deployment method. For example, on-premises deployment may be more cost-effective for small projects, while cloud-based deployment may be more cost-effective for larger projects.&lt;/li&gt;
&lt;li&gt;&lt;em&gt;&lt;strong&gt;Flexibility&lt;/strong&gt;&lt;/em&gt;: Consider the level of flexibility required for the project. For example, if the application needs to be deployed in different environments, a container or serverless deployment may be more appropriate.&lt;/li&gt;
&lt;li&gt;&lt;em&gt;&lt;strong&gt;Maintenance&lt;/strong&gt;&lt;/em&gt;: Consider the level of maintenance required for the deployment method. For example, on-premises deployment may require more maintenance than cloud-based deployment, which is managed by the cloud provider.&lt;/li&gt;
&lt;li&gt;&lt;em&gt;&lt;strong&gt;Security&lt;/strong&gt;&lt;/em&gt;: Consider the security requirements for the project. For example, if the application handles sensitive data, a cloud-based deployment method may require additional security measures to ensure the data is protected.&lt;/li&gt;
&lt;li&gt;&lt;em&gt;&lt;strong&gt;Integration&lt;/strong&gt;&lt;/em&gt;: Consider the integration requirements for the project. For example, if the application needs to integrate with other systems, a platform as a service (PaaS) deployment method may be more appropriate, as it provides pre-configured environments for deploying and running applications.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Overall, it is important to carefully evaluate the specific requirements and constraints of the project to select the most appropriate deployment method for the technology stack.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The section discusses different deployment approaches available for technology stacks, including on-premises, virtual machines, container, serverless, PaaS, and IaaS deployment. It also highlights the factors that should be considered when selecting a deployment method, such as scalability, cost, flexibility, maintenance, security, and integration requirements. The selection of the deployment method should depend on the specific requirements and constraints of the project.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2 id=&#34;summary&#34;&gt;Summary&lt;/h2&gt;
&lt;p&gt;In summary, we discussed the popular technology stacks such as LAMP, MEAN, MERN, MERN with Next.js, .NET, Python Flask, Django, Java, and Serverless stack. When choosing a technology stack, it is important to consider project requirements, scalability, cost, and development resources.&lt;/p&gt;
&lt;p&gt;Deployment approaches are also important when it comes to technology stacks. There are several deployment methods available, including on-premises, virtual machines, container, serverless, PaaS, and IaaS deployment. Each deployment method has its own advantages and disadvantages. For example, serverless deployment eliminates the need to manage underlying infrastructure and provides greater scalability. The selection of the deployment method should depend on the specific requirements and constraints of the project. When selecting a deployment method, scalability, cost, flexibility, maintenance, security, and integration requirements should be considered.&lt;/p&gt;
&lt;p&gt;In summary, the selection of the technology stack and deployment method should depend on the specific requirements and constraints of the project. It is important to carefully evaluate the project&amp;rsquo;s needs and select the appropriate technology stack and deployment method. By doing so, you can ensure that the project is successful and meets its goals&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Unlocking The Secrets of Algo Trading: Learn How to Use Python for Getting Data and Strategies…!!</title>
      <link>https://akarsh.micro.blog/2023/04/04/unlocking-the-secrets.html</link>
      <pubDate>Tue, 04 Apr 2023 09:00:00 +0530</pubDate>
      
      <guid>http://akarsh.micro.blog/2023/04/04/unlocking-the-secrets.html</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;With Python&amp;rsquo;s limitless libraries and tools, we can build a robust foundation to predict market trends, analyse financial data, and create advanced financial models.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Hey there! In this post, I&amp;rsquo;m going to talk about setting things up for algo trading. &lt;a href=&#34;https://www.youtube.com/watch?v=uvby-fWe8Ts&#34;&gt;In my previous video&lt;/a&gt;, 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.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;You can watch the supplementary video and &lt;a href=&#34;https://www.youtube.com/watch?v=vBBM_2fu15U&#34;&gt;Follow Along the Video&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2 id=&#34;hardware--software-setup&#34;&gt;Hardware &amp;amp; Software Setup&lt;/h2&gt;
&lt;p&gt;You don&amp;rsquo;t need a fancy computer for this, anything online or a simple computer will work.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;8 GB of RAM with an i5 Processor. Something lower might work too.&lt;/li&gt;
&lt;li&gt;Apple Silicon (m1/m2) is great too if you can install the required dependencies. There are few libraries which do not work on it.&lt;/li&gt;
&lt;li&gt;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.&lt;/li&gt;
&lt;li&gt;List of Libraries to Install
&lt;ul&gt;
&lt;li&gt;Pandas&lt;/li&gt;
&lt;li&gt;Numpy&lt;/li&gt;
&lt;li&gt;Matplotlib, Seaborn, Plotly&lt;/li&gt;
&lt;li&gt;yfinance&lt;/li&gt;
&lt;li&gt;Cufflinks&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Bonus&lt;/strong&gt; : Just use Google Colab and install yfinance, Cufflinks in there and get started&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&#34;heres-what-we-will-focus-on&#34;&gt;Here’s what we will focus on&lt;/h2&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Get market data from Yahoo Finance.&lt;/li&gt;
&lt;li&gt;Play with the data, get data from NSE, and do stats on it.&lt;/li&gt;
&lt;li&gt;Calculate moving averages and do plotting.&lt;/li&gt;
&lt;li&gt;Try to do something known as Bollinger bands, which is a technical indicator.&lt;/li&gt;
&lt;li&gt;Make a simple moving average-based strategy.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id=&#34;more-details&#34;&gt;More Details&lt;/h2&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The Complete Code is shared below&lt;/p&gt;
&lt;/blockquote&gt;
&lt;ol&gt;
&lt;li&gt;Install necessary libraries.&lt;/li&gt;
&lt;li&gt;Define variable ticker and set start and end dates.&lt;/li&gt;
&lt;li&gt;Download data and create a data frame.&lt;/li&gt;
&lt;li&gt;Reduce the number of days to make it easier to plot.&lt;/li&gt;
&lt;li&gt;Plot high lows and search for patterns.&lt;/li&gt;
&lt;li&gt;Calculate basic formulas like simple moving average, exponential moving averages, and Bollinger bands.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id=&#34;working-with-a-strategy&#34;&gt;Working with a Strategy&lt;/h2&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;p&gt;One popular trading strategy is using the &lt;strong&gt;simple moving average (SMA)&lt;/strong&gt;. 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.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;p&gt;However, it&amp;rsquo;s important to note that no trading strategy is foolproof. &lt;em&gt;Market conditions can change rapidly, and unforeseen events can impact a stock&amp;rsquo;s performance.&lt;/em&gt; Therefore, it&amp;rsquo;s essential to continually monitor the market and adjust trading strategies as needed.&lt;/p&gt;
&lt;p&gt;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 &lt;strong&gt;relative strength index (RSI)&lt;/strong&gt;, the &lt;strong&gt;moving average convergence divergence (MACD)&lt;/strong&gt;, and &lt;strong&gt;the Bollinger Bands&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;When studying financial engineering and data science, it&amp;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.&lt;/p&gt;
&lt;p&gt;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&amp;rsquo;s important to continually monitor the market and adjust strategies as needed to stay ahead of the game.&lt;/p&gt;
&lt;h2 id=&#34;complete-code&#34;&gt;Complete Code&lt;/h2&gt;
&lt;pre&gt;&lt;code&gt;#pip install yfinance plotly cufflinks

# Core Imports
import pandas as pd
import numpy as np
import datetime
import yfinance as yf
import matplotlib.pyplot as plt

#Ticker is the stock that we want to get
Ticker = &amp;quot;^NSEI&amp;quot;


# Get Sample data based on a Ticker
end1 = datetime.date.today()
start1 = end1 - pd.Timedelta(days=5)

df = yf.download(Ticker, start=start1, end=end1, interval=&amp;quot;5m&amp;quot; )
print(df.head())
df.info()

# Plotting the Data

df1a = df.copy()
df1a.loc[&#39;2023-02-13&#39;, [&#39;Open&#39;, &#39;High&#39;, &#39;Low&#39;, &#39;Close&#39;]].plot(grid=True, linewidth=1, figsize=(14, 9))

# Just the Closing Price
df1a[&#39;Close&#39;].plot(grid=True, linewidth=1, figsize=(14, 9))

# Core Calculation Functions 
# SMA
def get_sma(prices, rate):
  return prices.rolling(rate).mean()

# EMA
def get_ema(prices, rate):
  return prices.ewm(span=ema, adjust=False).mean()

# Bollinger Bands

# 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.

def get_bollinger_bands(prices,rate):
    sma = get_sma(prices, rate)
    std = prices.rolling(rate).std()
    bollinger_up = sma + std * 2 # Calculate top band
    bollinger_down = sma - std * 2 # Calculate bottom band
    return bollinger_up, bollinger_down


# Other Functions

def download_daily_data(ticker, start, end):
    &amp;quot;&amp;quot;&amp;quot; 
    The function downloads daily market data to a pandas DataFrame 
    using the &#39;yfinance&#39; API between the dates specified.
    &amp;quot;&amp;quot;&amp;quot;
    data = yf.download(ticker, start, end)
    
    return data

def compute_daily_returns(data):
    &amp;quot;&amp;quot;&amp;quot; 
    The function computes daily log returns based on the Close prices in the pandas DataFrame
    and stores it in a column  called &#39;cc_returns&#39;.
    &amp;quot;&amp;quot;&amp;quot;
    data[&#39;cc_returns&#39;] = np.log(data[&#39;Close&#39;] / data[&#39;Close&#39;].shift(1))
    return data

# Generate Bollinger bands for the above

bollinger_up, bollinger_down = get_bollinger_bands(df1a[&#39;Close&#39;],20)


# Plot the Results

symbol = &#39;NSE&#39;
closing_prices = df1a[&#39;Close&#39;]

plt.title(symbol + &#39; Bollinger Bands&#39;)
plt.xlabel(&#39;Days&#39;)
plt.ylabel(&#39;Closing Prices&#39;)
plt.plot(closing_prices, label=&#39;Closing Prices&#39;)
plt.plot(bollinger_up, label=&#39;Bollinger Up&#39;, c=&#39;g&#39;)
plt.plot(bollinger_down, label=&#39;Bollinger Down&#39;, c=&#39;r&#39;)
plt.legend()
plt.show()


# Strategy Perform Calculations

# Remove the Un-necessary Columns
df1a.drop(columns=[&#39;High&#39;, &#39;Low&#39;, &#39;Volume&#39;], inplace=True)

# Create a new colum which captures the percentage cahnge from previous day
df1a[&#39;cc_returns&#39;] = df1a[&#39;Close&#39;].pct_change()

# Define a short 12 day sma 
sma = 12
df1a[&#39;sma&#39;] = df1a[&#39;Close&#39;].rolling(window=sma).mean()

print(df1a.head())
print(df1a.tail())

# If the closging price is higher that sma buy else do nothing
df1a[&#39;position&#39;] = np.where((df1a[&#39;Close&#39;] &amp;gt; df1a[&#39;sma&#39;]), 1, 0)
df1a[&#39;position&#39;] = df1a[&#39;position&#39;].shift(1)
df1a[&#39;position&#39;].value_counts()

# Plotting the above strategy returns

df1a[&#39;strategy_returns&#39;] = df1a[&#39;cc_returns&#39;] * df1a[&#39;position&#39;]


df1a[&#39;strategy_returns&#39;] = 1 + df1a[&#39;strategy_returns&#39;]
df1a[&#39;cc_returns&#39;] = 1 + df1a[&#39;cc_returns&#39;]

print(df1a.head())
print(df1a.tail())

df1a[[&#39;cc_returns&#39;, &#39;strategy_returns&#39;]].cumprod().plot(grid=True, figsize=(9, 5))

print(&#39;Buy and hold returns: &#39;, np.round(df1a[&#39;cc_returns&#39;].cumprod()[-1], 2))
print(&#39;Strategy returns: &#39;, np.round(df1a[&#39;strategy_returns&#39;].cumprod()[-1], 2))
HyperWrite Logo
&lt;/code&gt;&lt;/pre&gt;
</description>
    </item>
    
  </channel>
</rss>