avatarJakub Polec

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

3706

Abstract

an class="hljs-attr">"Energy"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><span class="hljs-string">"XOM"</span><span class="hljs-punctuation">,</span> <span class="hljs-string">"CVX"</span><span class="hljs-punctuation">,</span> <span class="hljs-string">"OXY"</span><span class="hljs-punctuation">,</span> <span class="hljs-string">"CVE"</span><span class="hljs-punctuation">]</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"Weed"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><span class="hljs-string">"TLRY"</span><span class="hljs-punctuation">,</span> <span class="hljs-string">"ACB"</span><span class="hljs-punctuation">,</span> <span class="hljs-string">"CGC"</span><span class="hljs-punctuation">]</span> <span class="hljs-punctuation">}</span></pre></div><p id="0b01">Now, we can create a function that takes a sector name as input, fetches the historical data for the corresponding tickers, calculates performance metrics, and visualizes the results. This function will allow us to quickly check the performance of any sector in the future.</p><div id="af90"><pre><span class="hljs-comment"># Fetch data for each category</span> <span class="hljs-keyword">for</span> category, category_tickers <span class="hljs-keyword">in</span> tickers.items(): category_data = {} legend_labels = [] <span class="hljs-keyword">for</span> ticker <span class="hljs-keyword">in</span> category_tickers: logger.info(<span class="hljs-string">f"Fetching data for <span class="hljs-subst">{ticker}</span>..."</span>) <span class="hljs-keyword">try</span>: data = <span class="hljs-keyword">await</span> dc.equities.async_get_ohlcv( tickers=[ticker], exchanges=[<span class="hljs-string">"US"</span>], granularity=<span class="hljs-string">"1d"</span>, period_starts=[start_date], period_ends=[end_date], source=<span class="hljs-string">'eod'</span> ) <span class="hljs-keyword">if</span> data: df = data[<span class="hljs-number">0</span>] <span class="hljs-keyword">if</span> <span class="hljs-string">'datetime'</span> <span class="hljs-keyword">in</span> df.columns <span class="hljs-keyword">and</span> <span class="hljs-keyword">not</span> pd.api.types.is_datetime64_any_dtype(df.index): df[<span class="hljs-string">'datetime'</span>] = pd.to_datetime(df[<span class="hljs-string">'datetime'</span>]) df.set_index(<span class="hljs-string">'datetime'</span>, inplace=<span class="hljs-literal">True</span>) category_data[ticker] = df[<span class="hljs-string">'close'</span>] logger.info(<span class="hljs-string">f"Data for <span class="hljs-subst">{ticker}</span> fetched successfully."</span>)

 <span class="hljs-comment"># Calculate changes and append to legend labels</span>
 changes = calculate_changes(df[<span class="hljs-string">'close'</span>])
 change_label = <span class="hljs-string">', '</span>.join([<span class="hljs-string">f"<span class="hljs-subst">{k}</span>: <span class="hljs-subst">{v:<span class="hljs-number">.2</span>f}</span>%"</span> <span class="hljs-keyword">for</span> k, v <span class="hljs-keyword">in</span> changes.items()])
 legend_labels.append(<span class="hljs-string">f"<span class="hljs-subst">{ticker}</span> (<span class="hljs-subst">{change_label}</span>)"</span>)

<span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e: <span class="hljs-built_in">print</span>(<span class="hljs-string">f"Error fetching data for <span class="hljs-subst">{ticker}</span>: <span class="hljs-subst">{e}</span>"</span>)</pre></

Options

div><p id="1032"><b>The full code is available on GitHub for paid subscribers at <a href="https://quantjourney.substack.com/">https://quantjourney.substack.com/</a></b></p><p id="a8fc"><b>If you wish to access the complete code, please subscribe to support my work. Thank you.</b></p><p id="9509">So now we will plot the historical data, calculate performance metrics, and save the plots as PNG files for each sector.</p><p id="12e0">In the example usage section, we iterate over each sector and its corresponding tickers. For each sector, we fetch the historical data, calculate the performance metrics, print the metrics, and generate and save the plot as a PNG file.</p><p id="624f">The performance metrics are calculated as follows:</p><ul><li>1W: Average percentage change over the last 5 trading days (1 week)</li><li>1M: Average percentage change over the last 21 trading days (1 month)</li><li>3M: Average percentage change over the last 63 trading days (3 months)</li><li>6M: Average percentage change over the last 126 trading days (6 months)</li></ul><p id="7f05">The plots will be saved as PNG files with the naming convention “<i>{sector}_performance.png</i>”.</p><div id="7234"><pre><span class="hljs-comment"># Plotting line chart</span> fig = pl.plot_line(df=combined_df, legend_labels=legend_labels, legend_stats=put.LegendStats.NONE, <span class="hljs-comment"># Adjust as needed</span> title=<span class="hljs-string">f"<span class="hljs-subst">{category}</span> - Closing Prices and Performance (Past Year)"</span>, ylabel=<span class="hljs-string">'Closing Price'</span>, legend_title=<span class="hljs-string">"Ticker (Change: 1W, 1M, 3M, 6M)"</span>, x_date_freq=<span class="hljs-string">'M'</span>, fontsize=<span class="hljs-number">8</span> ) <span class="hljs-keyword">if</span> fig <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>: fig.savefig(<span class="hljs-string">f"<span class="hljs-subst">{category}</span>_closing_prices.png"</span>, <span class="hljs-built_in">format</span>=<span class="hljs-string">'png'</span>, dpi=<span class="hljs-number">300</span>, bbox_inches=<span class="hljs-string">'tight'</span>)</pre></div><p id="b8f7">So, let’s see results saved as pictures per each category.</p><p id="fd22">Gold:</p><figure id="f70d"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*P3O09lA3lIUlQlzx9dUivg.png"><figcaption></figcaption></figure><p id="148b">Silver:</p><figure id="b938"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*9J3LHpp51Z0vAuXQ-wn0NA.png"><figcaption></figcaption></figure><p id="ad9a">Crypto:</p><figure id="c6f5"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*pm83kjYQIxniNba31YkYMA.png"><figcaption></figcaption></figure><p id="8fd6">Energy:</p><figure id="9455"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*JKX9t_PYrme4LzVKvrr2Xg.png"><figcaption></figcaption></figure><p id="d00f">and Copper:</p><figure id="9cc7"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*UNeY_B66NlOcihw-9ga_Lg.png"><figcaption></figcaption></figure><p id="c0b9"><b>Conclusion</b></p><p id="966f">This analysis can be extended and customized based on specific requirements and preferences, such as adding more tickers, adjusting the time range, or incorporating additional performance metrics. Happy analyzing!</p><p id="cc53"><b>As always, the full code is available on GitHub for paid subscribers. If you wish to access the complete code, please subscribe to support my work. Thank you.</b></p></article></body>

Analyzing Stock Performance Across Key Sectors (Crypto, Metals, Energy, Weed)

As part of developing a backtesting framework, we need to plot time series data and evaluate the performance of various strategies. In this post, I will demonstrate how to use both the Trading framework and functions from the qlib library to fetch historical stock data, calculate performance metrics, and visualize the results for a selection of tickers across various sectors, including Crypto, Copper, Silver, Gold, Energy, and Weed.

We often hear about trending stocks, equities, or commodities being good investment opportunities. Regardless of the selection process, sometimes it’s worth checking the performance of these assets, especially if we value someone’s opinion. Although this code is quite simple, this post will showcase the capabilities of our built library (quant-lib) and provide a quick way to assess the performance of trending assets.

Today morning, I read about various themes driving the market:

“Themes Driving the Market Right Now Crypto ~ $COIN $MSTR $IBIT $MARA Copper ~ $COPX FC 0.00%↑ X $SCCO Silver ~ $AGQ $PAAS $SVM $AG $MAG Gold ~ $GFI $EGO $AU $AEM Energy ~ $XOM $CVX $OXY$CVE Weed ~ $TLRY ACB 0.00%↑ CGC 0.00%↑”

So, I decided to check the performance of these tickers and write a general function for similar checks in the future.

Let’s start defining a dictionary called tickers that maps sector categories to their respective stock tickers, we want to analyze. This allows us to easily organize and iterate over the tickers for each sector further:

# Define the tickers and categories
 tickers = {
  "Crypto": ["COIN", "MSTR", "IBIT", "MARA"],
  "Copper": ["COPX", "FCX", "SCCO"],
  "Silver": ["AGQ", "PAAS", "SVM", "AG", "MAG"],
  "Gold": ["GFI", "EGO", "AU", "AEM"],
  "Energy": ["XOM", "CVX", "OXY", "CVE"],
  "Weed": ["TLRY", "ACB", "CGC"]
 }

Now, we can create a function that takes a sector name as input, fetches the historical data for the corresponding tickers, calculates performance metrics, and visualizes the results. This function will allow us to quickly check the performance of any sector in the future.

# Fetch data for each category
 for category, category_tickers in tickers.items():
  category_data = {}
  legend_labels = []
  for ticker in category_tickers:
   logger.info(f"Fetching data for {ticker}...")
   try:
    data = await dc.equities.async_get_ohlcv(
     tickers=[ticker],
     exchanges=["US"],
     granularity="1d",
     period_starts=[start_date],
     period_ends=[end_date],
     source='eod'
    )
    if data:
     df = data[0]
     if 'datetime' in df.columns and not pd.api.types.is_datetime64_any_dtype(df.index):
      df['datetime'] = pd.to_datetime(df['datetime'])
      df.set_index('datetime', inplace=True)
     category_data[ticker] = df['close']
     logger.info(f"Data for {ticker} fetched successfully.")
     
     # Calculate changes and append to legend labels
     changes = calculate_changes(df['close'])
     change_label = ', '.join([f"{k}: {v:.2f}%" for k, v in changes.items()])
     legend_labels.append(f"{ticker} ({change_label})")
   except Exception as e:
    print(f"Error fetching data for {ticker}: {e}")

The full code is available on GitHub for paid subscribers at https://quantjourney.substack.com/

If you wish to access the complete code, please subscribe to support my work. Thank you.

So now we will plot the historical data, calculate performance metrics, and save the plots as PNG files for each sector.

In the example usage section, we iterate over each sector and its corresponding tickers. For each sector, we fetch the historical data, calculate the performance metrics, print the metrics, and generate and save the plot as a PNG file.

The performance metrics are calculated as follows:

  • 1W: Average percentage change over the last 5 trading days (1 week)
  • 1M: Average percentage change over the last 21 trading days (1 month)
  • 3M: Average percentage change over the last 63 trading days (3 months)
  • 6M: Average percentage change over the last 126 trading days (6 months)

The plots will be saved as PNG files with the naming convention “{sector}_performance.png”.

# Plotting line chart
   fig = pl.plot_line(df=combined_df,
          legend_labels=legend_labels,
          legend_stats=put.LegendStats.NONE,  # Adjust as needed
          title=f"{category} - Closing Prices and Performance (Past Year)",
          ylabel='Closing Price',
          legend_title="Ticker (Change: 1W, 1M, 3M, 6M)",
          x_date_freq='M',
          fontsize=8
          )
   if fig is not None:
    fig.savefig(f"{category}_closing_prices.png", format='png', dpi=300, bbox_inches='tight')

So, let’s see results saved as pictures per each category.

Gold:

Silver:

Crypto:

Energy:

and Copper:

Conclusion

This analysis can be extended and customized based on specific requirements and preferences, such as adding more tickers, adjusting the time range, or incorporating additional performance metrics. Happy analyzing!

As always, the full code is available on GitHub for paid subscribers. If you wish to access the complete code, please subscribe to support my work. Thank you.

Gold
Silver
Cryptocurrency
Crypto
Python
Recommended from ReadMedium