Skip to content

Instantly share code, notes, and snippets.

@florinel-chis
Created September 13, 2023 11:15
Show Gist options
  • Save florinel-chis/c2152c7a0abc9ffbef32486acfba7a40 to your computer and use it in GitHub Desktop.
Save florinel-chis/c2152c7a0abc9ffbef32486acfba7a40 to your computer and use it in GitHub Desktop.
Buy 1 tesla share a day and TP at 10k backtesting 3 years
import pandas as pd
# Load the data from the CSV file
data = pd.read_csv("TSLA_3_years_data.csv")
# Initialize variables
total_shares = 0
cumulative_cost = 0.0
total_profit = 0.0
data['Yesterday_Close'] = data['Close'].shift(1)
data['Daily_Change_Percent'] = ((data['Close'] - data['Yesterday_Close']) / data['Yesterday_Close']) * 100
#print(data.tail(20))
# Iterate through each row in the dataframe
for _, row in data.iterrows():
open_price = row['Open'] # Assuming 'Open' is the name of the column with opening prices
#if row['Daily_Change_Percent'] < 0.00:
total_shares += 1 # Buy 1 share
cumulative_cost += open_price # Add to the total cost
close = row['Close']
profit = row['Close']*total_shares - cumulative_cost
#(0.1*cumulative_cost)
if profit > 10000:
date = row['Date']
print(f"Total Shares sold: {total_shares}",f"Profit: ${profit:.2f}",f"Date: {date}")
total_shares = 0
cumulative_cost = 0.0
total_profit += profit
# Calculate the average purchase price
average_price = cumulative_cost / total_shares
open_p_l = close*total_shares - cumulative_cost
print(f"Total Shares owned: {total_shares}")
print(f"Average Purchase Price: ${average_price:.2f}")
print(f"Total Realised Profit: ${total_profit:.2f}")
print(f"Open P/L: ${open_p_l:.2f}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment