Skip to content

Trade on EMA Crossover #586

Trade on EMA Crossover

Trade on EMA Crossover #586

Workflow file for this run

name: Trade on EMA Crossover
on:
schedule:
- cron: '*/5 * * * *' # Run this workflow every 5 minutes
env:
PYTHON_VERSION: "3.10"
MARKETWATCH_USERNAME: ${{ secrets.MARKETWATCH_USERNAME }}
MARKETWATCH_PASSWORD: ${{ secrets.MARKETWATCH_PASSWORD }}
GAME_NAME: "marketwatchapistrategieema"
jobs:
trade:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: ${{ env.PYTHON_VERSION }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install pandas
pip install marketwatch
pip install yfinance
- name: Run trading script
env:
USERNAME: ${{ env.MARKETWATCH_USERNAME }}
PASSWORD: ${{ env.MARKETWATCH_PASSWORD }}
GAME_NAME: ${{ env.GAME_NAME }}
run: |
python - <<EOF
import time
import os
import pandas as pd
from datetime import datetime
from marketwatch import MarketWatch
username = os.environ.get('MARKETWATCH_USERNAME')
password = os.environ.get('MARKETWATCH_PASSWORD')
game_name = os.environ.get('GAME_NAME')
marketwatch = MarketWatch(username, password)
def calculate_ema(price_series, periods):
return price_series.ewm(span=periods, adjust=False).mean()
def trade_on_crossover(df, game_name, stock_symbol):
short_term = df['EMA_20'].iloc[-1]
long_term = df['EMA_80'].iloc[-1]
prev_short_term = df['EMA_20'].iloc[-2]
prev_long_term = df['EMA_80'].iloc[-2]
if short_term > long_term and prev_short_term <= prev_long_term:
marketwatch.buy(game_name, stock_symbol, 100)
elif short_term < long_term and prev_short_term >= prev_long_term:
marketwatch.sell(game_name, stock_symbol, 100)
def trade_multiple_stocks(stock_symbols):
price_data = {symbol: [] for symbol in stock_symbols}
for _ in range(160):
for symbol in stock_symbols:
ticker = yf.Ticker(symbol) # <-- Use yfinance here
price_data_point = ticker.history(period="1d")["Close"].iloc[-1] # <-- Fetch the last closing price
price_data[symbol].append(price_data_point)
if len(price_data[symbol]) > 150:
price_data[symbol].pop(0)
for symbol in stock_symbols:
df = pd.DataFrame(price_data[symbol], columns=['Close'])
for period in [20, 80]:
ema_column_name = f'EMA_{period}'
df[ema_column_name] = calculate_ema(df['Close'], period)
if len(df) >= 80:
trade_on_crossover(df, game_name, symbol)
time.sleep(60)
today = datetime.today().weekday()
if today >= 5:
exit(0)
tech_stocks = ['AAPL', 'GOOGL', 'MSFT']
health_stocks = ['JNJ', 'MRK', 'PFE']
utility_stocks = ['NEE', 'DUK', 'D']
all_stocks = tech_stocks + health_stocks + utility_stocks
trade_multiple_stocks(all_stocks)
EOF