Member-only story

Coding a trend-following trading program with Python

Luiggi Trejo
2 min readDec 29, 2022

--

Photo by Kanchanara on Unsplash

I´ve written elsewhere (here for example) about the merits of trading when a trend is present. One big trend, when detected in its early stages, could be worth really big money if traded correctly.

Here is a simple trend-following system implemented in Python that can be used to trade financial assets:

# 2022 - JL Trejo

# Import necessary libraries
import pandas as pd

# Load the historical data for the asset you want to trade
data = pd.read_csv('asset_data.csv')

# Calculate the 200-day moving average of the asset's price
ma = data['price'].rolling(200).mean()

# Identify the trend by comparing the current price to the moving average
if data['price'].iloc[-1] > ma.iloc[-1]:
# If the current price is above the moving average, the trend is up
trend = 'up'
else:
# If the current price is below the moving average, the trend is down
trend = 'down'

# Take action based on the trend
if trend == 'up':
# If the trend is up, buy the asset
print('Buy')
else:
# If the trend is down, sell the asset
print('Sell')

This system uses a 200-day moving average to identify the trend in the asset’s price. If the current price is above the moving average, the trend is considered to be up, and the system will buy the asset. If the current price is below the moving average, the trend is considered to be down, and the system will sell the asset.

I´ll be writing more on the subject, my dear reader, so…

Stay tuned!

--

--

Luiggi Trejo
Luiggi Trejo

No responses yet