'Basic Trading strategy with python

I am trying to code a basic trading strategy call sell the winner and buy the loser. I have listed the three conditions I want to code in python. I am a newbie on financial analysis. Based on the below question, I decided to adopt this approach to achieve the end objective.

Question.

Suppose that you have 100 USD at the start t0 and invest 50% in the first stock and 50% in the second stock. Now, at time t1 (i.e., one week later), there can be three cases:

  1. if the return of the first stock is equal to the return of the second stock, you do not change the composition of your portfolio.

  2. if the return of the first stock is larger than the return of the second stock, you reduce the amount invested in the second stock by 3% and use the proceeds to purchase the first stock.

  3. if the return of the second stock is larger than the return of the first stock, you reduce the amount invested in the first stock by 3% and use the proceeds to purchase the second stock. then you move from t1 to t2 and apply again the same rule.

Below is my approach and implementation.

  1. start with 100 USD, invest 50% to both stock at week 1

  2. calculate stock return after week 1 investment

  3. create a portfolio to stock records of stocks

  4. check if the return of 1st stock is equal to the return of second stocks, if so leave portfolio composition

Data

import random
from datetime import datetime
import pandas as pd

pd.date_range(end = datetime.today(), periods = 10).to_pydatetime().tolist()
date = pd.date_range(start="2022-01-09",end="2022-01-18")
stock_a = random.choices(range(47, 50), k=10)
stock_b = random.choices(range(147, 150), k=10)
df = pd.DataFrame({'stockA': stock_a,'stockB': stock_b},  index=date)

print(df.head().to_dict())

{'index': {0: Timestamp('2022-01-09 00:00:00'),
  1: Timestamp('2022-01-10 00:00:00'),
  2: Timestamp('2022-01-11 00:00:00'),
  3: Timestamp('2022-01-12 00:00:00'),
  4: Timestamp('2022-01-13 00:00:00')},
 'stockA': {0: 48, 1: 49, 2: 48, 3: 49, 4: 48},
 'stockB': {0: 147, 1: 147, 2: 149, 3: 147, 4: 149}}



# Set the initial capital
initial_capital= float(100.0)
investment_pct = 0.5
stock_investment = initial_capital * investment_pct
#investment table. I invest 50% on both stock
portfolio = (df.iloc[:,1:]/df.iloc[:,1:].iloc[0]*50)
#add date
portfolio['Date'] = df.index

#Calculate Stock return 
portfolio['stockA_Return'] = portfolio['stockA'].pct_change()
portfolio['stockB_Return'] = portfolio['stockB'].pct_change()
#set index to data
portfolio.set_index('Date', inplace=True)

My output after investing 50%

             stockA      stockB     stockA_Return   stockB_Return
Date                
06-May-2022 50.000000   50.000000   0.000000    0.000000
29-Apr-2022 49.077804   48.696650   -0.018444   -0.026067
22-Apr-2022 55.024380   50.368044   0.121166    0.034323
15-Apr-2022 57.059572   49.763641   0.036987    -0.012000
08-Apr-2022 56.741573   50.584144   -0.005573   0.016488

I just want to implement the second step in the below question but I can't figure out how to do that. any suggestion or solution is greatly appreciated. please this is my first time asking question on SO



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source