<?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 Akhilesh Gogikar on Medium]]></title>
        <description><![CDATA[Stories by Akhilesh Gogikar on Medium]]></description>
        <link>https://medium.com/@akhileshgogikar?source=rss-f929c2f8eaaa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*y2BabiViR00a__qpOMMxsw.jpeg</url>
            <title>Stories by Akhilesh Gogikar on Medium</title>
            <link>https://medium.com/@akhileshgogikar?source=rss-f929c2f8eaaa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 11:14:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@akhileshgogikar/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[The Evolution of Human Intelligence, Anthropological Growth, and the Economics of Existence: A…]]></title>
            <link>https://medium.com/@akhileshgogikar/the-evolution-of-human-intelligence-anthropological-growth-and-the-economics-of-existence-a-57a46e8bca74?source=rss-f929c2f8eaaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/57a46e8bca74</guid>
            <dc:creator><![CDATA[Akhilesh Gogikar]]></dc:creator>
            <pubDate>Mon, 07 Aug 2023 23:08:39 GMT</pubDate>
            <atom:updated>2023-08-07T23:08:39.931Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Evolution of Human Intelligence, Anthropological Growth, and the Economics of Existence: A Comprehensive Exploration</h3><h3>Introduction</h3><p>Human evolution is a captivating journey, tracing the footsteps of our ancestors from the primal forests to the bustling metropolises of today. This evolution is not just physical but also intellectual, marked by the growth of our cognitive abilities, societal structures, and economic systems. As we stand at the crossroads of biology and technology, understanding our past becomes paramount. It offers insights into our future, guiding us through the challenges and opportunities that lie ahead.</p><h3>1. The Genesis of Human Intelligence</h3><p>Early Hominids and Cognitive Beginnings: The first glimmers of intelligence emerged with early hominids like <em>Australopithecus</em>. These beings, while primitive, showcased rudimentary problem-solving abilities, primarily driven by survival needs. Environmental pressures, such as changing climates and predator threats, played a pivotal role in shaping these cognitive abilities. Adaptation became the key, and with it, the seeds of intelligence were sown.</p><p>Brain Evolution and the Expansion of Consciousness: The human brain’s evolution is a marvel. From the compact brains of early hominids to the intricate neural networks of modern humans, this growth has been exponential. This expansion facilitated the development of language, enabling communication and the sharing of ideas. Abstract thinking allowed early humans to plan, innovate, and create, while enhanced problem-solving abilities helped them navigate the challenges of their environment.</p><p>The Role of Societal Interactions: Living in communities offered early humans numerous advantages, from shared resources to collective defense. These societal interactions were crucibles for cognitive growth. As communities grew, so did the need for organization, leading to the emergence of collective knowledge, shared learning, and cultural norms.</p><h3>2. Anthropological Milestones and Societal Evolution</h3><p>From Nomads to Settlers: The Neolithic Revolution marked a significant anthropological transition. Humans, once nomadic hunters and gatherers, began to settle, cultivating land and domesticating animals. This shift brought both challenges, like defending settlements, and opportunities, such as the growth of larger communities and the birth of civilization.</p><p>The Birth and Growth of Civilizations: Civilizations like Mesopotamia, Egypt, and the Indus Valley became the epicenters of human knowledge and culture. These early civilizations developed writing systems, facilitating record-keeping and communication. Art and architecture flourished, reflecting the values, beliefs, and aspirations of these societies. Hierarchies emerged, leading to organized governance and societal structures.</p><p>Cultural Exchanges and the Global Melting Pot: Trade routes, like the Silk Road, facilitated more than just the exchange of goods. They became conduits for cultural exchange, spreading ideas, technologies, and beliefs. This synthesis of diverse cultures enriched societies, leading to advancements in science, art, and philosophy.</p><h3>3. Economics: From Basic Trade to Complex Systems</h3><p>The Early Days of Trade: Trade has been an integral part of human societies since time immemorial. Early humans engaged in simple barter systems, exchanging goods based on mutual needs. However, as societies grew, the limitations of the barter system became evident. This led to the emergence of standardized currencies, facilitating trade and commerce.</p><p>Industrial Revolution: A Paradigm Shift: The 18th and 19th centuries witnessed a seismic shift in the global economic landscape. The Industrial Revolution, marked by the advent of machines, transformed economies. Urbanization became the norm, with people flocking to cities in search of opportunities. However, this rapid growth brought challenges, from labor rights issues to environmental concerns.</p><p>The Digital Age and the New Economic Landscape: The digital revolution has reshaped the global economy. The rise of the internet, e-commerce, and digital services has democratized access to information and opportunities. Traditional businesses have had to adapt, while new economic models, like the gig economy, have emerged.</p><h3>4. The AI Era: Challenges and Opportunities</h3><p>The Unprecedented Rise of AI: AI is no longer the stuff of science fiction. It’s here, transforming industries and societies. From healthcare to finance, AI’s integration is revolutionizing sectors, offering efficiency and precision. However, this transformative potential comes with challenges, especially concerning job displacement and the redefinition of work.</p><p>Redefining Human Value in the Age of Machines: As machines take on tasks once deemed exclusively human, existential questions arise. What is the value of human labor in an AI-driven world? Can a symbiotic relationship emerge where humans and machines coexist, complementing each other’s strengths?</p><h3>5. The Future: A Synthesis of Biology and Technology</h3><p>Transhumanism: The Next Frontier: The boundaries between biology and technology are blurring. Concepts like neural interfaces and biohacking are becoming mainstream, offering the potential to enhance human capabilities. However, this fusion of biology and technology brings ethical challenges, from concerns about privacy to the very definition of what it means to be human.</p><p>Navigating the Ethical Landscape: In this brave new world, ethical considerations are paramount. The unchecked growth of technology, especially in areas like AI and biotechnology, can have profound societal implications. It’s crucial to navigate this landscape with caution, ensuring that advancements benefit humanity as a whole.</p><h3>Conclusion</h3><p>The journey of human evolution, from early hominids to the digital denizens of today, is a testament to our adaptability and resilience. As we stand on the cusp of a new era, marked by the fusion of biology and technology, it’s essential to reflect on our past. Understanding our evolutionary journey, the growth of societies, and the evolution of economic systems offers insights into the challenges and opportunities that lie ahead. In this rapidly changing world, the essence of being human will be our guiding light, helping us navigate the complexities of the future with wisdom and empathy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57a46e8bca74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Being Human Amidst Ubiquitous AI: An Anthropological Odyssey]]></title>
            <link>https://medium.com/@akhileshgogikar/being-human-amidst-ubiquitous-ai-an-anthropological-odyssey-279bb81208ea?source=rss-f929c2f8eaaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/279bb81208ea</guid>
            <category><![CDATA[economics]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[anthropology]]></category>
            <category><![CDATA[leadership]]></category>
            <category><![CDATA[business]]></category>
            <dc:creator><![CDATA[Akhilesh Gogikar]]></dc:creator>
            <pubDate>Fri, 04 Aug 2023 21:48:43 GMT</pubDate>
            <atom:updated>2023-08-04T21:48:43.172Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uw_ru-sJoFes6OT9GxNoJg.png" /></figure><p>In the vast tapestry of human evolution, each epoch has been marked by defining challenges and transformations. Today, as we stand at the crossroads of a world dominated by artificial intelligence (AI), we are compelled to introspect: What does it mean to be human in an age where machines not only think but also learn, evolve, and sometimes even outpace us?</p><h4>The AI Conundrum: More than Just Machines</h4><p>The articles and evidence reviewed, from Stanford GSB Insights to the nuanced distinctions between weak and strong AI, underscore a profound shift. AI is not merely a tool; it’s a mirror reflecting our aspirations, fears, and the very essence of our humanity. As machines begin to emulate human cognition, we’re faced with an existential question: If our unique selling proposition is no longer our intelligence, then what is it?</p><h4>The Discomfort of Our ‘Monkey Brains’</h4><p>Our primal instincts, often referred to as our ‘monkey brains’, evolved in an era of scarcity. They drove us to compete, hoard, and prioritize short-term gains. But in a world where AI promises abundance, these very instincts might become our Achilles’ heel. The discomfort isn’t just about job displacement or an identity crisis; it’s about a fundamental mismatch between our evolutionary programming and the new world order.</p><h4>The Shift in Value Systems</h4><p>Historically, human societies have valued scarcity. Gold, a rare metal, became a standard of wealth. Unique skills and talents were rewarded. But in an AI-driven world, what’s rare is no longer physical but intangible. Empathy, creativity, the human touch — these might become the new gold standards. The incentive mechanisms that drove us — competition, rewards, recognition — might need a complete overhaul. In a world of abundance, collaboration might outweigh competition, and shared success might become more valuable than individual triumphs.</p><h4>The Anthropological Implications</h4><p>From an anthropological lens, the rise of AI is more than just a technological shift; it’s a cultural metamorphosis:</p><ol><li>Redefining Success: In a world where machines can outthink us, success might no longer be about intelligence or even innovation. It might be about wisdom, ethical choices, and the ability to connect and collaborate.</li><li>New Social Hierarchies: The social structures might undergo a seismic shift. The elites of the future might not be those who control AI but those who understand the human essence, those who can bridge the gap between man and machine.</li><li>Cultural Narratives: Our stories, myths, and cultural narratives might evolve. If ancient civilizations had gods of fire and wind, we might have legends of AI, tales that help us make sense of our place in this new world.</li></ol><h4>Conclusion</h4><p>Being human in a world of ubiquitous AI is both a challenge and an opportunity. It’s a journey of self-discovery, of redefining our place in the cosmos. While the road ahead is fraught with uncertainties, one thing is clear: the definition of being human is evolving. And as we navigate this new era, our greatest strength might be our ability to adapt, to embrace change, and to find our purpose in a world where machines can think but only humans can feel.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=279bb81208ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Applied RL: Customized Deep Reinforcement Learning for Algorithmic Trading]]></title>
            <link>https://medium.com/@akhileshgogikar/custom-deep-rl-for-algo-trading-106b1a2daa16?source=rss-f929c2f8eaaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/106b1a2daa16</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Akhilesh Gogikar]]></dc:creator>
            <pubDate>Mon, 06 Jun 2022 17:43:39 GMT</pubDate>
            <atom:updated>2022-06-06T18:09:06.764Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*hMy40cJgfwl3Ixk06DENIw.jpeg" /></figure><p><strong>TLDR: I show how to design a multi-stock portfolio optimization/trading environment in OpenAI’s Gym environment then I show how to write a custom policy and neural network architecture for the learning agent.</strong></p><p>To the uninitiated, reinforcement learning is a field of AI that mimics the learning process of the animal mind — a policy that leads to rewards/treats is a good policy to live by. The idea is that the AI algorithm trains an Agent which operates within an environment, taking actions that are rewarded by the environment. The AI algorithm updates the policy of the agent over time to achieve higher rewards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*Oj7hHOlT_PRcMUxj6QJOeA.png" /><figcaption>AlphaGo utilized a policy network to learn policies from expert replay, a value network that accurately estimated the potential reward of a game state-action pair, and a tree search to find the most optimal action to take.</figcaption></figure><p>Reinforcement learning has been a part of AI research for more than 3 decades but the high point was in 2015 with the success of <a href="https://www.deepmind.com/research/highlighted-research/alphago">AlphaGo</a> defeating World Champion in Go using Neural Networks to learn the policy of the Agent. This was a start of a flurry of research into the field of deep reinforcement learning which is the specialization of utilizing deep neural networks as the policy learner in reinforcement learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6LoAVsX6NQELXM7EBHFcgw.jpeg" /><figcaption>In reinforcement learning an Agent takes actions in an environment, the state of which is changing constantly, and gets a reward for it. In Deep RL, the agent’s policy is decided by a Neural Network.</figcaption></figure><p>Deep reinforcement learning has seen research focus by major AI labs and tech giants alike in recent years. I personally believe that advancements in Deep Reinforcement Learning, in conjunction with other technologies, will play a crucial role in developing Artificial General Intelligence (AGI). RL has many applications in the coming years such as:</p><ol><li>Self-driving cars</li><li>Anomalous activity detection in cyber security</li><li>Information recommendation</li><li>Making energy management in grids and systems more efficient</li></ol><p>One of the most crucial functions AI/AGI must perform for humans is automating the process of creating wealth which would allow us to free ourselves up for better humanitarian pursuits. The application of Deep Reinforcement Learning to algorithmic trading will enable one of the many small automation AI can help us with in the future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*edhsO5MENoMccIVT9VBYkA.png" /><figcaption>RL algorithms are classified based on if a model of the learned or not and whether the model of the environment is given or not and how the deep neural network is trained — optimizing the value of the state-action pair or directly the policy function.</figcaption></figure><p>Many good libraries and toolkits exist in the open-source domain for the purpose of Algorithmic trading using Reinforcement learning. Yet, I found many of them are not very easy to deploy a model to market. After months of struggling with deploying these opensource libraries which either have minimal scope for customization or require in-depth library analysis for the excruciating amount of code rewrite.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ISPOIrB8REmJsqMwQkiWgg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xZe_NhjEXSVmRbOaG5H5SA.jpeg" /><figcaption>FinRL and TensorTrade are two upcoming libraries that provide out-of-the-box implementations to enable Reinforcement Learning for Algorithmic Trading but both of them are very much in active development.</figcaption></figure><p>I realized it is much better for someone to design their own custom Deep Reinforcement Learning experiment both as a learning experiment and for achieving their trading goals.</p><p>In the subsequent parts of the series of articles, I showcase how I prepare my dataset containing (Open, High, Low, Close, Volume) data points at 5-minute intervals for 30 stocks along with an index fund for a total of 31 assets. I then implemented my own custom environment for algorithmic trading in python using OpenAI’s gym — I shall explain the mathematical logic and variables embedded within this environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dt1ZgzF85iy4XYDm8hr8xg.jpeg" /><figcaption>Rewards earned by the final customized neural network in backtesting against data it had never seen.</figcaption></figure><p>I showcase how to design a custom policy to use with the Policy Proximal Optimization algorithm to perform the Reinforcement learning. Finally, I will showcase also how to use recurrent layers, geometric layers, and other complexities within the neural network.</p><p>Thanks for reading!</p><p><strong>Disclaimer: I would like to assert that these articles are not to be misconstrued as investment advice. Most algorithmic trading systems lose money when deployed to production. This article series is for educational purposes only.</strong></p><p>You can find the code and dataset used for these experiments in my <a href="https://github.com/Akhilesh-Gogikar/MultiStockRLTrading">Github</a> Repo. I would appreciate it if you could show some love and leave a star on the repo.</p><p>Please leave a comment I would love to hear your feedback on my work!</p><p>Please read ahead for data preprocessing for the RL — experiments in the below article.</p><p><a href="https://medium.com/@akhileshgogikar/applied-rl-data-preprocessing-for-algo-trading-4478251b9676">Applied RL: Custom RL for Algo Trading — Data Preprocessing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=106b1a2daa16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Applied RL: Custom Gym environment for multi-stock RL based Algo trading]]></title>
            <link>https://medium.com/@akhileshgogikar/custom-gym-environment-for-multi-stock-algo-trading-113b07dd445d?source=rss-f929c2f8eaaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/113b07dd445d</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <dc:creator><![CDATA[Akhilesh Gogikar]]></dc:creator>
            <pubDate>Mon, 06 Jun 2022 17:32:39 GMT</pubDate>
            <atom:updated>2022-06-06T17:45:00.723Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*hMy40cJgfwl3Ixk06DENIw.jpeg" /></figure><p>OpenAI open-sourced the Gym library for environment development in python. While it is mainly used for RL research, with many researchers coming up with better RL algorithms to improve the gameplay performance of Atari game environments implemented in it, we will use it to trade multiple stocks in the intraday setting. In the previous article, we discussed how to preprocess the data for our environment.</p><p><a href="https://medium.com/@akhileshgogikar/applied-rl-data-preprocessing-for-algo-trading-4478251b9676">Applied RL: Custom RL for Algo Trading — Data Preprocessing</a></p><p>While there are some good libraries with pre-implemented Gym environments for trading, I could not find one for multi-stock trading that can be used for inference without major memory manipulation on the backend making things unreliable. I thought it a good exercise to implement one for my specific use case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*BY5NA77e54PDoBWiaKHufw.png" /><figcaption>OpenAI Gym provides a framework for designing new environments for RL agents to learn tasks such as playing games, we will use it to build our trading environment.</figcaption></figure><p>Each Gym environment must have the following methods implemented:</p><pre>def CustomGymEnv(gym.Env):<br>    def __init__(self, args):<br>        #Define all the data that will be stored in the CustomEnv<br>        super(CustomGymEnv, self).__init__():<br>        # spaces</pre><pre>        # the action space for our agent which predicts score between (-1,1) for each stock as recommendation<br>        self.action_space = spaces.Box(low=-1, high=1, shape=(num_stocks,), dtype=np.float32)</pre><pre>        # the observation space which is (num_stocks, window_size, state_space)<br>        self.observation_space = spaces.Box(low=-np.inf, high=np.inf, shape=(num_stocks,window_size,state_space), dtype=np.float32)</pre><pre>    def reset():<br>        #Reset the environment variables for a new game cycle<br>    def step():<br>        #Execute a single round of trading within the environment<br>    def render():<br>        #Render a visualization of the environment to the screen</pre><p>For our trading use case, we will have to make some changes so that we track the right metrics and process the raw data into a format we can utilize for our purpose. We initialize the environment with the following information:</p><ol><li>dfs — a list of data frames containing the raw historical data, one for each asset</li><li>price_df — a data frame containing the historical closing prices of each stock as a column in each</li><li>initial_amount — the initial amount invested into the model for training</li><li>trade_cost — the cost of each trade, currently set to zero</li><li>num_features — the number of features per time interval for each asset</li><li>num_stocks — number of assets to be traded</li><li>window_size — the number of previous time intervals data to be considered for the next action</li><li>frame_bound — the range of values (start_index, end_index)in the price_df index to be used for training/test, start_index must be greater than window_size</li><li>scalers — the list of scalers used for scaling the data for each stock, internally defined if not already provided</li><li>tech_indicator_list — the list of technical indicators to be utilized for trading, num_features is updated if provided</li><li>reward_scaling — scaling the rewards/profits from our trading</li></ol><pre>class MultiStockTradingEnv(gym.Env):</pre><pre>     metadata = {&quot;render.modes&quot;: [&quot;human&quot;]}</pre><pre>     def __init__(self, dfs, price_df, initial_amount, trade_cost, num_features, num_stocks, window_size, frame_bound, scalers=None, tech_indicator_list=[], reward_scaling=1e-5):</pre><p>Since we are creating a trading environment we have to keep track of some more numbers such as the portfolio_value, margin, reserves, etc.</p><pre>self.margin = initial_amount</pre><pre>self.portfolio = [0]*num_stocks</pre><pre>self.PortfolioValue = 0</pre><pre>self.reserve = initial_amount</pre><p>The reset method for our environment will be rather simple, we reset all trackers to empty, the margin amount is set to the initial amount, and portfolio values are set to zero. The reset function must return the next observation i.e. the first set for new training.</p><pre>def reset(self):</pre><pre>    self._done = False</pre><pre>    self._current_tick = self._start_tick</pre><pre>    self._end_tick = len(self.prices)-1</pre><pre>    self._last_trade_tick = self._current_tick - 1</pre><pre>    self._position = np.zeros(self.assets)</pre><pre>    self._position_history = (self.window_size * [None]) + [self._position]</pre><pre>    self.margin = self.initial_amount</pre><pre>    self.portfolio = [0]*self.assets</pre><pre>    self.PV = 0</pre><pre>    self.reserve = self.initial_amount</pre><pre>    self._total_reward = 0.</pre><pre>    self._total_profit = 1.  # unit</pre><pre>    self._first_rendering = True</pre><pre>    self.history = {}</pre><pre>    return self._get_observation()</pre><p>Before we go ahead into explaining the step method for our environment, there is a prerequisite method we must call so that the data is prepared in the right manner internally for training and inference.</p><p>The process_data method must be called on our environment as it splices the data into the right window which we need based on the frame_bound variable earlier described, and scales the data based on the scalers available. The end_tick required for the condition to end each training loop is defined.</p><pre>def process_data(self):</pre><pre>    signal_features = []</pre><pre>    for i in range(self.assets):</pre><pre>        df = self.dfs[i]</pre><pre>        start = self.frame_bound[0] - self.window_size</pre><pre>        end = self.frame_bound[1]</pre><pre>        if self.scalers[i]:</pre><pre>            current_scaler = self.scalers[i]</pre><pre>            signal_features_i = current_scaler.transform(df.loc[:, self.tech_indicators])[start:end]</pre><pre>        else:</pre><pre>            current_scaler = StandardScaler()<br>            signal_features_i = current_scaler.fit_transform(df.loc[:, self.tech_indicators])[start:end]<br>            signal_features[i] = current_scaler</pre><pre>        signal_features.append(signal_features_i)</pre><pre>    self.prices = self.price_df.loc[:, :].to_numpy()[start:end]</pre><pre>    if self.representative:<br>        self.representative = self.price_df.loc[:, self.representative].to_numpy()[start:end]<br>    else:<br>        self.representative = self.price_df.loc[:, &#39;SENSEX&#39;].to_numpy()[start:end]</pre><pre>    self.signal_features = np.array(signal_features)</pre><pre>    self._end_tick = len(self.prices)-1</pre><pre>    return self.prices, self.signal_features</pre><p>Finally, we define the step method which is the most important method in our environment. We set the done condition to false and since we are now taking the action for the next time step we have to update the current_tick.</p><pre>def step(self, actions):</pre><pre>    self._done = False</pre><pre>    self._current_tick += 1</pre><p>The done state is updated if we are at the end of the cycle, this enables the agent to end trading and for the RL model to make updates.</p><pre>if self._current_tick == self._end_tick:</pre><pre>    self._done = True</pre><p>We get the current prices and since we have to divide the available amount by current prices we also create an array called current_prices_for_division</p><pre>#Get the current prices</pre><pre>current_prices = self.prices[self._current_tick]</pre><pre>#handling cases where current price is na and avoiding buying infinite 0 cost stocks</pre><pre>current_prices[np.isnan(current_prices)] = 0</pre><pre>current_prices_for_division = current_prices</pre><pre>current_prices_for_division[current_prices_for_division == 0] = 1e9</pre><p>Then we start processing the actions suggested by the agent, the agent provides a set of scores one for each asset, and we trade for only 33% of the assets the magnitude of which actions are the highest.</p><pre>#the absolute value distribution of next step portfolio</pre><pre>abs_portfolio_dist = abs(actions)</pre><pre># At any point in time we only trade for 33% of the stocks the model is most confident about</pre><pre># the scores for the rest are suppressed</pre><pre>N = int(np.round(abs_portfolio_dist.size*0.66))</pre><pre>abs_portfolio_dist[np.argpartition(abs_portfolio_dist,kth=N)[:N]] = 0</pre><p>Next, we update the margin available for trading, this takes into account price changes that may have taken place since the last trading interval.</p><pre>self.margin = self.reserve + sum(self.portfolio*current_prices)</pre><p>With the updated margin we then calculate the actions to be taken to change the portfolio</p><pre>#Normalize the portfolio positions for next step</pre><pre>norm_margin_pos = (abs_portfolio_dist/sum(abs_portfolio_dist))*self.margin</pre><pre>#Calulate the money in the next positions</pre><pre>next_positions = np.sign(actions)*norm_margin_pos</pre><pre>#Change in money value of the positions</pre><pre>change_in_positions = next_positions - self._position</pre><pre>#actions to take in the market</pre><pre>actions_in_market = np.divide(change_in_positions,current_prices_for_division).astype(int)</pre><p>Now we can update our internal representation of the portfolio — in case we are to do a production-grade operation an API call can be fired off at this stage to make the trade. We also update the PortfolioValue, margin, reserve, and cost of trading here.</p><pre>new_portfolio = actions_in_market + self.portfolio</pre><pre>new_pv = sum(new_portfolio*current_prices)</pre><pre>new_reserve = self.margin - new_pv</pre><pre>profit = (new_pv + new_reserve) - (self.PV + self.reserve)</pre><pre># calculate the cost of each action in market</pre><pre>cost = self.trade_cost*sum(abs(np.sign(actions_in_market)))</pre><p>Now we update the variables in the environment:</p><pre>self._position = next_positions</pre><pre>self.portfolio = new_portfolio</pre><pre>self.PortfolioValue = new_pv</pre><pre>self.reserve = new_reserve - cost</pre><p>Finally, we calculate the reward we had received for the action taken previously and after updating some history tracker, return the rewards.</p><pre># Calculate the total step reward - profit made this step</pre><pre>step_reward = profit - cost</pre><pre>self._total_reward += self.reward_scaling*step_reward</pre><pre>self.rewards.append(self._total_reward)</pre><pre>self.pvs.append(new_pv)</pre><pre>self._update_profit()</pre><pre>self._position = next_positions</pre><pre>self._position_history.append(self._position)</pre><pre>observation = self._get_observation()</pre><pre>info = dict( total_reward = self._total_reward, total_profit = self._total_profit,)</pre><pre>self._update_history(info)</pre><pre>if self.margin &lt; 0:</pre><pre>    self._done = True</pre><pre>return observation, step_reward, self._done, info</pre><p>To end it all, we also define the render method which for our case plots a figure of the portfolio values in our environment to be later showcased with Matplotlib.</p><pre>def render(self, mode=&#39;human&#39;):</pre><pre>    if self._first_rendering:</pre><pre>        self._first_rendering = False</pre><pre>    plt.cla()</pre><pre>    plt.plot(self.pvs)</pre><pre>    plt.suptitle(</pre><pre>        &quot;Total Reward: %.6f&quot; % self._total_reward + &#39; ~ &#39; +</pre><pre>        &quot;Total Profit: %.6f&quot; % self._total_profit<br>)<br>    plt.pause(0.01)</pre><p>And that’s it, we have finished defining a custom environment for our trading task. In applying RL to a problem, defining the environment is the most challenging task as there are a lot of design decisions we need to contend with. Gym library makes our life easy by bringing structure to this process but still, it requires domain expertise to understand what data points to track and how to configure the actions.</p><p>We can train and infer the environment with the standard policies and RL algorithms from most RL libraries allowing for the Gym-based environment API. Here is the rendering result with the additional market index value plot with the standard NeuralNetwork MLP policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2om7aFg2LoHwl-QhQ5uX6Q.jpeg" /></figure><p>An important part of designing an environment is also how the agent is rewarded in our case the overall profit is the reward which is pretty neat. The process of receiving rewards is a very important part of a successful RL agent.</p><p>Thanks for reading! As a disclaimer, I would like to explain that no part of this work must be misconstrued as investment advice. Most algorithmic trading systems — even the best of them, lose money when deployed in the market.</p><p>The code for this tutorial can be found on my <a href="https://github.com/Akhilesh-Gogikar/MultiStockRLTrading">Github repo</a>. If you like the work so far please consider adding a star to the repo as I will continue to develop it further as per the response and please leave a comment below. Now we can move on to implementing a customized policy for our new trading environment.</p><p><a href="https://medium.com/@akhileshgogikar/applied-rl-customizing-neural-networks-for-rl-policies-a5a9e2cf763e">Applied RL: Customization of RL policies using StableBaselines3</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=113b07dd445d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Applied RL: Custom RL for Algo Trading — Data Preprocessing]]></title>
            <link>https://medium.com/@akhileshgogikar/applied-rl-data-preprocessing-for-algo-trading-4478251b9676?source=rss-f929c2f8eaaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/4478251b9676</guid>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Akhilesh Gogikar]]></dc:creator>
            <pubDate>Mon, 06 Jun 2022 17:29:31 GMT</pubDate>
            <atom:updated>2022-06-06T17:44:12.242Z</atom:updated>
            <content:encoded><![CDATA[<h3>Applied RL: Custom RL for Algo Trading — Data Preprocessing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*hMy40cJgfwl3Ixk06DENIw.jpeg" /></figure><p>We are going to build a custom Gym environment for multi-stock trading with a customized policy in stablebaselines3 using the PPO algorithm</p><p><a href="https://medium.com/@akhileshgogikar/custom-deep-rl-for-algo-trading-106b1a2daa16">Applied RL: Customized Deep Reinforcement Learning for Algorithmic Trading</a></p><p>Unlike most AI tasks, AI in Algo trading benefits from the fact that the datasets are readily available with financial data providers such as YahooFinance, Quantopian, or your broker. It also helps that most tasks in Financial time-series-based AI don’t have a strict requirement for annotation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*wlSTqSOjctYKVdCCrYiTgQ.png" /><figcaption>A sample data frame of the raw data used from one of the stocks used to build the multi-stock trading environment.</figcaption></figure><p>The data set we utilize is a dataset collected for 30 stocks from the Indian stock market alongside the Sensex index values to make up for a total of 31 assets to be traded by our agent.</p><p>We loop over all the files and load them to data frames while also adding some trade time-based features as such:</p><pre>for filename in data_files:</pre><pre>    df = pd.read_csv(filename)</pre><pre>    df[&#39;datetime&#39;] = pd.to_datetime(df[&#39;datetime&#39;])</pre><pre>    name = df[&#39;name&#39;].iloc[0]</pre><pre>    # Adding the Time of Day and Day of Week features</pre><pre>    df[&#39;ToD&#39;] = df[&#39;datetime&#39;].dt.hour + df[&#39;datetime&#39;].dt.minute/60</pre><pre>    df[&#39;DoW&#39;] = df[&#39;datetime&#39;].dt.weekday/6</pre><pre>    df.sort_values([&#39;timestamp&#39;], inplace=True)</pre><p>Then we add more features using TA-Lib, a library for technical analysis in python.</p><pre><strong>def</strong> add_features(tic_df):</pre><pre>    # Returns in the last t intervals</pre><pre>    for t in range(1, 11):</pre><pre>        tic_df[f&#39;ret{t}min&#39;] =                                                                         tic_df[&#39;close&#39;].div(tic_df[&#39;open&#39;].shift(t-1)).sub(1)</pre><pre>    # Simple Moving Average based features</pre><pre>        tic_df[&#39;sma&#39;] = talib.SMA(tic_df[&#39;close&#39;])</pre><pre>        tic_df[&#39;5sma&#39;] = talib.SMA(tic_df[&#39;close&#39;], timeperiod=5)</pre><pre>        tic_df[&#39;20sma&#39;] = talib.SMA(tic_df[&#39;close&#39;], timeperiod=20)</pre><p>We also add signals for buy and sell based on other Algo-trading strategies such as moving average cross-overs.</p><pre>tic_df[&#39;sma_buy&#39;] = np.where((tic_df[&#39;close&#39;] &lt; tic_df[&#39;5sma&#39;]), 1, 0)</pre><p>Overall we add a total of 50 features for each stock at each timestep making our observation space of the size of (number_of_stocks, number_of_timesteps, number_of_features).</p><p>We then start to join all the data frames into one single data frame to align the timestamps and pad the timestamps with a null value.</p><pre>updated_df = add_features(df)</pre><pre>updated_df[&#39;datetime&#39;] = pd.to_datetime(updated_df[&#39;datetime&#39;])</pre><pre>updated_df = df.set_index(pd.DatetimeIndex(updated_df[&#39;datetime&#39;]))</pre><pre># Replace infinities with zeroes</pre><pre>updated_df.replace([np.inf, -np.inf], 0, inplace=True)</pre><pre>dfs = pd.concat([dfs,updated_df], axis=1)</pre><pre>dfs.interpolate(method=&#39;pad&#39;, limit_direction=&#39;forward&#39;, inplace=True)</pre><p>We then split the data frame into data frames of each stock so that we can pass a list of data frames to our environment. We also need to create a data frame to only contain the closing prices of each asset in that trading interval</p><pre>cols_per_asset = int(len(dfs.columns)/num_assets)</pre><pre>df_list = []</pre><pre>price_df = pd.DataFrame()</pre><pre>for i in range(num_assets):</pre><pre>    df = dfs.iloc[:,i*cols_per_asset:i*cols_per_asset+cols_per_asset]</pre><pre>    df.drop([&#39;datetime&#39;], axis=1, inplace=True)</pre><pre>    price_df[names[i]] = df[&#39;close&#39;]</pre><pre>    df_list.append(df)</pre><pre>cols_per_asset -= 1</pre><p>That’s it! We are done with preprocessing the data frame for trading and we can now initialize the environment.</p><pre>env = MultiStockTradingEnv(df_list, price_df, stock_dim=num_assets, initial_amount=1000000, trade_cost=0, state_space=cols_per_asset, action_space=num_assets, window_size=12 frame_bound = (12,len(price_df)-1500), tech_indicator_list=indicators)</pre><p>Okay! now that we have established how we preprocess our data and pass it to our RL environment we can now go ahead and start implementing the environment.</p><p><a href="https://medium.com/@akhileshgogikar/custom-gym-environment-for-multi-stock-algo-trading-113b07dd445d">Applied RL: Custom Gym environment for multi-stock RL based Algo trading</a></p><p><strong>Disclaimer: Any part of this tutorial must not be misconstrued as investment advice. Most algorithmic trading systems — even the best in backtesting — lose money when deployed in the market.</strong></p><p>If you liked my work, please show some love and leave a comment. The code for this article is available in my <a href="https://github.com/Akhilesh-Gogikar/MultiStockRLTrading">Github repo.</a> Please leave a star if you liked it and intend to use it in your work. Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4478251b9676" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Applied RL: Customization of RL policies using StableBaselines3]]></title>
            <link>https://medium.com/@akhileshgogikar/applied-rl-customizing-neural-networks-for-rl-policies-a5a9e2cf763e?source=rss-f929c2f8eaaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5a9e2cf763e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Akhilesh Gogikar]]></dc:creator>
            <pubDate>Mon, 06 Jun 2022 17:24:17 GMT</pubDate>
            <atom:updated>2022-06-06T17:57:46.328Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*hMy40cJgfwl3Ixk06DENIw.jpeg" /></figure><p>As explained in the previous post in this series we have developed a multi-stock trading environment using OpenAI’s Gym API.</p><p><a href="https://medium.com/@akhileshgogikar/custom-gym-environment-for-multi-stock-algo-trading-113b07dd445d">Applied RL: Custom Gym environment for multi-stock RL based Algo trading</a></p><p>We can train an RL model using this environment by importing the appropriate RL algorithm from StableBaselines3 which is a community-developed extension to the StableBaselines library originally open-sourced by OpenAI.</p><pre>from multi_stock_trading_env import MultiStockTradingEnv</pre><pre>from stable_baselines3 import PPO</pre><pre>env = MultiStockTradingEnv(df_list, price_df, num_stocks=num_assets, initial_amount=1000000, trade_cost=0, num_features=cols_per_asset, window_size=12, frame_bound = (12,len(price_df)-1500), tech_indicator_list=indicators)</pre><pre>prices, features = env.process_data()</pre><pre>model = PPO(&#39;MlpPolicy&#39;, env, verbose=2,tensorboard_log=&#39;tb_logs&#39;, batch_size=256)</pre><pre>model.learn(total_timesteps=1000)</pre><p>We can customize the RL algorithm by writing our own custom policy which can be utilized to train the RL agent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RUdQqJ7JntkS-5K2aZkqNQ.png" /><figcaption>stablebaselines3 provides an out-of-the-box features extractor and we can customize the fully-connected network.</figcaption></figure><p>We import the base ActorCriticPolicy class from the stable_baselines3. Then we update the _build_mlp_extractor method to update the mlp_extractor of the policy. Then we write a custom network to update the mlp_extractor.</p><pre>from stable_baselines3.common.policies import ActorCriticPolicy</pre><pre><strong>class</strong> CustomActorCriticPolicy(ActorCriticPolicy):</pre><pre>     <strong>def</strong> __init__( self, observation_space: gym.spaces.Space, action_space: gym.spaces.Space, lr_schedule: Callable[[float], float], net_arch: Optional[List[Union[int, Dict[str, List[int]]]]] = None, activation_fn: Type[nn.Module] = nn.Tanh, *args, **kwargs,):</pre><pre>         super(CustomActorCriticPolicy, self).__init__( observation_space, action_space, lr_schedule, net_arch, activation_fn,</pre><pre>         # Pass remaining arguments to base class</pre><pre>*args,**kwargs,)</pre><pre>         # Disable orthogonal initialization</pre><pre>    self.ortho_init = False</pre><pre>    <strong>def</strong> _build_mlp_extractor(self) -&gt; None:<br>        self.mlp_extractor = CustomNetwork( last_layer_dim_pi = self.action_space.shape[0], last_layer_dim_vf = self.action_space.shape[0], timesteps = self.observation_space.shape[1], feature_dim=self.observation_space.shape[2])</pre><p>For the custom neural network for the MLP extractor, we will build a simple our own custom MLP architecture but it will take into account reduction along a specific dimension each time.</p><p>We have to keep in mind that the default feature extractor in stablebaselines3 is the flattening operation so our observation input of the form (Num_stocks, Timesteps, Num_Features) is transformed into a 1D array of size (Num_stocks*Timesteps*Num_Features).</p><p>Our neural network transforms this input space into an actions array of size Num_stocks.</p><p>(Num_stocks*Timesteps*Num_Features) -&gt; nn.Linear -&gt; (Num_stocks*Num_Features) -&gt; Relu() -&gt; nn.Linear() -&gt; (Num_stocks,) -&gt; Tanh()</p><pre><strong>class</strong> CustomNetwork(nn.Module):</pre><pre>&quot;&quot;&quot;</pre><pre>Custom network for policy and value function.</pre><pre>It receives as input the features extracted by the feature extractor.</pre><pre>:param feature_dim: dimension of the features extracted with the features_extractor (e.g. features from a CNN)</pre><pre>:param last_layer_dim_pi: (int) number of units for the last layer of the policy network</pre><pre>:param last_layer_dim_vf: (int) number of units for the last layer of the value network</pre><pre>&quot;&quot;&quot;</pre><pre><strong>def</strong> __init__(</pre><pre>self,</pre><pre>feature_dim: int,</pre><pre>timesteps: int = 12,</pre><pre>last_layer_dim_pi: int = 64,</pre><pre>last_layer_dim_vf: int = 64,</pre><pre>):</pre><pre>    super(CustomNetwork, self).__init__()</pre><pre>    # IMPORTANT:</pre><pre>    # Save output dimensions, used to create the distributions</pre><pre>    self.latent_dim_pi = last_layer_dim_pi</pre><pre>    self.latent_dim_vf = last_layer_dim_vf</pre><pre>    # Policy network<br>    self.policy_net =<br>    nn.Sequential(<br>    nn.Linear(last_layer_dim_pi*timesteps*feature_dim,<br>    last_layer_dim_pi*feature_dim),<br>    nn.ReLU(),<br>    nn.Linear(last_layer_dim_pi*feature_dim,last_layer_dim_pi),<br>    nn.Tanh())</pre><pre>    # Value network<br>    self.value_net = nn.Sequential(<br>    nn.Linear(last_layer_dim_pi*timesteps*feature_dim,<br>    last_layer_dim_pi*feature_dim), nn.ReLU(),<br>    nn.Linear(last_layer_dim_pi*feature_dim, last_layer_dim_pi),<br>    nn.Tanh())</pre><pre><strong>def</strong> forward(self, features: th.Tensor) -&gt; Tuple[th.Tensor, th.Tensor]:</pre><pre>    &quot;&quot;&quot;</pre><pre>    :return: (th.Tensor, th.Tensor) latent_policy, latent_value of     the specified network.</pre><pre>    If all layers are shared, then ``latent_policy == latent_value``</pre><pre>    &quot;&quot;&quot;</pre><pre>    return self.policy_net(features), self.value_net(features)</pre><pre><strong>def</strong> forward_actor(self, features: th.Tensor) -&gt; th.Tensor:<br>    return self.policy_net(features)</pre><pre><strong>def</strong> forward_critic(self, features: th.Tensor) -&gt; th.Tensor:</pre><pre>    return self.value_net(features)</pre><p>Let’s see how our model performs by training it using a part of the data set and inferring it over the test data set.</p><pre>model = PPO(CustomActorCriticPolicy, env, verbose=2,tensorboard_log=&#39;tb_logs&#39;, batch_size=256)</pre><pre>model.learn(total_timesteps=1000)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*roOvkwDkDI7F74EIHWEeEQ.jpeg" /><figcaption>The rewards of the RL model with the new custom MLP architecture.</figcaption></figure><p>That’s it and now we have designed a custom policy and value networks for our RL policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*bckLrB1gfrVFsDYC1CeR_A.jpeg" /></figure><p>In fact, as long as we build a network that takes input as the 1D array (Num_stocks*Timesteps*Num_Features) and output the actions in the size (Num_stocks,) we should be good with any neural network we put in as a policy or value network so long as the learning process remains stable and bug-free.</p><p>In fact, in the next article, we will get funky as to how we can do it by adding recurrent layers to learn along the temporal dimension, adding attention mechanism in the hidden layers, try if we can add geometric learning by creating a fully connected graph with each node representing an asset.</p><p>You can find the code for this article on <a href="https://github.com/Akhilesh-Gogikar/MultiStockRLTrading">Github</a>.</p><p><strong>Disclaimer: I would like to assert that these articles are not to be misconstrued as investment advice. Most algorithmic trading systems lose money when deployed to production. This article series is for educational purposes only.</strong></p><p>I would appreciate it if you could show some love and leave a star on the repo.</p><p>The next article in this series can be found here →</p><p><a href="https://medium.com/@akhileshgogikar/applied-reinforcement-learning-3e73ca771bac">Applied RL: Advanced deep learning customization of neural networks for RL based Algo trading</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5a9e2cf763e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Applied RL: Advanced deep learning customization of neural networks for RL based Algo trading]]></title>
            <link>https://medium.com/@akhileshgogikar/applied-reinforcement-learning-3e73ca771bac?source=rss-f929c2f8eaaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e73ca771bac</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Akhilesh Gogikar]]></dc:creator>
            <pubDate>Mon, 06 Jun 2022 17:22:19 GMT</pubDate>
            <atom:updated>2022-06-06T17:46:34.070Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*hMy40cJgfwl3Ixk06DENIw.jpeg" /></figure><p>Previously, we had developed a custom policy network by defining a new neural network architecture with new linear layers.</p><p><a href="https://medium.com/@akhileshgogikar/applied-rl-customizing-neural-networks-for-rl-policies-a5a9e2cf763e">Applied RL: Customization of RL policies using StableBaselines3</a></p><p>But we can do so much more to customize the neural network architecture. As neural networks are universal function approximations, as long as the network architecture is not unstable and error-free almost any combination of neural network architecture can give good results. The usual goal of ML engineers is to find the most efficient and accurate architecture. For the purpose of this learning exercise, let’s not be bogged down by such utilitarian goals.</p><p>In this article, we will develop a neural network with the following additions:</p><ol><li>Add a recurrent unit to learn embeddings along the temporal dimension</li><li>Add an attention block to combine the embeddings to the attention vector</li><li>Add a graph attention layer to build a graph embedding of the attention vector</li><li>Add a capsule layer on the fusion of the graph attention embedding with the attention vector</li></ol><p>To get started, we build the custom neural network inheriting from the nn.Module of Pytorch.</p><pre><strong>class</strong> CapsGATattentionGRU(nn.Module):<br>    <strong>def</strong> __init__(self,input_dim,time_step,hidden_dim,use_gru=True):<br>        <br>        super(CapsGATattentionGRU, self).__init__()</pre><pre>        outer_edge = np.ones(shape=(2, input_dim**2))</pre><pre>        # Edge_index for adjacency matrix for geometric learning<br>        count = 0<br>        for i in range(input_dim):<br>            for j in range(input_dim):<br>                outer_edge[0][count] = i<br>                outer_edge[1][count] = j<br>                count += 1<br>      <br>        # basic parameters<br>        self.dim = hidden_dim<br>        self.input_dim = input_dim<br>        self.time_step = time_step<br>        self.outer_edge = outer_edge<br>        self.batch = 1</pre><pre>        self.inner_edge = <br>            torch.tensor(outer_edge,dtype=torch.int64).to(&#39;cuda:0&#39;)</pre><pre>        self.use_gru = use_gru</pre><pre>        # hidden layers</pre><pre>        if self.use_gru:</pre><pre>            self.temporal_encoder =<br>                nn.GRU(input_dim*hidden_dim,input_dim*hidden_dim, num_layers=2, bidirectional=False)</pre><pre>        self.inner_gat0 = GATv2Conv(hidden_dim , hidden_dim)<br>        self.inner_gat1 = GATv2Conv(hidden_dim,hidden_dim)</pre><pre>        self.attention = AttentionBlock(12,hidden_dim)</pre><pre>        self.caps_module =<br>            CapsuleLinear(out_capsules=self.input_dim,<br>                in_length=2*hidden_dim, out_length=hidden_dim,<br>                in_capsules=None, routing_type=&#39;dynamic&#39;,<br>                num_iterations=3)</pre><pre>        self.fusion = nn.Linear(hidden_dim,input_dim)</pre><p>So we have defined some key layers in this initialization of the neural network:</p><ol><li>The temporal encoder layer is an instance of the nn.GRU from PyTorch</li></ol><pre><strong>def</strong> forward(self,inputs):</pre><pre>    inputs = torch.nan_to_num(inputs, nan=0.0, posinf=1.0)</pre><pre>    #inputs shape : torch.Size([1, 18600])<br>    if self.use_gru:</pre><pre>    embedding,_ =<br>    torch.relu(self.temporal_encoder(inputs.view(-1,self.time_step, self.input_dim*self.dim)))</pre><pre>    # Embedding shape: torch.Size([1, 12, 1550])</pre><p>2. The attention layer is an instance of the custom Attention block defined below:</p><pre><strong>class</strong> AttentionBlock(nn.Module):</pre><pre><strong>def</strong> __init__(self,time_step,dim):</pre><pre>    super(AttentionBlock, self).__init__()</pre><pre>    self.time_step = time_step</pre><pre>    self.attention_matrix = nn.Linear(time_step, time_step)</pre><pre><strong>def</strong> forward(self, inputs):</pre><pre>    inputs_t = torch.transpose(inputs,2,1) # (batch_size, input_dim, time_step)</pre><pre>    attention_weight = self.attention_matrix(inputs_t)</pre><pre>    attention_probs = F.softmax(attention_weight,dim=-1)</pre><pre>    attention_probs = torch.transpose(attention_probs,2,1)</pre><pre>    attention_vec = torch.mul(attention_probs, inputs)</pre><pre>    attention_vec = torch.sum(attention_vec,dim=1)</pre><pre>    return attention_vec, attention_probs</pre><p>The attention layer is applied along the temporal dimension of the embeddings:</p><pre># Embedding shape: torch.Size([1, 12, 1550])</pre><pre>att_vector,_ = self.attention(embedding) # (100,dim)</pre><pre># Attention vector shape: torch.Size([1, 1550])</pre><p>3. inner_gat0 and inner_gat1 are instances of graph attention layers from PyTorch geometric which are applied in a Residual fashion</p><pre>inner_graph_embedding = torch.relu(self.inner_gat0(x,self.inner_edge))</pre><pre>inner_graph_embedding0 = torch.relu(self.inner_gat1(inner_graph_embedding, self.inner_edge.view(2, -1)))</pre><pre>inner_graph_embedding = torch.add(inner_graph_embedding, inner_graph_embedding0)</pre><pre>inner_graph_embedding = inner_graph_embedding.view(-1,self.input_dim,self.dim)</pre><pre># inner_graph_embedding shape: torch.Size([1, 31, 50])</pre><p>4. Finally we add a capsule network layer to apply something like a hough transform</p><pre># fusion</pre><pre>fusion_vec = torch.cat((att_vector,inner_graph_embedding),dim=-1)</pre><pre># fusion_vec shape : torch.Size([1, 31, 50])</pre><pre>caps_out, _ = self.caps_module(fusion_vec)</pre><pre># caps_out.shape: torch.Size([1, 31, 50])</pre><pre>out_vec = torch.tanh(self.fusion(torch.relu(caps_out)))</pre><pre># out_vec.shape: torch.Size([1, 31, 31])</pre><pre>return out_vec</pre><p>Let’s see what we can do with this concoction of deep learning techniques when amalgamated to form a neural network.</p><p>We update the policy and value network in our new custom policy, observe that we had to make some changes in the linear layers, and add a transpose to make sure the output vector is (num_stocks,) shaped.</p><pre># Policy network</pre><pre>self.policy_net = nn.Sequential(</pre><pre>CapsGATattentionGRU(last_layer_dim_pi,timesteps,feature_dim),</pre><pre>nn.Linear(last_layer_dim_pi, 1), Transpose(), nn.Tanh()</pre><pre>)</pre><pre># Value network</pre><pre>self.value_net = nn.Sequential(</pre><pre>CapsGATattentionGRU(last_layer_dim_vf,timesteps,feature_dim),</pre><pre>nn.Linear(last_layer_dim_pi, 1), Transpose(), nn.Tanh()</pre><pre>)</pre><p>Then we run the model learning process with this policy, but due to the added bells and whistles, the training process requires substantially more amount of time.</p><pre>model = PPO(GATActorCriticPolicy, env, verbose=2,tensorboard_log=&#39;tb_logs&#39;, batch_size=16)</pre><pre>model.learn(total_timesteps=1000)</pre><p>When we run inference on the test data we see the following returns we see improved results, in fact, we see consistently positive results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dt1ZgzF85iy4XYDm8hr8xg.jpeg" /></figure><p>And that’s it folks we have explored building a custom RL environment for trading and trained custom RL policies by using the StableBaselines3 library.</p><p>Hope you liked my work but it is important to note that this work has been done only for educational purposes and none of it must be understood as a bit of profitable advice for investing. In my experience, all but a handful of — even the best in backtesting — trading strategies lead to losses when deployed in production.</p><p>Please check out my <a href="https://github.com/Akhilesh-Gogikar/MultiStockRLTrading">GitHub repository</a> for the code. I would appreciate some love with a few claps and if you could also star my Github repo.</p><p>Please show some love and leave a comment if you have feedback. Many thanks if you have read through all the articles so far. Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e73ca771bac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI based Auto-Generation of X-ray reports using Attention]]></title>
            <link>https://medium.com/@akhileshgogikar/ai-based-auto-generation-of-x-ray-reports-using-attention-8fcdad6545a2?source=rss-f929c2f8eaaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fcdad6545a2</guid>
            <category><![CDATA[radiology]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[x-rays]]></category>
            <dc:creator><![CDATA[Akhilesh Gogikar]]></dc:creator>
            <pubDate>Wed, 13 Nov 2019 04:01:29 GMT</pubDate>
            <atom:updated>2019-11-13T04:01:29.979Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*SCTfL6-HaLZc-eDlj75zWQ.png" /><figcaption>Example of an X-ray report</figcaption></figure><p>When you hear that AI is going to replace Radiologists completely — as Good Ol’ Geoffrey Hinton famously said — You might relive the scares of AI dominating the workforce and eventually taking over our planet. On the contrary it is the need of the Hour that we build AI systems to support as many job roles as we can to improve the impact that these jobs can have to humanity.</p><p>As we always start with low hanging fruits — We turn our attention to Radiology. Radiology involves Analysis and Reporting of findings from medical images — Xrays, CT scans, MRIs — to help further diagnosis of ailments and proper treatment. Analysis of images is a modality of AI that current solutions excel at — Computer Vision.</p><p>Currently the world faces an acute shortage of radiologists. Testimony to that would be the booming Tele-radiology market growing at a near 19% CAGR across the globe, key players coming in from the developing world with dense English speaking populations examples — India, Indonesia etc. Scarcity in of Radiologists in rural India can go as high as 1:100,000. AI which can help radiologist workflows to become more productive and efficient is in high demand.</p><p>This is a clear problem which begs to be solved and there are nearly two dozen Medical Imaging AI startups looking to fill the gap. The demand for the solutions is so desperate that major Tele-radiology firms in India have already tied up with AI startups or are developing in-house proprietary algorithms using all the domain knowledge they have. They major requirement from these solutions is to provide an explainable AI which can not only tell a radiologist its inference but also showcase a basis for its judgement.</p><p>A new technique which still in nascent stages which is most approriate for automated AI report generation from images is the much celebrated Image captioning using a combination of Convolution &amp; Recurrent Neural Networks. Famously demonstrated in the paper “Show &amp; Tell” by Google.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*Kxmy6hnUB979L2dT1ejnEQ.png" /><figcaption>Demonstrating Google’s Show and Tell</figcaption></figure><p>The solution works by extracting a vector which represents the image using a convolutional neural network which a specialized AI component for images and classification tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3BRLw4lsANPEfGgimG3YVQ.png" /><figcaption>Typical CNN as per wikipedia</figcaption></figure><p>This representation is then passed on to one of many types of recurrent neural networks — Vanilla RNN, GRUs, LSTMs, Bi-LSTMs. These recurrent units are specialized in learning from and generating sequences for prediction type of tasks. Essentially they preserve the essence of a previous operation to derive the prediction for current input in the sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F8WphMopgERgNflz8Eu6Uw.png" /><figcaption>Typical RNN operation</figcaption></figure><p>This how-ever doesn’t explain how the AI is making decision on how to caption the Image. Montreal based researchers solved this problem in a subsequent model called “Show, Attend &amp; Tell”. This new model utilized a attention model which back traced the RNN’s activations to a feature map that can overlay on top of the original image and showcase the source of the prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*6sqMffOLgQgtTvf9vQARDw.png" /><figcaption>Show Attend and Tell in action</figcaption></figure><p>This technique can then be applied to X-ray image captioning problem considering each finding as a token in the vocabulary. We get the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ap9CA9og7nN4DVanWcYCAw.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*clomLxbQyrz9XSLXMwBh6Q.gif" /></figure><p>This technique comprises of one of the lesser known aspects of the AI revolution that is going swoop in to everyday lives and business operations. This will benefit radiologists by generating a preliminary set of finding and sources of those inference which they can they validate or correct, saving crucial time an “human” attention effort.</p><p>Attention based image captioning can also be applied in other industries requiring explainable AI but my personal belief is this technique and Radiology is a match made in heaven.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fcdad6545a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>