I have a df consisting of monthly share prices. I was hoping to find the optimal buy price and sell price to maximize earnings (revenue - costs). From research, it appears Scipy Optimize is the best tool to use, however all the examples I've seen do not show it being used with a dataframe.
A previous question sort of covered this. but I couldn't get it working for me, as my buy and sell quantities will change depending on the price. Meaning I need to recalc the df fields.
Any help would be greatly appreciated!
import pandas as pd
import numpy as np
import math
import datetime
from scipy.optimize import minimize
df = pd.DataFrame({
'Time': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
'Price': [44, 100, 40, 110, 77, 109, 65, 93, 89, 73]})
# Create Empty Columns
df[['Qty', 'Buy', 'Sell', 'Cost', 'Rev']] = pd.DataFrame([[0.00, 0.00, 0.00, 0.00, 0.00]], index=df.index)
# Initial Values
buy_price = 50
sell_price = 100
# Set Values at Time 0
df.at[0, 'Qty'] = 0
df.at[0, 'Buy'] = np.where(df.at[0, 'Price'] < buy_price, min(30 - df.at[0, 'Qty'], 10), 0)
df.at[0, 'Sell'] = np.where(df.at[0, 'Price'] > sell_price, min(df.at[0, 'Qty'], 10), 0)
df.at[0, 'Cost'] = df.at[0, 'Buy'] * df.at[0, 'Price']
df.at[0, 'Rev'] = df.at[0, 'Sell'] * df.at[0, 'Price']
# Set Remaining Values
for t in range(1, len(df)):
df.at[t, 'Qty'] = df.at[t-1, 'Qty'] + df.at[t-1, 'Buy'] - df.at[t-1, 'Sell']
df.at[t, 'Buy'] = np.where(df.at[t, 'Price'] < buy_price, min(30 - df.at[t, 'Qty'], 10), 0)
df.at[t, 'Sell'] = np.where(df.at[t, 'Price'] > sell_price, min(df.at[t, 'Qty'], 10), 0)
df.at[t, 'Cost'] = df.at[t, 'Buy'] * df.at[t, 'Price']
df.at[t, 'Rev'] = df.at[t, 'Sell'] * df.at[t, 'Price']