Spaces:
Runtime error
Runtime error
| def simulate_trading(signals_data, initial_capital=1000, investment_per_buy=100): | |
| """ | |
| Simulates trading based on buy and sell signals. | |
| Parameters: | |
| - signals_data (pd.DataFrame): DataFrame with 'Close', 'Buy_Signal', and 'Sell_Signal'. | |
| - initial_capital (float): The initial capital at the start of the trading period. | |
| - investment_per_buy (float): The fixed amount in dollars to invest at each buy signal. | |
| Returns: | |
| - float: The value of the stock currently held at the end of the period. | |
| - float: The amount of cash remaining if any. | |
| """ | |
| cash = initial_capital | |
| holdings = 0 | |
| for _, row in signals_data.iterrows(): | |
| # Buy | |
| if row['Buy_Signal'] and cash >= investment_per_buy: | |
| shares_bought = investment_per_buy / row['Close'] | |
| holdings += shares_bought | |
| cash -= investment_per_buy | |
| # Sell | |
| if row['Sell_Signal'] and holdings > 0: | |
| shares_sold = holdings * 0.25 | |
| holdings -= shares_sold | |
| cash += shares_sold * row['Close'] | |
| # Calculate the value of the remaining stock holdings at the last known price | |
| final_stock_value = holdings * signals_data.iloc[-1]['Close'] | |
| return final_stock_value, cash | |
| # Example usage | |
| if __name__ == "__main__": | |
| # Assuming signals_data DataFrame exists with 'Close', 'Buy_Signal', 'Sell_Signal' | |
| signals_data = pd.DataFrame({ | |
| 'Close': [100, 105, 103, 108, 107], # Example close prices | |
| 'Buy_Signal': [True, False, True, False, False], | |
| 'Sell_Signal': [False, True, False, True, False] | |
| }, index=pd.date_range(start='2020-01-01', periods=5, freq='D')) | |
| final_stock_value, remaining_cash = simulate_trading(signals_data) | |
| print(f"Final Value of Stock Holdings: ${final_stock_value:.2f}") | |
| print(f"Remaining Cash: ${remaining_cash:.2f}") | |