How to Beat the Stock Market with Maths: A Dual Strategy Approach

martin vizzolini
Coinmonks
11 min readJul 27, 2023

--

Is it possible to discover a foolproof winning strategy? What if we could simultaneously bet on red and black in a casino roulette while keeping the losing bet intact?

Over the past two years, I embarked on an exhilarating journey to outsmart the market. It began with my relentless pursuit of leveraging artificial intelligence models, aiming to uncover hidden patterns that could unlock profitable trading strategies. However, despite my best efforts, the market remained an elusive adversary. It became apparent that a different approach was necessary — one that harnessed the power of probabilities.

Challenges Faced

From AI Models to Trading Bots
As I started into the world of trading, I experimented with various AI models in the hopes of gaining an advantage. While they showed promise, they often fell short of delivering consistent results. It became clear that relying solely on AI models was not enough to navigate the complexities of the market. I needed a more reliable and comprehensive solution.

The Bear Market Challenge
One of the significant obstacles I encountered trading to build a profitable trading bot was the unpredictable nature of bear markets. These market conditions made it exceptionally challenging to find a bot that could consistently generate profits. The strategies that worked well in bull markets failed to adapt effectively to the downward trends. It was a humbling realization that prompted me to rethink my approach.

Avoiding the ‘Break Even’ Point
Many times, the profit is so minimal that it becomes insignificant due to fees. It is essential to understand that a winning strategy does not always guarantee profitability. It becomes important to determine the profit threshold necessary to make the bot consistently profitable.

Managing the Risk of Ruin
The risk of ruin refers to the probability of losing the entire investment capital due to a series of consecutive losses. The algorithmic trading system takes into account the risk of ruin and aims to manage losses in a controlled manner.
The algorithm defines price levels at which trades will be closed if the market moves against the position. These levels are established based on technical analysis and aim to limit losses in each trade.

The Dual Strategy Market

Attacking the Problem from Both Sides:
To overcome the limitations of a unidirectional trading approach, I decided to adopt a dual perspective. I began simultaneously deploying bots that operated in both the long and short positions, all within the same cryptocurrency market. This approach allowed me to exploit opportunities regardless of market direction, effectively hedging against potential losses.

The advantage of operating two instances of the bot, one configured in “long” and the other in “short,” in the same market with the same cryptocurrencies lies in the ability to maximize trading opportunities and reduce the associated risk.

The main advantages of operating in both positions:

  • Risk diversification: By simultaneously trading in “long” and “short” positions, effective risk diversification is achieved. While one position may incur losses due to an unfavorable market movement, the other position may be generating profits from a movement in the opposite direction. When the profits generated from the positive trend outweigh the losses incurred from the opposite bot trend, we can secure a guaranteed profit.
  • The bot can capitalize on both bullish and bearish market trends. By covering both sides of the market, the opportunity to generate profits in any market condition is maximized.
  • Increased trading opportunities: By trading in both “long” and “short” positions, the bot can execute more trades compared to a unidirectional strategy.

The logic of the bot can be applied to multiple markets and various assets. For the following examples, we will focus on cryptocurrencies for ease of demonstration, but the same principles can be configured to apply to other markets like FOREX.

The Algorithm’s Strategy

At the core of my new trading algorithm lies a logic of (re-entries) and controlled losses. Instead of fixating on predicting price movements with unwavering certainty, the algorithm focuses on identifying favorable entry and exit points.

We can split the algorithm into three different parts:

1: Enhancing Trading Confidence

The strategy becomes even more powerful when we incorporate multiple coins into our trading approach. By analyzing various coins simultaneously, we can identify trades that inspire higher confidence. If one coin doesn’t meet our criteria for a confident trade, we can compensate for it by adding more trades from other coins that do meet our requirements.

By leveraging a multi-coin and a dual-positions approach, based on the most probable outcomes, the trading algorithm becomes a more robust and reliable tool for achieving consistent profits.

2: Identifying entry points

As a first step, we need to understand what we will refer to as entry points. These entry points are determined by the first algorithm in the chain, which is responsible for detecting these points, whether they are for selling or buying an asset. The form and effectiveness of this algorithm are key reasons why it works so well.

The initial analysis involves examining the price history and applying a Fourier transform function that maps the price to a coordinate on a plane.

Fourier transform applied in a time stock series

This algorithm detects when a trend changes within a predefined timeframe. When we use this as trend information, we can add logic to identify the candidate entry point we are looking for.

When applied to stock market data, and with the correct configuration, the Fourier Transform can help identify entry points by revealing the underlying cycles or patterns in the price movements.

Waves pattern of a fourier transform

The amplitude and phase of each wave indicate the strength and timing of each cycle. By analyzing these waves, the bot can identify the most significant cycles and use them to predict future price movements, providing potential entry points for trades.

It’s important to note that the Fourier Transform is just one tool in our strategy. While it’s powerful for identifying cyclical patterns, it’s not infallible. In fact, the algorithm may incorrectly identify a trend change about 20% of the time. However, these potential losses are mitigated by the implementation of a stop-loss measure. We anticipate that the bot will lose in these 20% of trades, and our strategy is designed to control the percentage of loss for each of these transactions.

Fourier Transform Trend Algorithm

And using the trend information we can find our candidate entry points

Entry Points Algorithm

3: Business logic

This is the point where we take action based on the signals generated by the previously discussed logic to determine if a point is suitable for a long or short trade, or possibly both. It’s here we decide if repurchasing is required or if we should increase our short position.

Unleashing the Potential

By combining statistical probabilities and careful risk management, the algorithm has unlocked the potential to achieve consistent profitability, even in the face of volatile market conditions.

The first graphic shows the trend entry points algorithm and the second one the executed buy/sell trades in a Long market in a period of 3 months.

Let’s try with multiple Assets

Bot in Long mode — 30 days of trades

By trading multiple coins against the same capital, we can exploit a wider range of market opportunities. Each cryptocurrency has its unique market dynamics and price trends. By analyzing and trading multiple coins, we can capture diverse market movements and trends, thereby increasing our chances of identifying profitable trades.

Is it possible to guarantee the profitability of our strategy?

While absolute certainty is elusive in the world of trading, we can significantly tilt the odds in our favor. Our approach leverages the power of probability, focusing on identifying re-entry points and capturing profits when the likelihood of success is high. We set our stop losses based on what’s happened before and what the market’s doing, which helps us avoid big losses. In essence, our strategy is rooted in the principle of capitalizing on the most likely to happen. That’s how we up our game.

How much profitable the Bot is?

I will share an example showcasing the results of the bot running two instances: one operating in the Long position, which may incur losses during a bearish trend, and another instance only operating in Short positions, which may be affected by a bullish market.

We will explore various scenarios to evaluate the bot’s performance. As demonstrated in the subsequent examples, there are periods where the short-term bot generates profits while the long-term bot incurs losses, and vice versa. This dual approach allows us to balance out the performance and maintain a steady profit trajectory

# Long Bot Instance
python src/live/fft_bot_trader.py \
--start_date=2020-11-1 \
--end_date=2021-11-11 \
--window_days=30 \
--coin_list=ARPA,XMR,OCEAN,CELO,LTC,ANT,TRX,XRP,OGN,CTXC,NMR \
--initial_capital=500 \
--order_size=20 \
--bot_type=long \
--umbral_rsi_down_first_force=true \
--umbral_rsi_up_first_force=true
# Short Bot Instance
python src/live/fft_bot_trader.py \
--start_date=2020-11-11 \
--end_date=2021-11-11 \
--window_days=30 \
--coin_list=ARPA,XMR,OCEAN,CELO,LTC,ANT,TRX,XRP,ZEC,EOS,RSR,REEF \
--initial_capital=500 \
--order_size=20 \
--bot_type=short \
--umbral_rsi_down_first_force=true \
--umbral_rsi_up_first_force=true

The key parameters to highlight are:

window_days: Cycle in which we reinvest our capital. (Compound)
bot_type: Indicates whether the bot will be operating in LONG or SHORT positions.
initial_capital: Initial Capital shared by all coins in the list
coin_list: List of coins that will concurrently participate in the bot instance and with which it will be trading.
Why do I use these specific list coins and not others? There are several answers to that, which might require another post to explain in detail. But in summary, these coins have demonstrated a strong correlation with the entry point recognition algorithm and perform well in both market directions. So far, I have identified approximately 20 coins that fulfill this function, while there are others that perform well only in one trend and some that are currently under testing. The number of coins must be related to the capital and order size, for a bot trading operating 12 coins we need between 15 and 20 order positions. (capital/order_size = order positions). The profit results will depend on a correct configuration of these parameters.

Backtesting Example 1

Long Bot Results

Change in capital for short positions Bot over time

The black dashed line represents the initial capital over time. This serves as a baseline to compare the performance of the trading bot. The colored lines represent the performance of each coin operating Long positions. Each colored line is calculated by applying the profits or losses from trading that coin to the initial capital. This means that the final result is the sum of these individual profits or losses.

If a colored line is above the black dashed line at any point, this means that trading that coin has resulted in a profit at that point in time.

Short Bot Results

Change in capital for short positions Bot over time

We can see more coins in losses for the bot operating in Short mode in this period of time, also we see another list of coins that generate profits. And, as we can see in the next graphic (red line) the bot operating in short positions did not achieve any significant profits, even though it was in loss most of the period. Why? because we were operating a bull market, but at the same time the bot was profiting in the opposite direction. The average profit of both bot instances (blue line) represents the combined result of our strategy.

Combined Bot Results

Results

Days: 374
Initial Capital:
$100
Final Capital:
$195,69

It’s interesting to note that the red and green lines often move in opposite directions. This is almost a natural behavior, one bot is making a profit (e.g., the market is trending in a direction favorable for that bot), the other bot might be making a loss, and vice versa. However, there are times when both bots can make a profit simultaneously, such as when the market is highly volatile. During these times, the avg profit (blue line) can increase significantly, indicating that both bots are performing well. This is the ideal scenario for our trading strategy.

Backtesting Example 2

Results

Days: 726
Initial Capital:
$100
Final Capital:
$235,33

In these results, we observe periods where the Short bot instance outperforms the average and others where it falls below. The same pattern is seen with the Long bot instance. They effectively balance each other out over time. The first year and a half show a significant capital increase, while the last six months have been relatively stable. These results are quite impressive, especially considering a two-year period.

Backtesting Example 3

In our final example, we’ll examine the results of running an additional instance of the algorithm with an identical configuration but initiated 10 days after the first one. This allows us to observe how the bot’s performance varies when launched on different dates.

Instance (1) Start on date: 2020–09–05

Results Instance (1)

Days: 1034
Initial Capital:
$100
Final Capital:
$339,29

Start on date: 2020–09–15

Results Instance (2)

Days: 1034
Initial Capital:
$100
Final Capital:
$395,12

We observe that the bot’s performance remains relatively consistent in both examples, with the primary objective being to ensure profitability, as indicated by the upward trajectory of the blue line!

Conclusion

The unique strength of this trading strategy bot lies in its ability to operate effectively in both directions of the market. Regardless of whether the market is trending bullish or bearish, the bot is designed to capitalize on these movements and generate profits.
This dual-direction operation allows us to remain profitable irrespective of the current market direction, making the most of every market condition.

I am exiting to validate these results in the live trading bot instance. Currently, I have an instance of the bot actively trading on an exchange. It’s been operational for 10 days now and the results have been truly impressive. The most crucial aspect was to ensure that the entry points and profit percentages in the live trading matched those from the backtesting. I am optimistic about this project and look forward to sharing the live results soon.

The next phase of this journey involves investigating the effective utilization of leverage to maximize profitability without significantly increasing risk. This involves finding a delicate balance between increasing leverage for higher returns and managing the associated losses when the trade is negative.

Finally, I would like to share a notable transaction executed by the bot trading Long positions in a real exchange, compared with the backtesting transaction results.

Back testing result
Live instance Bot real order results

To be continued..

Link to Part 2

--

--