how to set up a python script to buy ETFs automatically every week

How to Set Up a Python Script to Buy ETFs Automatically Every Week

Imagine waking up every Monday morning knowing that your investment portfolio has already taken care of itself. While you were sleeping, a small piece of code quietly logged into your brokerage account and purchased another slice of a diversified fund, steadily building your wealth without you lifting a finger. This isn’t science fiction or something reserved for City traders with fancy algorithms—it’s something everyday people can set up from their laptop at home.

In this guide, we’re going to walk you through exactly how to set up a Python script to buy ETFs automatically every week. Whether you’ve never written a line of code in your life or you’re completely new to investing, we’ll break everything down into simple, manageable steps. By the end, you’ll understand not just the how, but the why—and you’ll be equipped to make informed decisions about whether this approach is right for you.

What Are ETFs and Why Automate Your Investments?

Before we dive into the technical bits, let’s make sure we’re all on the same page about what we’re actually buying and why automation makes sense.

Understanding ETFs in Plain English

ETF stands for Exchange-Traded Fund. Think of it as a basket containing tiny pieces of many different investments—shares in companies, government bonds, commodities, or a mix of everything. When you buy one unit of an ETF, you’re essentially buying a small portion of everything in that basket.

For example, a popular ETF like the Vanguard FTSE All-World ETF (ticker: VWRL) contains shares from over 3,500 companies across the globe. By purchasing just one unit, you instantly own a tiny piece of Apple, Shell, Toyota, and thousands of other businesses. This diversification is why ETFs are beloved by beginner and experienced investors alike—they spread your risk across many companies rather than betting everything on one.

The Magic of Pound Cost Averaging

When you invest a fixed amount regularly—say, £50 every week—you practice something called pound cost averaging. When prices are high, your £50 buys fewer units. When prices drop, your £50 buys more units. Over time, this smooths out the bumps of market volatility and means you don’t need to worry about timing the market perfectly.

This is precisely why learning how to set up a Python script to buy ETFs automatically every week can be so powerful. It removes emotion from the equation, eliminates the temptation to time the market, and ensures you stay consistent even when life gets busy.

Why Automation Beats Manual Investing

Let’s be honest—most of us have good intentions about investing regularly, but life gets in the way. You forget, you procrastinate, or you convince yourself that next week will be a better time to buy. Automation solves all of these problems:

  • Consistency: Your script runs regardless of whether you’re on holiday, stuck in meetings, or simply can’t be bothered
  • Discipline: Removes the emotional temptation to skip investments when markets look scary
  • Time savings: Once set up, you reclaim the mental energy spent thinking about when and how much to invest
  • Learning opportunity: Building this system teaches you valuable skills in coding and financial automation

Important Considerations Before You Start

Before we get into the exciting technical setup, we need to address some crucial points. This isn’t about dampening your enthusiasm—it’s about making sure you approach this responsibly and legally.

The Regulatory Landscape in the UK

In the United Kingdom, investment platforms must be authorised and regulated by the Financial Conduct Authority (FCA). This protection means your money is safeguarded up to £85,000 per firm through the Financial Services Compensation Scheme if something goes wrong with your broker.

When choosing a platform for automated trading, ensure they’re FCA-regulated and offer API access—the technical interface that allows your Python script to communicate with their systems. Not all brokers offer this, and some that do may have restrictions on automated trading or require approval.

Tax Considerations: ISAs and Capital Gains

Here’s where things get particularly interesting for UK investors. If you’re buying ETFs in a Stocks and Shares ISA, any gains you make are completely tax-free. You can invest up to £20,000 per tax year into ISAs, and you won’t owe HMRC a penny on profits, dividends, or interest.

However, most ISA providers don’t offer API access for automated trading. This means you might face a choice: automate your investments in a General Investment Account (GIA) where you’ll potentially owe Capital Gains Tax on profits exceeding your £3,000 annual allowance, or manually invest in an ISA to keep things tax-free.

For many people starting out with modest weekly investments, the convenience of automation might outweigh the tax benefits, especially if your total gains are unlikely to exceed the CGT allowance. But this is a personal decision worth thinking carefully about.

Investment Risk Warning

We need to be absolutely clear: investing in ETFs carries risk. The value of your investments can go down as well as up, and you might get back less than you put in. Past performance doesn’t guarantee future results. The automation we’re discussing doesn’t eliminate risk—it just makes the process of accepting that risk more systematic.

Only invest money you can afford to lose, and consider speaking with a qualified financial adviser if you’re unsure whether investing is right for your circumstances.

Choosing the Right Platform for Automated ETF Investing

Not all investment platforms are created equal when it comes to automation. Here’s what to look for and some options available to UK investors.

What to Look for in a Broker

  • API availability: The platform must offer an Application Programming Interface that allows external programs to place trades
  • FCA regulation: Non-negotiable for your protection
  • Reasonable fees: Watch out for per-trade commissions that could eat into small weekly purchases
  • Good documentation: Clear instructions for developers make your life much easier
  • Fractional shares: Ideally, you want to invest exact pound amounts rather than buying whole units

UK-Friendly Options to Consider

Trading 212: Popular among UK retail investors, Trading 212 has been developing API access and is FCA-regulated. They offer commission-free trading and fractional shares, making them ideal for small regular investments.

Interactive Brokers: A more professional platform with robust API support. They’re FCA-regulated and offer access to a wide range of global ETFs. Their API is well-documented and reliable, though the platform can feel overwhelming for beginners.

Alpaca: While US-based, Alpaca offers commission-free trading with excellent API support. UK residents can use their services, though you’ll need to consider currency conversion costs and tax reporting implications.

IG: A well-established UK broker offering API access through their IG Labs platform. They’re fully FCA-regulated with strong infrastructure, though their fee structure may not suit very small trades.

Step-by-Step Guide: Setting Up Your Automated ETF Buying Script

Now we’re getting to the heart of the matter. This practical step-by-step section will guide you through the entire process, even if you’ve never coded before.

Step 1: Install Python on Your Computer

Python is a free programming language that’s perfect for this kind of automation. Here’s how to get it:

  1. Visit python.org and download the latest version for your operating system
  2. Run the installer, making sure to tick the box that says “Add Python to PATH”
  3. Open Command Prompt (Windows) or Terminal (Mac) and type python –version to verify it’s installed

Don’t worry if this feels unfamiliar—millions of people have done exactly this, and there are countless tutorials available if you get stuck.

Step 2: Set Up Your Development Environment

You’ll need a text editor to write your code. We recommend Visual Studio Code—it’s free, beginner-friendly, and works on Windows, Mac, and Linux. Download it from code.visualstudio.com and install the Python extension when prompted.

Next, open your terminal and install the libraries you’ll need by typing:

pip install requests schedule python-dotenv

These packages help your script communicate with the internet, run on a schedule, and keep your sensitive information secure.

Step 3: Create Your Brokerage Account and Get API Credentials

Sign up with your chosen FCA-regulated broker and complete their verification process. This typically involves providing identification documents and proof of address—standard stuff under UK anti-money laundering regulations.

Once approved, navigate to their developer or API section and generate your API keys. You’ll typically receive two pieces of information:

  • API Key: Like a username that identifies your account
  • Secret Key: Like a password that authenticates your requests

Treat these credentials like your banking passwords—never share them or post them publicly.

Step 4: Write Your Python Script

Create a new file called weekly_etf_buyer.py and let’s build it piece by piece. The exact code will vary depending on your broker’s API, but here’s the general structure:

First, you’ll import the necessary libraries and load your credentials securely from an environment file rather than putting them directly in your code. Then, you’ll create a function that connects to your broker’s API and submits a buy order for your chosen ETF. Finally, you’ll use the schedule library to run this function every week at your preferred time.

The core logic looks something like this in plain English:

  1. Connect to the broker’s server using your API credentials
  2. Check that the market is open (ETFs trade during stock exchange hours)
  3. Calculate how many units you can buy with your weekly budget
  4. Submit a market order to buy those units
  5. Log the transaction details for your records
  6. Handle any errors gracefully and notify you if something goes wrong

Step 5: Test Thoroughly Before Going Live

Most brokers offer a paper trading or sandbox environment where you can test your script with fake money. This is absolutely essential—never skip this step. Run your script multiple times, check that orders are being placed correctly, and verify that error handling works when things go wrong.

Common issues to watch for include:

  • Insufficient funds in your account
  • Market being closed during weekends or bank holidays
  • API rate limits if you’re making too many requests
  • Network connectivity problems

Step 6: Deploy and Schedule Your Script

For your script to run automatically every week, it needs to be running on a computer that’s always on. You have several options:

Your own computer: Use Task Scheduler (Windows) or cron jobs (Mac/Linux) to run the script at set times. The downside is your computer needs to be on and connected to the internet.

Cloud services: Platforms like PythonAnywhere, AWS, or Google Cloud can run your script for you 24/7. Many offer free tiers sufficient for this use case. PythonAnywhere is particularly beginner-friendly and costs around £4-5 per month for reliable scheduled tasks.

Raspberry Pi: A small, cheap computer that can run continuously in your home. Initial cost around £50-70, but no ongoing fees.

A Real-World UK Example with Numbers

Let’s make this concrete with a scenario featuring Sarah, a 32-year-old marketing manager from Manchester.

Sarah decides to invest £100 per week into the Vanguard FTSE All-World ETF (VWRL), which tracks global stock markets. She sets up her Python script using Interactive Brokers, which charges no commission on ETF purchases.

Year One: Sarah invests £5,200 (52 weeks × £100). The market has some ups and downs, but her pound cost averaging means she buys more units when prices dip. By year-end, assuming average historical returns of around 7% annually for global equities, her portfolio might be worth approximately £5,550.

Year Five: Sarah has invested £26,000 in total. With compound growth (assuming the same 7% average annual return), her portfolio could be worth approximately £32,000—that’s around £6,000 in gains, completely hands-off.

Year Twenty: Now we see the real magic of consistency and compound growth. Sarah has invested £104,000 over two decades. With compound returns, her portfolio could potentially be worth over £250,000. The exact figure will depend on actual market performance, but the principle holds: small, consistent investments grow substantially over time.

Throughout all of this, Sarah’s weekly Python script simply did its job—buying a little more of the world’s economy each Monday morning while she got on with her life. This is the power of understanding how to set up a Python script to buy ETFs automatically every week.

Maintaining and Monitoring Your Automated System

Setting up your script isn’t quite the end of the journey. Here’s how to keep things running smoothly.

Regular Health Checks

Even the best automated systems need occasional attention. Set a reminder to check on your script monthly:

  • Verify that purchases are being executed as expected
  • Check your account has sufficient funds for upcoming purchases
  • review any error logs for issues that might need addressing
  • Ensure your API credentials haven’t expired

Keeping Records for HMRC

If you’re investing outside an ISA, you’ll need records for your tax return. Your script should log every transaction with the date, price, quantity, and total value. This makes calculating any Capital Gains Tax straightforward when the time comes.

Adjusting Your Strategy

Life changes, and your investment approach might need to change too. Perhaps you get a pay rise and want to increase your weekly amount, or you decide to add a second ETF for more diversification. The beauty of having built this system yourself is that you understand how to modify it.

Alternatives If Coding Isn’t For You

We’ve covered how to set up a Python script to buy ETFs automatically every week in detail, but let’s be honest—this approach isn’t for everyone. If the technical aspects feel overwhelming, there are simpler alternatives:

Standing orders to investment platforms: Many UK platforms like Vanguard Investor, AJ Bell, and Hargreaves Lansdown allow you to set up regular monthly investments automatically. You won’t have weekly flexibility, but it achieves similar results with zero coding.

Robo-advisers: Services like Nutmeg, Wealthify, and Moneyfarm automatically invest your money into diversified portfolios. They charge a small management fee but handle everything for you.

No-code automation tools: Platforms like IFTTT or Zapier might offer integrations with some brokers, though options are currently limited in the UK market.

Take

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top