/r/algotrading

Photograph via snooOG

A place for redditors to discuss quantitative trading, statistical methods, econometrics, programming, implementation, automated strategies, and bounce ideas off each other for constructive criticism. Feel free to submit papers/links of things you find interesting.

/r/AlgoTrading place for redditors to discuss quantitative trading, statistical methods, econometrics, programming, implementation, automated strategies and to bounce ideas off each other for constructive criticism. Feel free to submit papers/links of things you find interesting.

This sub is not for the promotion of your blog, youtube, channel, or firm.

*THIS DOES NOT CONSTITUTE INVESTMENT ADVICE, USE AT OWN RISK*

*SEARCH THE SUB/GOOGLE/STACK OVERFLOW BEFORE ASKING QUESTIONS FOUND ON THE FRONTPAGE OF THE ABOVE WILL BE REMOVED*

Good places to start with code examples:

STRATEGY
Big-Intro to quantstrat and trading systems
R & quanstrat video tutorial
portfolio optimization
Great blog with more advanced code and ideas from the "systematic investor" note: code here does not follow standard R conventions
Blog here with strategy examples from Ilya Kipnis
quantivity paper feed
How to learn algortihmic trading
Strategy books thread
Quantopian Lecture Series

How to get historical data for free
Daily Bar data for Stocks
Tick level Forex Data
Historical Bar Data for Crypto Currencies - Binance
Historical Bar Data for Crypto Currencies - BitMEX

Charts with live feeds for global exchanges
TradingView HTML5/web based charts

Math/Stats/Machine Learning
Introduction to Statistical Learning with applications in R
Elements of Statistical Learning

Production Systems
aleph-null: open source python ib
quick-fix
node.js to ib api
subreddit thread on systems

Paper Feeds
Quant news feed
Quantocracy blog feed

Live Chat Rooms

Official Discord: Official Discord for /r/AlgoTrading

R Language in Finance Discord: Discord for R Programming for Financial Applications

R Language in Finance Discord IRC Version sync'd to discord irc.libera.chat #r-finance

Book Recommendations List of recommended books on Algo Trading

Big post of recommended books

Do's:

  • Submit Interesting papers, blog postings
  • Code/packages we love these!
  • strategies (even if they don't work a negative result is still useful)
  • Read the sidebar (intro to quantmod/quantstrat) will answer questions on how to download data, chart, build test and validate strategies.
  • Have a technical informative discussion
  • Submit business links and questions (e.g. contractual issues,licensing etc)
  • Submit tax optimization links and questions
  • Submit infrastructure links and questions
  • Submit compliance/regulatory links and questions

Don'ts:

  • Submit paysites for indicators/software/systems/whatever
  • Submit things without methodology or at least some guidance
  • Flame on other users, we're all here to learn so be constructive in your criticism
  • Downvote without posting why, Give your constructive criticism or don't critique at all
  • Post asking how to get started without viewing the links on the sidebar, or reviewing previous posts in the subreddit
  • Ask for career advice there is /r/financialcareers for that
  • Ask for educational advice, as each case is special and your thread has no value for practitioners, there are rankings of quant programs, computational finance, machine learning and stats out there
  • Submit software that is proprietary and not open source
  • Submit links/posts that are for the sole purpose of generating referrals/sales/$$, if it is not informative and useful then it does not belong here, shilling your products is not appreciated.
  • Submit posts that are summaries of other posts without additional content
  • Submit videos without accompanying assets (e.g. code)

FAQ's:

  • Q: "Hi guys im new how do I get started?"
  • A: Read the sidebar, if you have a precise specific question please google it and should you not find the answer then you can ask here.

  • Q: I am a student and want to know what courses to study to get into algo trading?

  • A: Algotrading is at the intersection of statistics/computer science/machine learning/mathematics/finance/economics.

  • Q: Where should I apply for a job?

  • A: /r/financialcareers for that

  • Q: I have bug ABC with language XYZ ?

  • A: http://quant.stackexchange.com/ or http://http://stackoverflow.com/

If you get spam filtered, message the mods and we will review and unblock as required.

/r/algotrading

1,762,386 Subscribers

12

Alpaca VS Any Broker API

I know Alpaca used to be ideal. I had used them a while back because their API was free/SUPER cheap, and the other brokerages didn't offer much if anything at all as far as an API for traders.

I had opened a new Alpaca account. Just out of past knowledge and built out a new algo.

When it came time to implement order handling.. I got curious and started looking elsewhere.

It seems. Pretty much everyone. Even the brofintech brokerages have well polished and CHEAPER APIs.

So my question to you sages is this.

  • IS Alpaca still the king brokerage for little dude algos/trading automation?
14 Comments
2024/12/01
20:36 UTC

8

Licensing or selling pathways for algos?

Curious, are there any licensing or selling pathways for solo/retail quants who have built something that brings value? Ex: if I had an algo that accurately predicts the probability of a stock going long with 65% precision. Could I tap into a network to license? Any prop firms I could reach out too and broker a deal? Any other pathways?

For the naysayers, who will say if you had this why not use it yourself. I'm a problem solver(not a trader) who has a vast skillset in programming, statistics, analytics and machine learning.(should have probably been a quant, life didn't offer me that pathway). So I say all that to say this, the challenge of finding a solution in a complex environment was what intrigued me. Now I have an asset that brings value I'd prefer to license to someone's whose job is to be a trader.

This is a serious inquiry, thanks in advance.

16 Comments
2024/12/01
18:33 UTC

16

Anyone coding to pass on a system to others who are non-coders?

Background: traded options for over 25 years, career in finance. No one in my immediate family have the capacity to take over my trading or internalize my experience and knowledge. Need to code something more complex than "trade X strike on Y stock each Z period". The strategies are low frequency.

Issue: can not code, but I can learn, and I need to code in an environment which will not deprecate, so that once set up, they can just monitor the trades or at the very least, get alerts with clear instructions.

Question: what does the brain trust here think about the environment, set up, etc.? I use Schwab, so I think there is good enough documentation for their API, but what if that deprecates? Does it come to me teaching them to trade point and click with rigid instructions?

Thanks to all in advance.

70 Comments
2024/12/01
12:27 UTC

49

What programming language did you go for?

Hi!! Just like the title says, I am curious about what was your preferred programming language to implement your logic, do the backtesting, build for "production" to start trading etc.

I was thinking about giving Rust a try on this, since its memory safety and borrow system paired with its good performance could be key in these applications. What do you think?

110 Comments
2024/12/01
08:58 UTC

10

Book recommendations

Hi folks, I have worked on hardware abstractions, infra tooling for data center platforms using c++, python in leading companies in this field. I am looking for a career switch into HFTs with two main intentions: Money and my interest in socket programming and concurrency. I have a computer science degree with decent math skills.

Please suggest books related to c++ and finance that I can start reading to gain insights into this field.

6 Comments
2024/12/01
06:29 UTC

15

Seeking feedback on rebalancing strategy using Nelder-Mead weighting on top 5 SPY stocks. Thanks in advance.

As the title says. Below is a high level analysis of the strategy -- it sounds all nice and good (thanks for being kind, ChatGPT), but I'm looking for feedback from real practicioneers.

Edit: Specifically - How sound is the hypothesis? And how might this be improved with other/better factors, a different universe and/or better risk management?

The KEY 5 SPY Strategy: Marrying Technical Efficiency with Fundamental Value

A Deep Dive into Modern Portfolio Selection Using KER and FCF Yield

2024 Performance of KEY 5 vs. SPY Buy + Hold

10-Yr Performance of KEY 5 vs. SPY Buy + Hold

10-Yr Performance of Equal Allocation to top 5 weighted SPY stocks vs. SPY Buy + Hold

Abstract

This examines the KEY 5 SPY Strategy, an adaptive approach to portfolio rotation that combines technical efficiency measurement (KER - Kaufman Efficiency Ratio) with fundamental value assessment (FCF Yield) to select and weight positions among the S&P 500's top constituents. We explore both the theoretical foundations and practical implementation details that make this strategy particularly effective in real-world trading conditions.

Hypothesis

The strategy posits that combining price efficiency (KER) with fundamental value (FCF Yield) identifies stocks with sustainable momentum. By measuring how efficiently price moves alongside a company's ability to generate free cash flow, we can select securities where technical trend and fundamental strength reinforce each other. The strategy hypothesizes that optimally / adaptively weighting these factors within the most liquid S&P 500 constituents produces superior risk-adjusted returns compared to single-factor approaches.

1. Introduction: Why This Strategy Matters

Let's start with a simple truth: most strategies that look great in backtests fall apart in live trading. What makes the KEY 5 SPY Strategy different? The answer lies in its adaptive combination of two factors that complement each other in ways that might not be immediately obvious.

Think of KER as your technical analyst with a physics degree - instead of drawing trendlines, it's measuring the actual efficiency of price movements. Meanwhile, FCF Yield plays the role of your fundamental analyst who doesn't care about stories or projections - just cold, hard cash generation relative to price. When these two analysts agree, something interesting tends to happen.

2. Technical Framework

2.1 Universe Selection

Rather than simply picking the largest S&P 500 components, the strategy:

  1. Filters constituents based on their weights in SPY
  2. Sorts by weight to identify the top candidates
  3. Selects from this filtered universe to ensure liquidity and representativeness

2.2 Position Sizing

Here's where things get sophisticated. Rather than equal weighting (which would be simpler), the strategy employs an optimized weighting scheme that:

  1. Calculates z-scores for both KER and FCF Yield
  2. Optimizes factor weights using the Nelder-Mead method
  3. Generates portfolio weights proportional to the combined, optimized factor scores
  4. Key detail: The optimization objective function is:-(np.dot(factor_zscores, weights) * trailing_return).sum()

This means it's explicitly considering the interaction between factor scores and recent performance.

3. The Factors: A Deeper Look

3.1 Kaufman Efficiency Ratio (KER)

Let's talk about what KER really measures. Imagine you're walking through a city. You could measure the distance you've traveled in two ways:

  1. The straight-line distance from start to finish (net directional movement)
  2. The actual distance you walked following streets and turns (total price movement)

KER is essentially comparing these two measurements in price action. A high KER means price is moving efficiently in one direction - like taking a straight path through the city. A low KER means price is moving inefficiently - like wandering through back alleys.

Implementation detail from the code:

Efficiency = abs(Close[n] - Close[0]) / Sum(abs(Close[i] - Close[i-1]))

The strategy calculates this over a 21-day lookback period by default.

3.2 Free Cash Flow Yield

FCF Yield might seem like a simple value metric, but its power lies in what it doesn't measure. Unlike earnings yields or other traditional value metrics, FCF Yield:

  • Is harder to manipulate through accounting choices
  • Captures actual cash-generating ability
  • Naturally penalizes companies that require heavy ongoing capital investment
  • Rewards capital-light businesses with strong market positions

4. The Secret Sauce: Integration Method

The integration of these factors involves several sophisticated steps that aren't immediately obvious:

4.1 Z-Score Normalization - The code normalizes both factor values to z-scores, ensuring comparability across different scales:

factor_zscores = (factors_df - factors_df.mean()) / factors_df.std()

4.2. Return Integration - A unique aspect is how the strategy incorporates trailing returns:

trailing_return = price_df.pct_change(self._lookback-1).iloc[-1]

This creates a natural momentum overlay that helps confirm factor signals.

4.3 Optimization The Nelder-Mead optimization with bounds ensures:

  • Factor weights remain between 0 and 1
  • The solution maximizes factor effectiveness
  • The weights adapt to changing market conditions

5. Risk Management

The strategy employs the following risk management layers:

  1. Position Concentration By limiting selection to 5 positions, the strategy maintains focus while ensuring sufficient diversification.
  2. Monthly Rebalancing Regular rebalancing ensures the portfolio doesn't drift from its intended factor exposures.

Note: While the code includes a trailing equity stop at 90% of peak equity, this feature is not used in the live implementation of the strategy.

6. Why It Works: A Behavioral Perspective

The strategy's effectiveness can be attributed to several behavioral factors:

  1. Efficiency Recognition Markets tend to underreact to improvements in business efficiency. KER helps identify when this recognition is occurring in a sustained way.
  2. Quality Migration High FCF Yield companies often experience gradual multiple expansion as their quality becomes more widely recognized.
  3. Momentum Confirmation The integration of trailing returns helps confirm when the market is actively repricing these factors.

7. Conclusion: Why This Matters

The KEY 5 SPY Strategy represents a sophisticated yet implementable approach to portfolio rotation. Its success stems from:

  1. The complementary nature of its chosen factors
  2. Sophisticated factor integration and weighting
  3. Sufficient risk management
  4. Focus on highly liquid securities

More importantly, it demonstrates how combining traditional fundamental factors with technical efficiency measures can create a more robust investment process than either approach alone.

The strategy's use of optimization and factor integration techniques shows how modern quantitative methods can enhance traditional factor investing approaches while maintaining practicality and interpretability.

Note: This document represents an academic analysis of the strategy's structure and theoretical underpinnings. Actual trading results may vary based on market conditions and implementation details.

15 Comments
2024/11/30
23:43 UTC

78

Backtest results too good to be true - What is wrong with my strategy?

I am testing a simple option trading strategy and getting pretty good results, but since I'm a novice I'm afraid there must be something wrong with my approach.

The general idea of the strategy is that every Friday, I will buy the option expiring in one week that has the highest expected payoff (provided there is one with positive EV). I compute the expected payoff with a monte carlo simulation.

Here's what I'm doing in detail. Given a ticker, at each date t:

  1. Fetch the last 2 years of prices for that ticker
  2. Compute mean and std of returns
  3. Run a monte carlo simulation to get the expected stock price in one week (t+7)
  4. Get the options chain at time t. For each option in the chain, compute the expected payoff using the array of prices simulated in (3).
  5. Select the option with the highest expected payoff, provided there is one with a positive EV. The option price must also be below my desired investment size. It can be either call or put.
  6. Then fetch the true price at time t+7 and compute the realized payoff

I have backtested this strategy on a bunch of stocks and I get pretty high returns (for large/mega cap stocks a bit less, but still high). This seems too simple to make sense. Provided the code I wrote is not the problem, is there anything wrong with the theory behind this strategy? Is this something that people actually do?

80 Comments
2024/11/30
20:29 UTC

7

Dedicated Servers vs VPS

Hey guys!

I would like to have your opinion regarding a setup I am putting together to run optimizations in MetaTrader 5.

Which service do you think I should subscribe to, a dedicated server or a VPS? The goal is to leave this machine performing optimizations 24/7.

It is important to remember that the most important variable for running optimizations in MetaTrader 5 is the number of processor cores/threads.

I found this solution, but I have no idea of ​​the price, whether it is expensive or cheap. πŸ‘‡

Netcup Root Server β€” https://www.netcup.com/en/server/root-server

Nectcup VPS β€” https://www.netcup.com/en/server/vps

Other information: 1) I will access the service remotely, using a MacBook. 2) I need the server to be Windows, to run MetaTrader 5 and other tools natively.

Please bear with me in this infrastructure part, I have no experience. πŸ˜‚

β€”

Edit 1: The setup I'm building will not be for trading, but rather for optimizations in MetaTrader 5. Latency is not important β€” as I said in the post β€” what I need are cores/threads.

Edit 2: To give you a little more context, rest assured, I know exactly what I'm doing, it's what I do for a living. I've always done my strategy mining and evaluation/validation locally, both for myself and for investment funds and assets that I provide services to. However, I recently signed a new contract to create some portfolios for a fund where, through a clause, I have to share the entire strategy mining process with the fund manager. That's why the setup needs to happen on a VPS/Dedicated Server.

35 Comments
2024/11/30
19:05 UTC

7

QuantConnect Tick Data Volume doesn't align with other data sources

I'm comparing the total daily volume, aggregated from the Tick data with other data sources like finviz, tradingview, and in some cases CME. The aggregate volume numbers never align with any of the other data sources, which generally align with each other. Here's the code I'm using to aggregate:

public class RetrospectiveTanButterfly : QCAlgorithm
{
   private Dictionary<Symbol, SymbolData> _symbolData;

 public override void Initialize()
 {
    SetStartDate(2021, 9, 16);    // Set Start Date
    SetEndDate(2021, 9, 20);      // Set End Date
    SetCash(100000);              // Set Strategy Cash

    _symbolData = new Dictionary<Symbol, SymbolData>();

    var tickers = new List<string> { "ESBA" };
    foreach (var ticker in tickers)
    {
        var symbol = AddEquity(ticker, Resolution.Tick).Symbol;

        var symbolData = new SymbolData
        {
            BidPrice = Securities[symbol].BidPrice,
            AskPrice = Securities[symbol].AskPrice
        };

        _symbolData[symbol] = symbolData;
    }
}

public override void OnData(Slice data)
{
    foreach (var kvp in _symbolData)
    {
        var symbol = kvp.Key;
        var symbolData = kvp.Value;

        if (!data.Ticks.ContainsKey(symbol)) continue;

        var ticks = data.Ticks[symbol];
        foreach (var tick in ticks)
        {
            if (tick.TickType == TickType.Quote)
            {
                if (tick.BidPrice != 0)
                    symbolData.BidPrice = tick.BidPrice;

                if (tick.AskPrice != 0)
                    symbolData.AskPrice = tick.AskPrice;
            }
            else if (tick.TickType == TickType.Trade)
            {
                symbolData.TotalVolume += tick.Quantity;
                symbolData.today = tick.EndTime;
            
            }
        }
    }
}

public override void OnEndOfDay(Symbol symbol)
{
    if (!_symbolData.ContainsKey(symbol)) return;

    var symbolData = _symbolData[symbol];
    Debug($"{symbol.Value}'s total volume is {symbolData.TotalVolume} for {symbolData.today}");

    symbolData.Clear();
   }

}

Anyone have any experience with QuantConnect's Tick data and volume numbers? I've found a few threads where people reported similar results, but no resolution.

2 Comments
2024/11/30
19:00 UTC

5

feedback on order slicing in python

hi all, I have a more technical question about order slicing with python. The high level idea is I use IB TWS python API, I was initially using MKT order so it got filled instantly, but after scaling up I hv noticed a higher price slippage so I made the below functions

the function itself check every 0.001 sec, if the internal order manager position (orderPosition) != filledPosition(real position executed on IB), then I amend the price to the new mid price (ps the instrument I trade did not hv mid price price type)

however I am not a technical expert but I have read python is performing quite badly on multithreading, and also the time.sleep() may not be the best way to do a regular checking on order positon

would be very grateful to have you all's feedback

code:

    def order_sender():
        global filledPosition, orderPosition, midPrice
    
        while True:
            if filledPosition != orderPosition:
                difference = orderPosition - filledPosition
                amend_order(order, midPirce)
            
            time.sleep(0.001)

// IB TWS api call back

    def updateMktDepth(self, reqId: TickerId, position: int, operation: int,
                       side: int, price: float, size: Decimal):
        global midPrice
        global bestBidList
        global bestAskList
        super().updateMktDepth(reqId, position, operation, side, price, size)
        if side == 1:
            bestBidList[position] = (price, size)
        else:
            bestAskList[position] = (price, size)

        if (len(bestBidList) > 0 and len(bestAskList) > 0):
            midPrice = (bestBidList[0][0] + bestAskList[0][0]) / 2

    def orderStatus(self, orderId:OrderId , status:str, filled:Decimal,
                    remaining:Decimal, avgFillPrice:float, permId:int,
                    parentId:int, lastFillPrice:float, clientId:int,
                    whyHeld:str, mktCapPrice: float):
        global filledPosition
        print("[orderStatus] orderId:", orderId, "|Status:", status, "|Filled:", filled, "|Remaining:", remaining, "|lastFillPx:", lastFillPrice, "|avgFillPx:", avgFillPrice)
        if not avgFillPrice == 0:
            filledPosition = filledPosition + filled
6 Comments
2024/11/30
18:20 UTC

8

Profitable Strategy - Can Pinescript be Automated for Options?

I have a brief background in computer science and got to work about a year ago coding a strategy through TradingView's Pinescript. For the past 12 or so months I've had the bot running, it has proved very profitable (achieving my expected +EV of 6% per 100 trades while taking over 1000 trades annually). However, I'm getting tired of sitting behind my screen all day waiting to place the trades.

I also have to be pretty quick with the entries and exits - and feel a bot would do substantially better than me in quickly entering exiting contracts. (No crazy frequency, however - I average 6 trades a day).

Is there anyway to take my Pinescript strategy and automate it so that a bot can enter and exit desired SPY options contracts? I always choose the closest in-the-money, 1 DTE contract - so perhaps this would help with simplicity?

Like I said - my strategy is very profitable (and forward looking). But, it would be nice if I didn't have to sit at my screen all day waiting to take trades.

Thank you for any help.

Edit: For clarification - currently, I am manually entering trades (SPY 1DTEs) on my phone through Robinhood. Simply using Tradingview for charting / entry+exit signals.

18 Comments
2024/11/30
15:40 UTC

16

How do you choose instruments to TrendFollow?

I've been testing various trend following strategies, they perform well on some stocks and does not on some stocks.

I decided to test on index rather than individual stocks. Some highly profitable trades are spanning for over 6 months or an year. Only way I know to trend follow on indices are to trade their Future contracts, but the farthest contracts available here in India are 3 months away, meaning I cannot take trades that spans over 3 months. How do I tackle this? Sell the contract and roll it over to the next farthest contract?

I can trend follow on stocks without the issue I stated above, because I will just buy and hold the stocks until it hit my target or stoploss. But there are over 4000 individual stocks to choose from, honestly it is overwhelming, testing on subset of 50 or 100 of them and seeing some perform well at certain period and some perform worse. I don't have a good system to take an educated guess to pick a stock to follow a trend.

Things I've tried -

My strategy is pretty basic, testing a MA Cross Over.

Wait for cross over to last at least 5 bars once crossed.
Check ADX values to be at a certain level.
Check super trends.
More and more

Anything that I try ends up proving me this could be a zero sum game.

Any directions on picking the right instrument would really help me move forward.

For what it's worth, the tools I use are just Python.

Thanks.

8 Comments
2024/11/30
07:35 UTC

22

Ib_insync vs IBKR API

I'm wondering what you all recommend for IBKR to build a system to make automated trades with python? I'm experienced with python from a data perspective but not experienced from a web/API/event perspective.

ib_insync has been archived due to the author's passing. ib_async, it's successor seems to have less hands to make updates: https://github.com/ib-api-reloaded/ib_async/discussions/92

Is worth the risk to use ib_async/in_sync for ease of use even though it might not be supported? Or, should I bite the bullet and figure out the official ibkr API?

For context, I'm just looking to execute 10-100 trades per day at/near open and closing them out at/near close

23 Comments
2024/11/30
05:55 UTC

3

Stocks with options on the market

I spent an ungodly amount of time trying to find a website with this data to have the clearing house have a quick and easy button to get it.

https://www.theocc.com/market-data/market-data-reports/series-and-trading-data/directory-of-listed-products

Hopefully if someone tries to google
"List of stocks with options" it will lead them here

it's free and curated.

8 Comments
2024/11/29
03:15 UTC

40

I invite you guys to try the `tradingview-screener` release candidate!

Hey y'all, about to release version `3.0.0` but wanted to get some feedback before, so please try it out and let me know what you think.

to try it:
```
pip install tradingview-screener==3.0.0rc1
```

The full changelog can be found here:
https://github.com/shner-elmo/TradingView-Screener/discussions/56

Updated docs:
https://shner-elmo.github.io/TradingView-Screener/dev/tradingview_screener.html

10 Comments
2024/11/29
14:29 UTC

7

A little help for a newbie intern :)

firstly happy thanksgiving, I would like to know if its possible for a brokerage to make its own algos like VWAP TWAP and POV. Currently we are a brokerage that buys (I am not sure if we pay them for each order) but we buy it from a market maker. I am total newbie in this industry but would definitely like to know if there is a possibility if we can make those algos and use them on our clients rather than us buying it from market maker. If I am wrong pls dont cook me up on comments rather pls help. Thanks and have a great weekend !

9 Comments
2024/11/28
23:02 UTC

20

Looking for Feedback on My Trading System: Is My Equity Curve and unrealistic profits Red Flags?

Hi all.

Im looking for some feedback on my system, iv been building it for around 2/3 years now and its been a pretty long journey.Β 

It started when came across some strategy on YouTube using a combination of Gaussian filtering, RSI and MACD, I manually back tested it and it seemed to look promising, so I had a Trading View script created and carried out back tests and became obsessed with automation.. at first i overfit to hell and it fell over in forward tests.

At this point I know the system pretty well, the underlying Gaussian filter was logical so I stripped back the script to basics, removed all of the conditions (RSI, MACD etc), simply based on the filter and a long MA (I trade long only) to ensure im on the right side of the market.

I then developed my exit strategy, trial and error led me to ATR for exit conditions.

I tested this on a lot of assets, it work very well on indexes, other then finding the correct ATR conditions for exit (depending on the index, im using a multiple of between 1.5 and 2.5 and period of 14 or 30 depending on the market stability) – some may say this is overfit however Im not so sure – finding the personality of the index leads me to the ATR multiple..Β 

Iv had this on forward test for 3 months now and overall profitable and matching my back testing data.

Things that concern me are the ranging periods of my equity curve, my system leverages compounding, before a trade is entered my account balance is looked up by API along with the spread to adjust the stop loss to factor the spread and size accordingly.Β 

My back testing account and my live forward testing account is currently set to Β£32000 at 0.1% risk per trade (around Β£32 risk) while testing.Β 

This EC is based on back test from Jan 2019 to Oct 2024, covers around 3700 trades between VGT, SPX, TQQQ, ITOT, MGK, QQQ, VB, VIS, VONG, VUG, VV, VYM, VIG, VTV and XBI.

Iv calculated spreads, interest and fees into the results based on my demo and live forward testing data (spread averaged)Β 

Also, using a 32k account with 0.1% risk gaining around 65% over a period of 5 years in a bull market doesn’t sound unreasonable until you really look at my tiny risk.. its not different from gaining 20k on a 3.2k account at 1% risk.. now running into unrealistic returns – iv I change my back testing to account for a 1% risk on the 32k over the 5 years its giving me the unrealistic number of 3.4m.. clearly not possible on a 32k account over 5 years..Β 

My concerns is the EC, it seems to range for long periods..Β Β 

At a bit of a cross roads, bit of a lonely journey and iv had to learn everything myself and just don’t know if im chasing the impossible.Β 

Appreciate anyone who managed to read all of this!Β 

Β EDIT:

To clarify my tiny Β£32 risk.. Β I use leveraged spread betting usingΒ IG.com - essentially im "betting" on price move, for example with a 250 pip stop loss, im betting Β£0.12 per point in either direction, total loss per trade is around Β£32, as the account grows, the points per pip increases - I dont believe this is legal in the US and not overly popular outside of UK and some EU countries - the benefits are no capital gains tax, down side is wider spreads and high interest (factored into my testing)

Β 

https://preview.redd.it/v6plzaqoso3e1.png?width=726&format=png&auto=webp&s=df8490f900b5733812c9ac787dd133a9cea7ab91

53 Comments
2024/11/28
18:42 UTC

17

quant infrastructure: home NAS w/ option to push to cloud?

I want to experiment with some alternative assets like maybe crypto or forex, which have nothing to do with my work in equities. I'm thinking of building a home NAS to experiment with. But I also want to consider the option if pushing the infrastructure to a cloud provider at later date.

I thinking I will test locally on a NAS/home infrastructure and if something seems interesting, I can go live on a cloud account later. I don't have a ton of experience building databases and certainly not maintaining them.

Any feedback is welcome on what is most reasonable.

* Should I use local docker containers and then push to S3, etc. when I want?

* Should I just straight install databases (postgres, etc.) on unbuntu and they will be easy to move to an S3 later?

25 Comments
2024/11/28
17:30 UTC

0

Happy Thanksgiving!

Anyone else's algo bought SPY options to double your money tomorrow like mine did?

Disclosure: this was actually a manual trade based on my frequentist algo. The algo can count. Can it predict? Here is the rage inducing original post: https://www.reddit.com/r/algotrading/comments/1go9hjw/a_frequentists_walk_down_wall_street/

Here is my trade:

https://preview.redd.it/zd5u4asrvm3e1.png?width=197&format=png&auto=webp&s=70c7d99a3e816c508060d37b940ef02777897383

Have a good day and Happy Thanksgiving!

EDIT: Here is my closing trade for 80% return.

https://preview.redd.it/308bh2u92v3e1.png?width=369&format=png&auto=webp&s=990fb624624cef30aa37df4a4033db3d9cad65b9

3 Comments
2024/11/28
12:52 UTC

0

How long does it take to learn pytorch

Hey all, I was wondering if you guys use pytorch for algo trading and backtesting. What languages are you guys even using most for Algorithimic trading. Is pytorch extremely helpful for algo trading? How long does it take to become good at it? I started about a month ago and feel like I’m still shit. If anyone has made any cool pytorch model for trading I would love to take a look at the source code to learn more about how to approach certain things. I learned pinescript and it was pretty helpful but not life changing. I want to make trading strategies that can at least give me enough entry opportunities to make me 100%-300% ROI per year consistently or at least give me more intraday and scalp entries to size up my long term portfolio.

32 Comments
2024/11/28
11:53 UTC

6

Best Options For Extremely Low Latency API Calls Into Coinbase One Advanced API?

I’ve developed and backtested an algorithm I’ve been working on for a long time and that backtest results are worth trying in the market.

I currently have backtested all available data for ETHUSD and BTCUSD on TradingView and outperform the benchmarks by a significant margin. The algo also outperforms stocks with high volume and volatility during trading hours, but I prefer to stick to Crypto for now due to no PDT regulations.

The timeframe is 30s so I need my trade execution to be as fast as possible. I plan to use CB One with their Advanced platform’s API and the subscription for $0 trading fees.

My only barrier to cross is developing a method to execute the trades within 1-2 seconds.

I can code this algo outside of TV, it’s just where I initially developed it.

Any suggestions would be appreciated.

8 Comments
2024/11/28
05:35 UTC

1

Best way to get trade-by-trade data?

I'm trying to get trade-by-trade data. Ideally, I would get a history of transactions, for example:

11.01 -- 4 shares trade at $1.04/share

11:02 -- 50 shares traded at $1.02/share

etc.

I'm looking for an affordable option -- preferably with an API so I can programmatically analyze it

25 Comments
2024/11/28
04:50 UTC

13

Options Historical Level 2 Data Vendors

Hi,

I understand these data must be expensive. Do you guys recommend any reliable data vendors for options historical level 2 data? Going back as far as it can. I've looked online but I figured you guys are experts in which ones to go after.

8 Comments
2024/11/27
23:30 UTC

2

Switching from Twelvedata, any better quality data feeds?

I'm looking to switch from Twelvedata. When I first got it the data feed was good, never noticed major differences. Now I'm noticing discrepancies. Any suggestions for a better data broker?

6 Comments
2024/11/27
22:30 UTC

21

Did something change in the market on early 2019? I've been backtesting an automated trading algo on QC and it works well on and after 2019 all included (covid, 2022, etc) , but the results from 2004 to 2019 are disappointing.

It is only trading very liquid stocks, per-minute resolution, from simple indicators... and pre-2019 vs post 2019 are completely different results. Is there are a change in the market? is there a change in the per-minute data? Thanks for any insight.

55 Comments
2024/11/27
16:54 UTC

0

I figured out a major intraday reason why price often reverses. I need a statistician/coder to help me determine R:R and probability.

I found the keyhole. I just need you to find the key(s) that fit. DM if qualified to backtest optimal R:R at specific price levels established during the day. This is very serious and could make both of us very profitable. I realize that most redditors are boneheads.

5 Comments
2024/11/27
13:30 UTC

126

Should I create a platform for retail traders to access tools professionals use?

As someone with experience in the finance industry, I’ve noticed that many tools used by professional traders are not accessible to retail traders. I’m considering creating a platform to bridge this gap, making professional-grade tools more available to retail traders, including those involved in algorithmic trading.

I’d love your input on a few things:

  1. Do you think there’s demand among retail traders for tools commonly used by professionals?

  2. How would you recommend marketing such a platform to algo traders or retail traders in general?

  3. Are there any features or considerations you think would make such a platform especially valuable?

I’m exploring this idea to help retail traders level the playing field and would appreciate your thoughts before proceeding. Thanks in advance for your insights!

63 Comments
2024/11/27
05:23 UTC

11

What dataprovider should I use for getting ^OMXH25 data?

Yahoo went behind a pay wall a while ago and I haven't been able to find data providet that is able to give data to All helsinki stocks and the OMXH25 index.

financialmodelingprep.com

works for just the Helsinki stocks but the index is behind a pay wall

8 Comments
2024/11/27
01:44 UTC

Back To Top